如何使用 FileSaver.js 在 Angularjs 中将以下内容保存为 PDF [英] How to save following content as PDF in Angularjs using FileSaver.js

查看:59
本文介绍了如何使用 FileSaver.js 在 Angularjs 中将以下内容保存为 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 FileSaver.js 将此内容保存为正确的 PDF

I am unable to save this content as proper PDF using FileSaver.js

这是 Angular 代码

this is Angular code

$http(
  { url:root.api_root+'/appointments/generatePDF/'+$route‌​Params.id,
    method:'GE‌​T'
}).then(function(r‌​es){ // 
    $log.log(res.data); 
    var blob = new Blob([res.data], { type: 'application/pdf' });
    window.open(res.data); 
    // saveAs(blob, 'file.pdf');
});

这是 TCPDF 后端代码

this is TCPDF Backend code

$pdf->Output("php://output", 'F'); 
echo file_get_contents("php://output");

推荐答案

下载PDF文件等二进制数据时,设置responseType属性很重要:

When downloading binary data such as PDF files, it is important to set the responseType property:

$http(
  { url:root.api_root+'/appointments/generatePDF/'+$route‌​Params.id,
    method:'GE‌​T',
    //IMPORTANT
    responseType: 'blob'
}).then(function(r‌​es){ // 
    $log.log(res.data);
    //var blob = new Blob([res.data], { type: 'application/pdf' });
    //window.open(res.data);
    var blob = res.data; 
    saveAs(blob, 'file.pdf');
});

如果省略 responseType 属性,XHR API 默认将数据处理为 UTF-8 文本.将数据解码为 UTF-8 文本 的过程会损坏二进制文件,例如 PDF 或图片.

If the responseType property is omitted, the XHR API defaults to processing the data as UTF-8 text. The process of decoding the data as UTF-8 text will corrupt binary files such as PDF or images.

有关更多信息,请参阅 MDN Web API 参考 - XHR ResponseType

For more information, see MDN Web API Reference - XHR ResponseType

这篇关于如何使用 FileSaver.js 在 Angularjs 中将以下内容保存为 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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