如何使用PDFKIT(Node JS)将多个图像放入PDF?



我想要的是粘贴来自multilpe URL的多个图像。 为此,我下载并逐个附加到pdf 但问题是代码不是同步的。我是节点/javascript的新手。

这是我的代码和错误 请帮助我

var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://cdn.pixabay.com/ers90__340.png', 'google.png', function(){
console.log('done');
});
// Create a document
const doc = new PDFDocument();
// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('out.pdf'));
// Embed a font, set the font size, and render some text
doc
//.font('fonts/PalatinoBold.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('google.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
.scale(0.6)
.translate(470, -380)
.path('M 250,75 L 323,301 131,161 369,161 177,301 z')
.fill('red', 'even-odd')
.restore();
// Add some text with annotations
doc
.addPage()
.fillColor('blue')
.text('Here is a link!', 100, 100)
.underline(100, 100, 160, 27, { color: '#0000FF' })
.link(100, 100, 160, 27, 'http://google.com/');
// Finalize PDF file
doc.end();

错误:这是 IM 在运行时得到的结果 在下载图像之前,pdfkit 模块运行其代码 我不知道如何同步

internal/fs/utils.js:230
throw err;
^
Error: ENOENT: no such file or directory, open 'google.png'
at Object.openSync (fs.js:457:3)
at Object.readFileSync (fs.js:359:35)
at Function.open (/Users/sharan/node_modules/pdfkit/js/pdfkit.js:4432:19)
at PDFDocument.openImage (/Users/sharan/node_modules/pdfkit/js/pdfkit.js:4575:24)
at PDFDocument.image (/Users/sharan/node_modules/pdfkit/js/pdfkit.js:4476:22)
at Object.<anonymous> (/Users/sharan/Desktop/jsss/var8.js:32:5)
at Module._compile (internal/modules/cjs/loader.js:1144:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1164:10)
at Module.load (internal/modules/cjs/loader.js:993:32)
at Function.Module._load (internal/modules/cjs/loader.js:892:14) {
errno: -2,
syscall: 'open',
code: 'ENOENT',
path: 'google.png'
}

你可以试试这个....

ImagesUrlArr.forEach(function (el){
doc.addPage().image(el.data, {fit: [500, 400], align: 'center',valign: 'center'})
})

最新更新