存储在服务器上生成的PDF文件 [英] Storing generated PDF files on the server

查看:1181
本文介绍了存储在服务器上生成的PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 jsPDF 插件,我创建一个的.pdf 文件基础上产生一个按钮点击下载。我想将文件保存到启动下载我的​​服务器来代替。因此,当单击该按钮,我想将文件保存在:

Using the jsPDF plugin, I am creating a .pdf file 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 :

/tmp/uploads/pdf/example.pdf

我知道我需要必须使用 Jquery.Ajax 发布文件到服务器。然而,看着文件,我没有看到的.pdf 作为一种数据类型的支持。

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

我的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();
});

在此基础上 XML文档,节省例如

我尝试以下

Based on this xml document saving example I tried the following:

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?

推荐答案

我管理这个用修复 FORMDATA(),这里是我如何做的:

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

$(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的

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";
}

关键的部分是 VAR PDF = doc.output(); 要获取原始PDF数据。

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

这篇关于存储在服务器上生成的PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆