I have a problem with a php generated pdf file. The generation of the pdf works very fine. After I saved the file to my webserver i can download it and open it with my Mac or with Browsers like Edge Chrome and Firefox. Only if i open the file with Adobe Acrobat Reader it didnt open the file.
Error: An Error occured by opening this file. The file is damaged and cant be repaired.
I have created the file with javascript and a little php. In JS i used the libary pdfLib to create the pdf File.
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
.
.
...changes in the pdf File...
.
.
const pdfBytes = await pdfDoc.save();
const dateOfToday = getDateofToday();
const dateTimeStamp = new Date().getTime();
const fileName = "Vertrag_von_" + dateOfToday + "_ID_" + dateTimeStamp + ".pdf";
sendWithAjax(pdfBytes, studio[4], answers["email"], fileName, answers["telenummer"]);
function sendWithAjax(pdfBytes, studioMail, customerMail , fileName, customerPhoneNumber) {
pdfBytes = bytesToBase64(pdfBytes);
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);
var data = new FormData();
data.append("byte", JSON.stringify(pdfBytes));
data.append("studioMail", JSON.stringify(studioMail));
data.append("customerMail", JSON.stringify(customerMail));
data.append("fileName", JSON.stringify(fileName));
data.append("customerPhoneNumber", JSON.stringify(customerPhoneNumber));
xmlhttp.send(data);
}
After the creation of the pdf file in JS i send the UInt8_Array and other informations with the help of ajax to my php file.
In the php.file i used following code to decode the Uint8_Array to a Base64 string and saved it in a file on my webserver.
if(!empty($_POST['byte'])){
$data = json_decode($_POST['byte']);
$fileName = json_decode($_POST['fileName']);
$studioMail = json_decode($_POST['studioMail']);
$customerMail = json_decode($_POST['customerMail']);
$customerPhoneNumber = json_decode($_POST['customerPhoneNumber']);
if (!empty($data)) {
// Detects if there is base64 encoding header in the string.
// If so, it needs to be removed prior to saving the content to a phisical file.
if (strpos($data, ',') !== false) {
@list($encode, $data) = explode(',', $data);
}
$base64data = base64_decode($data, true);
$pdf = fopen ('contractPDFs/'.$fileName ,'w');
fwrite ($pdf,$base64data);
fclose ($pdf);
}
echo "Contract saved";
sendEMailToStudio($fileName, $studioMail, $customerMail, $customerPhoneNumber);
sendEMailToCustomer($customerMail);
} else {
echo "No Data Sent";
}
Can somebody help me by my problem and explain me why i cant open the pdf file with Adobe Acrobat Reader?
Thanks