如何生成带样式的 PDF 并将其上传到服务器 (Jquery)

我正在尝试生成一个 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 文件是空的。我不知道为什么。


上传.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 文件保存在我的服务器上。


慕雪6442864
浏览 265回答 1
1回答

aluckdog

如果有人遇到同样的问题。我找到了解决方案。JS$("#printer").on("click",function(e){var element = document.getElementById('qrcode');var opt = {&nbsp; image:&nbsp; &nbsp; &nbsp; &nbsp; { type: 'jpeg', quality: 0.98 },&nbsp; html2canvas:&nbsp; { scale: 3 },&nbsp; jsPDF:&nbsp; &nbsp; &nbsp; &nbsp; { unit: 'cm', format: 'letter', orientation: 'landscape' }};html2pdf().from(element).set(opt).toPdf().output('datauristring').then(function (pdfAsString) {&nbsp; &nbsp; // The PDF has been converted to a Data URI string and passed to this function.&nbsp; &nbsp; // Use pdfAsString however you like (send as email, etc)!var arr = pdfAsString.split(',');pdfAsString= arr[1];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var data = new FormData();&nbsp; &nbsp; &nbsp; &nbsp; data.append("data" , pdfAsString);&nbsp; &nbsp; &nbsp; &nbsp; var xhr = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; &nbsp; xhr.open( 'post', 'upload.php', true ); //Post the Data URI to php Script to save to server&nbsp; &nbsp; &nbsp; &nbsp; xhr.send(data);&nbsp; &nbsp; &nbsp; &nbsp; })e.preventDefault();&nbsp; //stop the browser from following&nbsp; &nbsp; window.location.href = 'uploads/file.pdf';});上传.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 contentsif (strpos($bin, '%PDF') !== 0) {&nbsp; throw new Exception('Missing the PDF file signature');}# Write the PDF contents to a local filefile_put_contents('uploads/file.pdf', $bin);?>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript