【发布时间】:2021-04-29 20:19:57
【问题描述】:
我有一个 PDF 文件,我想使用 NodeJS 将其读入内存。理想情况下,我想使用base64 对其进行编码以进行传输。但不知何故,read 函数似乎没有读取完整的 PDF 文件,这对我来说毫无意义。原始 PDF 是使用 pdfKit 生成的,可以使用 PDF 阅读器程序查看。
原始文件test.pdf 的磁盘空间为 90kB。但是,如果我将其读取并写入磁盘,则只有 82kB 并且新的 PDF test-out.pdf 不行。 pdf查看器说:
无法打开文档。 pdf文档已损坏。
base64 编码因此也不能正常工作。我使用这个webservice 对其进行了测试。有人知道为什么以及这里发生了什么吗?以及如何解决。
我已经找到this 的帖子了。
fs = require('fs');
let buf = fs.readFileSync('test.pdf'); // returns raw buffer binary data
// buf = fs.readFileSync('test.pdf', {encoding:'base64'}); // for the base64 encoded data
// ...transfer the base64 data...
fs.writeFileSync('test-out.pdf', buf); // should be pdf again
编辑 MCVE:
const fs = require('fs');
const PDFDocument = require('pdfkit');
let filepath = 'output.pdf';
class PDF {
constructor() {
this.doc = new PDFDocument();
this.setupdocument();
this.doc.pipe(fs.createWriteStream(filepath));
}
setupdocument() {
var pageNumber = 1;
this.doc.on('pageAdded', () => {
this.doc.text(++pageNumber, 0.5 * (this.doc.page.width - 100), 40, {width: 100, align: 'center'});
}
);
this.doc.moveDown();
// draw some headline text
this.doc.fontSize(25).text('Some Headline');
this.doc.fontSize(15).text('Generated: ' + new Date().toUTCString());
this.doc.moveDown();
this.doc.font('Times-Roman', 11);
}
report(object) {
this.doc.moveDown();
this.doc
.text(object.location+' '+object.table+' '+Date.now())
.font('Times-Roman', 11)
.moveDown()
.text(object.name)
.font('Times-Roman', 11);
this.doc.end();
let report = fs.readFileSync(filepath);
return report;
}
}
let pdf = new PDF();
let buf = pdf.report({location: 'athome', table:'wood', name:'Bob'});
fs.writeFileSync('outfile1.pdf', buf);
【问题讨论】:
标签: javascript node.js pdf file-io node-pdfkit