简体   繁体   中英

How can I combine multiple webpages and get them as pdf?

I have multiple pages that I am getting after filling a form with puppeteer. I am currently using "page.printToPDF" api of puppeteer to obtain the webpage as a pdf but the problem is that I have multiple pages and I would like to combine all of them and get a single pdf. Is there anyway I can achieve this with puppeteer and javascript?

Here is an alternative solution, there are many packages for merging pdf files.

在此处输入图片说明

Here is how you can use one of the many pdf merging packages.

const PDFMerge = require('pdf-merge');
const files = [
    `${__dirname}/1.pdf`,
    `${__dirname}/2.pdf`
];
const finalFile = `${__dirname}/final.pdf`;

Here is how you can print multiple pages and then merge them.

// goto first page and save pdf file
await page.goto('http://example1.com', {waitUntil: 'networkidle'});
await page.pdf({path: files[0], format: 'A4', printBackground: true})

// goto first page and save pdf file
await page.goto('http://example2.com', {waitUntil: 'networkidle'});
await page.pdf({path: files[1], format: 'A4', printBackground: true})

// merge two of them and save to another file
await PDFMerge(files, {output: finalFile);

It's all about how you take advantages of your resources.

var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('https://www.google.co.in/', 'utf8');
var options = { 
  format: 'A4',
  "border": {
    "top": "0.2in",            // default is 0, units: mm, cm, in, px
    "bottom": "1in",
    "left": "0.1cm",
    "right": "0.1cm"
  },
};

pdf.create(html, options).toFile('./google.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/app/businesscard.pdf' } 
});

You have to install html-pdf after this use above code. for more information about to convert check link. https://www.npmjs.com/package/html-pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM