jQuery 在服务器上存储生成的 PDF 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29826687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:38:20  来源:igfitidea点击:

Storing generated PDF files on the server

jqueryajaxpdfjspdf

提问by b0w3rb0w3r

Using the jsPDFplugin, I am creating a .pdffile and generating a download based on a button click. I would like to save the file onto my server instead of initiating the download. So when the button is clicked I would like the file to be saved in :

使用该jsPDF插件,我正在创建一个.pdf文件并基于单击按钮生成下载。我想将文件保存到我的服务器上,而不是启动下载。因此,当单击按钮时,我希望将文件保存在:

/tmp/uploads/pdf/example.pdf

I am aware I need have to use Jquery.Ajaxto post the file to the server. However, looking at the documentation and I didn't see any support for .pdfas a datatype.

我知道我需要使用Jquery.Ajax将文件发布到服务器。但是,查看文档,我没有看到对.pdf作为数据类型的任何支持。

My code:

我的代码:

$(document).on("click", "#PDF", function () {
    var table = document.getElementById("result");
    var tbl = window.sessionStorage.getItem("tbl");
    var cols = [],
        data = [];

    function html() {
        var doc = new jsPDF('p', 'pt');
        var res = doc.autoTableHtmlToJson(table, true);
        doc.autoTable(res.columns, res.data);
        doc.save( tbl+".pdf");
    }
    html();
});

Based on this xml document savingexample I tried the following:

基于此xml 文档保存示例,我尝试了以下操作:

var pdfDocument = doc.save( tbl+".pdf");
        var pdfRequest = $.ajax({
              url: "/tmp/uploads/pdf",
              processData: false,
              data: pdfDocument
            });

This downloaded the file instead of saving it. How can I save the file?

这下载了文件而不是保存它。如何保存文件?

采纳答案by b0w3rb0w3r

I managed to fix this using FormData(), here's how I did it:

我设法使用 解决了这个问题FormData(),这是我的方法:

$(document).on("click", "#PDF", function () {
    var table = document.getElementById("result");
    var cols = [],
        data = [];

    function html() {
        var doc = new jsPDF('p', 'pt');
        var res = doc.autoTableHtmlToJson(table, true);
        doc.autoTable(res.columns, res.data);
        var pdf =doc.output(); //returns raw body of resulting PDF returned as a string as per the plugin documentation.
        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);

    }
    html();
});

upload.php

上传.php

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

The key part being var pdf =doc.output();where you want to get the raw pdf data.

关键部分是var pdf =doc.output();您想要获取原始 pdf 数据的位置。

回答by Nico

If your PDF contains binary data, you can get into problems if you try to transfer the PDF via string. I used the blob output format of jsPDF with success.

如果您的 PDF 包含二进制数据,则在尝试通过字符串传输 PDF 时可能会遇到问题。我成功地使用了 jsPDF 的 blob 输出格式。

var doc = new jsPDF();
// ... generate pdf here ...

// output as blob
var pdf = doc.output('blob');

var data = new FormData();
data.append('data' , pdf);

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (this.readyState == 4) {
    if (this.status !== 200) {
      // handle error
    }
  }
}

xhr.open('POST', 'upload.php', true);
xhr.send(data);

Your upload.php can then use the $_FILESarray in PHP

你的upload.php然后可以使用$_FILESPHP中的数组

<?php
if(!empty($_FILES['data'])) {
    // PDF is located at $_FILES['data']['tmp_name']
    // rename(...) it or send via email etc.
    $content = file_get_contents($_FILES['data']['tmp_name']);
} else {
    throw new Exception("no data");
}
?>

回答by mahmoud hemdan

javascript

javascript

doc = new jsPDF({
         unit: 'px',
         format: 'a4'
     });
    doc.addImage(img, 'JPEG', 20, 20);
    var data = {};
    var base64pdf = btoa(doc.output());
    $.ajax({
        url: 'WS/FileUploadHandler.ashx',
        type: 'post',
        async: false,
        contentType: 'application/json; charset=utf-8',
        data: base64pdf,
        dataType: 'json'
    });

FileUploadHandler.ashx

文件上传处理程序.ashx

public void ProcessRequest(HttpContext context)
    {
        var jsonString = String.Empty;
        context.Request.InputStream.Position = 0;
        using (var inputStream = new StreamReader(context.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }
        var byteArray = Convert.FromBase64String(jsonString);
        File.WriteAllBytes(@"C:\Users\mahmoud.hemdan\Downloads\testtest.pdf", byteArray);
    }

回答by Nitin

Using Asp.net/C# and jQuery: Based on @mahmoud hemdan answer, i did for my requirement. I did like below:

使用 Asp.net/C# 和 jQuery:基于@mahmoud hemdan 的回答,我满足了我的要求。我确实喜欢下面:

Javascript:

Javascript:

function createPDF(){
  var doc = new jsPDF('landscape');
  var u = $("#myCanvas").toDataURL("image/png", 1.0);
  doc.addImage(u, 'JPEG', 20, 20, 250, 150);
  var base64pdf = btoa(doc.output());
  $.ajax({
      url: 'ChartPDF.aspx?pdfinput=1',
      type: 'post',
      async: false,
      contentType: 'application/json; charset=utf-8',
      data: base64pdf,
      dataType: 'json'
  });
}

ChartPDF.aspx.cs code:

ChartPDF.aspx.cs 代码:

protected void Page_Load(object sender, EventArgs e)
    {
        var pdfinput= Request.QueryString["pdfinput"];
        if (pdfinput!= null)
        {
            var jsonString = string.Empty;
            HttpContext.Current.Request.InputStream.Position = 0;
            using (var inputStream = new StreamReader(Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            var byteArray = Convert.FromBase64String(jsonString);
            //Get your desired path for saving file
            File.WriteAllBytes(@"C:\ReportPDFs\Test.pdf", byteArray);
        }
    }

I called up the page without any querystring parameter and the page creates the graph(Code not given for drawing the graph as it is not part of the qs.) and after that it calles createPDF() function which result in reloading the page and saving the graph as pdf file on server. Later i use the file from path.

我在没有任何查询字符串参数的情况下调用了页面,页面创建了图形(没有给出用于绘制图形的代码,因为它不是 qs 的一部分。)然后它调用 createPDF() 函数,这导致重新加载页面并保存图形为服务器上的 pdf 文件。后来我使用路径中的文件。

回答by varsha dokhale

I have successfully save jspdf file in server using jspdf, javascript and php with png image

我已经使用 jspdf、javascript 和 php 和 png 图像成功地将 jspdf 文件保存在服务器中

here is the javascript

这是javascript

var doc = btoa(pdf.output());
var data = new FormData();
data.append("data", doc);
var xhr = new XMLHttpRequest();
xhr.open( 'post', 'data/test.php?name=' +name, true );
alert(data);
xhr.send(data);

And the php file

和 php 文件

if(!empty($_POST['data'])){ 
 $data = base64_decode($_POST['data']);
 //$data = $_POST['data'];
$name = $_GET['name'];
 $fname = $name."_bell_quote.pdf"; // name the file
 $file = fopen("../quote/" .$fname, 'w'); // open the file path
 fwrite($file, $data); //save data
 fclose($file);
 echo "Bell Quote saved";   
}
else {
 echo "No Data Sent";
}