如何使用Node.js将多个图像转换为单个PDF

14

我需要将多张图片合并成单个PDF。我可以为一张图片创建PDF。当我有多张图片时会遇到问题。请问如何创建多页PDF。

3个回答

19

我通过以下代码获得了所需的输出。

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()

1
我遇到了多图像问题,当我试图一次添加10张或50张图像时,它会崩溃并显示错误消息:“不完整或损坏的PNG文件”。有什么解决方案吗? - kbhaskar

6

这是正确的做法:

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();

4
你可以使用一个名为 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>

Live demo


感谢@Felix的回复,但我的问题是我必须将该PDF文件作为邮件附件发送,并且我的服务器是VPN服务器。因此,我正在寻找一个能够将图像转换为PDF的Node包,在那之后,我将在邮件中添加该PDF。因为服务器URL无法从外部访问。 - Gaurav Kandpal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接