Gaurav Kandpal
Gaurav Kandpal

Reputation: 1310

How to convert multiple images into single pdf using nodejs

I need to convert multiple images into a single PDF. I'm able to create PDF for one image. The problem comes when I have multiple images. How I can create multiple pages PDF.

Upvotes: 14

Views: 23116

Answers (3)

Binary
Binary

Reputation: 501

This is the proper way to do it:

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

Upvotes: 6

Gaurav Kandpal
Gaurav Kandpal

Reputation: 1310

I got my desired output by below code.

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

Upvotes: 19

Felix Fong
Felix Fong

Reputation: 985

You can use a library called html-pdf to convert your HTML template to a PDF file

Code:

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

Upvotes: 4

Related Questions