我需要将图像转换为PDF。我可以为一张图像创建PDF。当我有多张图片时,问题就来了。如何创建多页PDF。
答案 0 :(得分:3)
您可以使用名为html-pdf
的库将HTML模板转换为PDF文件
代码:
server.js
const express = require('express');
const app = express();
const ejs = require('ejs');
const htmlPdf = require('html-pdf');
const fs = require('fs');
const path = require('path');
const images = [
'https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&h=350',
'https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&h=350',
'https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&h=350',
];
app.get('/', (req, res) => {
fs.readFile(path.resolve(`${__dirname}/views/template.ejs`), 'utf-8', (error, content) => {
if(error){
console.log(error);
}else{
const html = ejs.render(content, {
images,
});
htmlPdf.create(html).toStream(function(err, stream){
stream.pipe(res);
});
}
});
});
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
views/template.ejs
<html>
<body>
<h1>Cat images</h1>
<ul>
<% images.forEach(image => { %>
<img src="<%- image%>" />
<% }) %>
</ul>
</body>
</html>
答案 1 :(得分:3)
我通过以下代码获得了所需的输出。
PDFDocument = require('pdfkit');
fs = require('fs');
doc = new PDFDocument
//Pipe its output somewhere, like to a file or HTTP response
//See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'))
//Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('./test.jpg', {
fit: [500, 400],
align: 'center',
valign: 'center'
});
doc.addPage()
.image('./1.png', {
fit: [500,400],
align: 'center',
valign: 'center'
});
doc.end()
答案 2 :(得分:0)
这是正确的方法:
var pdf = new (require('pdfkit'))({
autoFirstPage: false
});
var img = pdf.openImage('./myImage.jpg');
pdf.addPage({size: [img.width, img.height]});
pdf.image(img, 0, 0);
pdf.end();