Node-Webkit Download PDF

Node-Webkit Download PDF

本文关键字:PDF Download Node-Webkit      更新时间:2023-09-26

我正在构建一个node-webkit应用程序,我从一个网站收到下载特定文件的请求。当我发起web服务调用时,我在response.body中返回文件。我试图使用fs api中的示例将pdf保存到我的本地文件夹,即:

(我正在传递响应。Body到data字段,并传递一个字符串'binary'来指定options下的编码)

var options = { encoding: 'binary' };
console.log('File name:' + fileName);
fileOperations.write(fileName, response.body, options, null);
在fileOperations:

module.exports = {
    write: function (filename, data, options, callback) {
    fs.writeFile(filename, data, options, function (err) {
      if (err) throw err;
      console.log('It''s saved!');
    });
  }
};

文件以正确的文件名、扩展名和文件大小保存到本地文件夹。然而,当在预览中打开时,每个页面都是空白的。我是否指定了错误的编码类型?

这听起来和我遇到的问题很相似。下载文件(不只是pdf)会产生奇怪的结果。这更可能是你的问题....不是fs函数。而不是使用内置的节点http的东西,我们选择使用Request库(npm Request),并以这种方式执行下载:

 request({
      method: 'GET',
      uri: baseUrl + '/api/v1/documents/versions/contents/doc33',
      headers: {"Access-Control-Allow-Origin": baseUrl, "Cookie": cookie}
    }, function (error, response, body) {
      var contentDisp = response.headers['content-disposition'].split('"');
      var ext = contentDisp[1].split('.')[1];
      // you can rename the downloaded file (temp) and add the proper extension here...
    }).pipe(fs.createWriteStream('temp')); // you can append a directory to the temporary name as well..
}
我想试试这个,看看它是否适合你。跨平台处理文件可能很困难。

从node-webkit应用程序导出pdf文件。首先你需要pdfkit;你可以在这里看到doc .

那么你只需要在js中要求它:

var pdfkit = require('pdfkit');
var fs = require('fs');

你必须像这样使用另存为框:从我的应用程序中的一个例子:

<button id="export">Export</button>
<input style="display:none" id="fileDialog" type="file" class="button small" accept=".pdf" nwsaveas="">

带导出功能:

$('#export').click(function(event) {
    chooseFile('#fileDialog');
});
function chooseFile(name)
{
    var chooser = $(name);
    chooser.change(function(event) {
        event.preventDefault();
        exp_to = $(this).val(); // where to export
            console.log($(this).val());
        exporT();
    });
        chooser.trigger('click');
}

最后=>

function exporT() // export() is already reserved
    {
        event.preventDefault();
        var doc = new pdfkit();
        doc.pipe(fs.createWriteStream(exp_to));
        doc.fontSize(20) // font size
            .text('your text here')//.whatyouwant()
            .end();
    }