我正在尝试使用 PDFMake 生成多个 PDF 服务器端。每个 PDF 都有一个特定部分,该部分在要生成的所有 PDF 中都是不变的,
general
。然后,该 general
部分由 line
分隔,然后将特定于该文档的信息加载到其下方。
这在第一个 PDF 上效果很好。然而,在第二次,布局就被打破了。我该如何解决这个问题?
"use strict";
const fs = require("fs");
const PdfPrinter = require("pdfmake");
const fonts = {
Helvetica: {
normal: "Helvetica",
bold: "Helvetica-Bold",
italics: "Helvetica-Oblique",
bolditalics: "Helvetica-BoldOblique",
},
};
const printer = new PdfPrinter(fonts);
const general = [{ text: "This is general text" }];
const first = [{ text: "This is the text for the first pdf" }];
const second = [{ text: "This is the text for the second pdf" }];
const line = [{canvas: [{ type: 'line', x1: 0, y1: 5, x2: 595-2*40, y2: 5, lineWidth: 2 }],margin: [ 0, 10, 0, 10 ]},];
let docDefinition = {
pageSize: "letter",
defaultStyle: {
font: "Helvetica"
}
};
docDefinition.content = [general,line,first];
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream('one.pdf'));
pdfDoc.end();
docDefinition.content = [general,line,second];
pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream('two.pdf'));
pdfDoc.end();
所以我在 GitHub issues page 上提出了一个问题,得到的答复是:
一个
变量只能使用一次来生成 PDF。docDefinition
虽然这可能是真的,但我确实通过使用仅包含 headerLine 的表格找到了足够的解决方法。这不是我的想法,但我不记得我从哪里得到它。
function line() {
//Usually one would use a canvas to draw the line
//{canvas: [{ type: 'line', x1: 0, y1: 5, x2: 595-2*40, y2: 5, lineWidth: 2 }],margin: [ 0, 10, 0, 0 ]},
//For some reason, that's not working and the layout just breaks
return {
table : {
headerRows : 1,
widths: ['100%'],
body : [
[''],
['']
]
},
layout : 'headerLineOnly'
}
}
然后您可以在
line()
中需要线条的任何位置使用 docDefinition
。
"use strict";
const fs = require("fs");
const PdfPrinter = require("pdfmake");
const fonts = {
Helvetica: {
normal: "Helvetica",
bold: "Helvetica-Bold",
italics: "Helvetica-Oblique",
bolditalics: "Helvetica-BoldOblique",
},
};
const printer = new PdfPrinter(fonts);
const general = [{ text: "This is general text" }];
const first = [{ text: "This is the text for the first pdf" }];
const second = [{ text: "This is the text for the second pdf" }];
let docDefinition = {
pageSize: "letter",
defaultStyle: {
font: "Helvetica"
}
};
docDefinition.content = [general,line(),first];
let pdfDoc = printer.createPdfKitDocument(docDefinition);
pdfDoc.pipe(fs.createWriteStream('one.pdf'));
pdfDoc.end();
我知道这已经很长一段时间了,但为了帮助其他人——解决这个问题的一个简单方法是让你的画布返回新对象。例如我有:
report.canvas.titleArt = {}
如果将该静态对象更改为返回对象的函数,它似乎工作正常:
report.canvas.titleArt = function() {
return {};
}