【发布时间】:2017-07-13 03:53:40
【问题描述】:
在我的 node/express 应用程序中,我使用 node-html-pdf 创建了一个 pdf 文件:
exports.getTestPdf = async function(req, res) {
// set page format
const options = { format: 'A4' };
// define content
const html = `
<html>
<head>
<meta charset="utf8">
<title>PDF Test</title>
<style>
.page {
position: relative;
height: 90mm;
width: 50mm;
display: block;
page-break-after: auto;
margin: 50px;
overflow: hidden;
}
</style>
</head>
<body>
<div class="page">
Page 1
</div>
<div class="page">
Page 2
</div>
</body>
</html>
`;
// set header
res.set('Content-type', 'application/pdf');
// create and stream file to client
pdf.create(html).toStream(function(err, stream){
stream.pipe(res);
});
// check: the file is created with content when saved server side
// pdf.create(html, options).toFile('./pdf-test.pdf', function(err, res) {
// if (err) return console.log(err);
// console.log(res); // { filename: pathtofile/pdf-test.pdf' }
// });
}
此文件将在 Angular 2 前端接收。
服务:
@Injectable()
export class PdfService {
constructor (private http: Http) {}
getPdf (): any {
return this.http.get('api/test-pdf')
.map(res => res)
.catch(this.handleError);
}
}
控制器:
pdf(){
this.userService.getPdf().subscribe(
response => {
// create hidden dom element (so it works in all browsers)
let a = document.createElement("a");
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
var blob = new Blob([response._body], { type: 'application/pdf' });
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'MerapiExport.pdf';
a.click();
},
error => this.errorMessage = <any>error
);
}
当我通过按钮激活我的 pdf() 函数时,将下载一个空的 pdf 文件。任何想法为什么文件为空且没有内容?
【问题讨论】:
标签: node.js angular pdf express