Javascript 下载带有 filesaver.js 和 blob 的 pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33494377/
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-23 15:08:39  来源:igfitidea点击:

download a pdf with filesaver.js and blob

javascriptfilesaver.js

提问by madca0313

I'm trying to download a file with Filesaver.js. And when I try to do this with csv, it works fine. But I need to download a pdf now.

我正在尝试下载带有Filesaver.js. 当我尝试使用 csv 执行此操作时,它运行良好。但我现在需要下载pdf。

How can I do that? I use Filesaver.jswith a blob object, my code looks something like this:

我怎样才能做到这一点?我Filesaver.js与 blob 对象一起使用,我的代码如下所示:

var filename = "myfile.csv";
var s = "my csv text content";
var blob = new Blob([s], {type "text/csv;charset=utf-8"});
var filesaver = saveAs(blob,filename);

I'd like to know what kind of data type should I pass to the blob onject, when I'd like to download the pdf.

当我想下载pdf时,我想知道应该将哪种数据类型传递给blob onject。

回答by Ruslan López

Data type should be application/pdfof course.

数据类型application/pdf当然应该是。

The content should be on base64so the blob should start with

内容应该打开,base64所以 blob 应该以

data:application/pdf;base64,

As you can see in the jspdflibrary source code.

正如您在jspdf库源代码中所见

Enjoy the demo.

享受演示

回答by Przemek

PDF is completely another format and FileSaver's only mission is saving files.

PDF 完全是另一种格式,FileSaver 的唯一任务是保存文件。

You can use jsPDFlibrary to do that. This is how you could use it in your case:

您可以使用jsPDF库来做到这一点。这就是你可以在你的情况下使用它的方式:

var filename = "myfile.csv";
var s = "my csv text content";

var pdf = new jsPDF();
pdf.text(10, 10, s);
pdf.save(filename.replace(".csv", ".pdf"));

回答by Ado

 var blob = new Blob([response.data], {type: "application/pdf;charset=utf-8"});
 var blob = new Blob([response.data], {type: "text/plain;charset=utf-8"});

Both are ok,but header should be

两者都可以,但标题应该是

{responseType:"arraybuffer"}