Как создать PDF со стилем и загрузить его на сервер (Jquery) - PullRequest
1 голос
/ 11 ноября 2019

Я пытаюсь сгенерировать файл PDF, загрузить его на сервер и НЕ загружать его напрямую (локально).

Поэтому я попробовал JsPdf, но проблема с Jspdf заключается в том, что он не сохраняет мою таблицу стилей.

Затем я попробовал Html2Pdf (это также работает с моей таблицей стилей), но я не могу отправить данные в файл «upload.php». Я не могу найти синтаксис вывода для html2pdf.

JS:

$("#printer").on("click",function(e){

var element = document.getElementById('qrcode');

html2pdf().from(element).toPdf().outputPdf().then(function(pdf) {
    //Convert to base 64


        var data = new FormData();
        data.append("data" , pdf);
        var xhr = new XMLHttpRequest();
        xhr.open( 'post', 'upload.php', true ); //Post to php Script to save to server
        xhr.send(data);


        })

});




Мой PDF-файл на сервере пуст. И я не знаю почему.

upload.php:

<?php
if(!empty($_POST['data'])){
    $data = $_POST['data'];
    $fname = "test.pdf"; // name the file
    $file = fopen("uploads/" .$fname, 'w'); // open the file path
    fwrite($file, $data); //save data
    fclose($file);
} else {
    echo "No Data Sent";
}
?>

Я был бы очень признателен за любую помощь.

Просто нужно сохранить сгенерированный файл PDF на моем сервере.

1 Ответ

0 голосов
/ 11 ноября 2019

Если у кого-то есть такая же проблема. Я нашел решение.

JS


$("#printer").on("click",function(e){

var element = document.getElementById('qrcode');

var opt = {

  image:        { type: 'jpeg', quality: 0.98 },
  html2canvas:  { scale: 3 },
  jsPDF:        { unit: 'cm', format: 'letter', orientation: 'landscape' }
};

html2pdf().from(element).set(opt).toPdf().output('datauristring').then(function (pdfAsString) {
    // The PDF has been converted to a Data URI string and passed to this function.
    // Use pdfAsString however you like (send as email, etc)!

var arr = pdfAsString.split(',');
pdfAsString= arr[1];    

        var data = new FormData();
        data.append("data" , pdfAsString);
        var xhr = new XMLHttpRequest();
        xhr.open( 'post', 'upload.php', true ); //Post the Data URI to php Script to save to server
        xhr.send(data);

        })

e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.pdf';

});

upload.php

<?php
$data = $_POST['data'];
$b64 = $data;

# Decode the Base64 string, making sure that it contains only valid characters
$bin = base64_decode($b64, true);

# Perform a basic validation to make sure that the result is a valid PDF file
# Be aware! The magic number (file signature) is not 100% reliable solution to validate PDF files
# Moreover, if you get Base64 from an untrusted source, you must sanitize the PDF contents
if (strpos($bin, '%PDF') !== 0) {
  throw new Exception('Missing the PDF file signature');
}

# Write the PDF contents to a local file
file_put_contents('uploads/file.pdf', $bin);
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...