javascript 从 JSON 创建可下载的 pdf 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26677904/
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
Create downloable pdf file from JSON
提问by Joe Lewis
Basically, the issue I'm experiencing is I have queried to the server to return a pdf file which is returned in JSON format.
基本上,我遇到的问题是我已向服务器查询以返回以 JSON 格式返回的 pdf 文件。
I have tried to create a HTML element to auto download the pdf (this is not the issue), the issue is the pdf downloaded can not be opened because it fails and reports an error, for example in Adobe Reader:
我尝试创建一个 HTML 元素来自动下载 pdf(这不是问题),问题是下载的 pdf 无法打开,因为它失败并报告错误,例如在 Adobe Reader 中:
"Adobe reader could not open 'test.pdf' because is either not supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)"
“Adobe 阅读器无法打开‘test.pdf’,因为文件类型不受支持或文件已损坏(例如,它作为电子邮件附件发送但未正确解码)”
I'm working with AngularJS to make the ajax call to the server to get the JSON object and then try to format it and download it:
我正在使用 AngularJS 对服务器进行 ajax 调用以获取 JSON 对象,然后尝试对其进行格式化并下载它:
...
var pdf = pdfservice.get({id:pdfId});
console.log(pdf);
pdf.$promise.then(function(data){
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment/pdf;charset=utf-8,' + encodeURI(data),
target: '_self',
download:'test.pdf'
})[0].click();
});
...
UPDATE
更新
Using the $http service from Angular and with the same code, it downloads the pdf but it's empty, so maybe it could be an issue of encoding or formating the json object...
使用来自 Angular 的 $http 服务并使用相同的代码,它下载 pdf 但它是空的,所以可能是编码或格式化 json 对象的问题......
...
$http({ method: 'GET', url: 'http://www.testweb.com/pdf/1')
.success(function(data) {
console.log(data);
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment/pdf;charset=utf-8,' + encodeURI(data),
target: '_self',
download:'test.pdf'
})[0].click();
});
...