使用node 8.11
和pdfmake 0.1.53
和pm2
。 pdfmake
给出了混合的响应,但是随机(几乎)失败(空白页)和成功(包含内容)。是临时存储错误吗?也尝试使用其他名称,但是在关闭并打开系统后第一次设置正确,然后又开始获得空白页后,得到空白页。
注意:直接下载并不总是会失败。最后附上了样本。
示例代码:
module.exports = {
generateReport: function(req, res){
var fonts = {
Roboto: {
normal: 'node_modules/fonts/Roboto-Regular.ttf',
bold: 'node_modules/fonts/Roboto-Medium.ttf',
italics: 'node_modules/fonts/Roboto-Italic.ttf',
bolditalics: 'node_modeules/fonts/Roboto-MediumItalic.ttf'
}
};
var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
var fs = require('fs');
var docDefinition = {
content: [
'First paragraph',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
]
};
var PdfPrinter = printer.createPdfKitDocument(docDefinition);
PdfPrinter.pipe(fs.createWriteStream('public/pdfs/document.pdf'));
PdfPrinter.end();
}
}
app.js
const express = require('express');
var path = require('path');
var app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use('/api', require('./routes/api'));
app.listen('3003', 'localhost');
console.log('Server started at port 3003');
api.js
const express = require('express');
const ctrl = require('../controllers/ctrl');
var router = express.Router();
router.route('/generate-report').get(ctrl.generateReport);
module.exports = router;
直接下载总是伴随着内容。
直接下载的示例代码:
module.exports = {
generateReportAndDownload: function(req, res){
var fonts = {
Roboto: {
normal: 'node_modules/fonts/Roboto-Regular.ttf',
bold: 'node_modules/fonts/Roboto-Medium.ttf',
italics: 'node_modules/fonts/Roboto-Italic.ttf',
bolditalics: 'node_modeules/fonts/Roboto-MediumItalic.ttf'
}
};
var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
var doc = printer.createPdfKitDocument({
info: {
title: 'PDF with External Image',
author: 'Matt Hagemann',
subject: 'PDF with External Image',
},
content: ['First paragraph',
'Another paragraph, this time a little bit longer to make sure'],
defaultStyle: {
fontSize: 11,
font: 'Roboto', // The font name was defined above.
lineHeight: 1.2,
}
})
doc.end()
res.setHeader('Content-type', 'application/pdf')
res.setHeader('Content-disposition', 'inline; filename="Example.pdf"')
doc.pipe(res)
}
}