我有以下问题。
我使用js的pdf库来创建pdf。作为最后一步,我创建了一个uint8array:
const pdfBytes = await pdfDoc.save()
现在,我想在ajax的帮助下将这个pdfbytes发送到我的web服务器上的php.file。这个php文件应该从pdf字节数组中创建一个pdf,并将其附加到电子邮件中,然后发送到特定的电子邮件地址。
我把ajax调用编码成这样:
function sendWithAjax(pdfBytes, email) {
if (window.XMLHttpRequest) {
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else {
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "sendContractEmail.php", true);
const data = {bytes: pdfBytes, mail: email};
xmlhttp.send(data);
}
但是我如何对php.file进行编码以生成pdf并通过电子邮件发送呢?
我的php代码:
<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT') {
echo "this is a put request";
parse_str(file_get_contents("php://input"),$post_vars);
echo $post_vars['pdfBytes']." is pdfBytes";
?>
谢谢你的帮助!
我为同样的问题斗争了一个星期。最后我得到了结果。
第一个问题是将TypedArray Buffer(pdfBytes(转换为Base64
var data = new Uint8Array(pdfBytes);
var base64 = bufferToBase64(data); // cal function that convert TypedArray Buffer
//console.log(base64(;检查输出
var formData = new FormData();
formData.append("name", name);
formData.append("surname", surname);
formData.append("email", email);
formData.append("pdffile", base64);
var request = new XMLHttpRequest();
request.open("POST", "test.php");
request.send(formData);
发送到php
$first_name = $_POST['name']; // required
$last_name = $_POST['surname']; // required
$email_to = $_POST['email']; // required
$binarr=$_POST['pdffile'];
$email_from = 'sundsx@mailaddress.it';
$extension = 'pdf';
$FileName = str_replace("'", "_", $first_name);
$FileSurName = str_replace("'", "_", $last_name);
$filePath = $_SERVER['DOCUMENT_ROOT'].'/files/'.$FileName."_".$FileSurName.".".$extension;
# Decode the Base64 string, making sure that it contains only valid characters
$bin = base64_decode($binarr, true);
在这里查看你的$bin base64guru
if (strpos($bin, '%PDF') !== 0) {
throw new Exception('Missing the PDF file signature');
}
# Write the PDF contents to a local file
file_put_contents($filePath, $bin); // Goal!
享受轻松的生活