Giter Site home page Giter Site logo

ultimateakash / puppeteer-html-pdf Goto Github PK

View Code? Open in Web Editor NEW
22.0 3.0 5.0 294 KB

HTML to PDF converter for Node.js

Home Page: https://www.npmjs.com/package/puppeteer-html-pdf

JavaScript 100.00%
html2pdf puppeteer html-pdf htmltopdf puppeteer-pdf html-pdf-node node-html-pdf puppeteer-html-pdf

puppeteer-html-pdf's Introduction

puppeteer-html-pdf

HTML to PDF converter for Node.js

NPM JavaScript Style Guide Known Vulnerabilities


Versions

Node.js puppeteer-html-pdf
>=20.0.0 v4.x
<20.0.0 v3.x

Installation

npm install puppeteer-html-pdf
const htmlPDF = new PuppeteerHTMLPDF();

Methods

htmlPDF.setOptions(options);
htmlPDF.getPage();
htmlPDF.create(content, callback);
htmlPDF.writeFile(pdfBuffer, filePath, callback);
htmlPDF.readFile(filePath, encoding, callback);
htmlPDF.setAutoCloseBrowser(flag);
htmlPDF.closeBrowser();
htmlPDF.closeBrowserTabs();

Usage

Example 1

const PuppeteerHTMLPDF = require("puppeteer-html-pdf");
const hbs = require("handlebars");

const htmlPDF = new PuppeteerHTMLPDF();
htmlPDF.setOptions({ format: "A4" });

const pdfData = {
  invoiceItems: [
    { item: "Website Design", amount: 5000 },
    { item: "Hosting (3 months)", amount: 2000 },
    { item: "Domain (1 year)", amount: 1000 },
  ],
  invoiceData: {
    invoice_id: 123,
    transaction_id: 1234567,
    payment_method: "Paypal",
    creation_date: "04-05-1993",
    total_amount: 8000,
  },
  baseUrl: "https://ultimateakash.com",
};
const html = await htmlPDF.readFile(__dirname + "/sample.html", "utf8");
const template = hbs.compile(html);
const content = template(pdfData);

try {
  const pdfBuffer = await htmlPDF.create(content);
  const filePath = `${__dirname}/sample.pdf`;
  await htmlPDF.writeFile(pdfBuffer, filePath);
} catch (error) {
  console.log("PuppeteerHTMLPDF error", error);
}

Example 2

const PuppeteerHTMLPDF = require("puppeteer-html-pdf");

const htmlPDF = new PuppeteerHTMLPDF();
const options = {
  format: "A4",
  path: `${__dirname}/sample.pdf`, // you can pass path to save the file
};
htmlPDF.setOptions(options);

const content = "<style> h1 {color:red;} </style> <h1>Welcome to puppeteer-html-pdf</h1>";

try {
  await htmlPDF.create(content);
} catch (error) {
  console.log("PuppeteerHTMLPDF error", error);
}

Example 3

const PuppeteerHTMLPDF = require("puppeteer-html-pdf");

const htmlPDF = new PuppeteerHTMLPDF();
const options = {
  width: "219mm",
  height: "297mm",
  margin: {
    left: "25px",
    right: "25px",
    top: "20px",
  },
  path: `${__dirname}/sample.pdf`, // you can pass path to save the file
  browserWSEndpoint: "wss://chrome.browserless.io?token=YOUR_TOKEN",
};
htmlPDF.setOptions(options);

const content = "https://www.google.com";

try {
  await htmlPDF.create(content);
} catch (error) {
  console.log("PuppeteerHTMLPDF error", error);
}

Example 4

const PuppeteerHTMLPDF = require("puppeteer-html-pdf");

const htmlPDF = new PuppeteerHTMLPDF();
htmlPDF.setOptions({ format: "A4", timeout: 60000 });
htmlPDF.setAutoCloseBrowser(false);

const urls = [
  "https://www.google.com",
  "https://www.yahoo.com",
  "https://www.bing.com",
  "https://www.yandex.com",
  "https://www.duckduckgo.com",
  "https://www.ask.com",
  "https://www.aol.com",
];
try {
  const pdfPromises = urls.map(async (url, index) => {
    const pdfBuffer = await htmlPDF.create(url);

    const filePath = `${__dirname}/PDF_${index + 1}.pdf`;
    await htmlPDF.writeFile(pdfBuffer, filePath);

    console.log(`Generated PDF from ${url}`);
  });

  await Promise.all(pdfPromises);
} catch (error) {
  console.log("PuppeteerHTMLPDF error", error);
} finally {
  await htmlPDF.closeBrowser();
}

Example 5

const PuppeteerHTMLPDF = require("puppeteer-html-pdf");

const htmlPDF = new PuppeteerHTMLPDF();
htmlPDF.setOptions({ format: "A4" });

const content1 = "https://www.google.com";
const content2 = "https://www.yahoo.com";

try {
  htmlPDF.setAutoCloseBrowser(false);
  const pdfBuffer1 = await htmlPDF.create(content1);
  const filePath1 = `${__dirname}/google.pdf`;
  await htmlPDF.writeFile(pdfBuffer1, filePath1);

  const pdfBuffer2 = await htmlPDF.create(content2);
  const filePath2 = `${__dirname}/yahoo.pdf`;
  await htmlPDF.writeFile(pdfBuffer2, filePath2);
} catch (error) {
  console.log("PuppeteerHTMLPDF error", error);
} finally {
  await htmlPDF.closeBrowser();
}

Options

Property Modifiers Type Description Default
displayHeaderFooter optional boolean Whether to show the header and footer. false
footerTemplate optional string HTML template for the print footer. Has the same constraints and support for special classes as PDFOptions.headerTemplate.
format optional PaperFormat letter.
headerTemplate optional string

HTML template for the print header. Should be valid HTML with the following classes used to inject values into them:

- date formatted print date

- title document title

- url document location

- pageNumber current page number

- totalPages total pages in the document

height optional string | number Sets the height of paper. You can pass in a number or a string with a unit.
landscape optional boolean Whether to print in landscape orientation. false
margin optional PDFMargin Set the PDF margins. undefined no margins are set.
omitBackground optional boolean Hides default white background and allows generating pdfs with transparency. false
pageRanges optional string Paper ranges to print, e.g. 1-5, 8, 11-13. The empty string, which means all pages are printed.
path optional string The path to save the file to. undefined, which means the PDF will not be written to disk.
preferCSSPageSize optional boolean Give any CSS @page size declared in the page priority over what is declared in the width or height or format option. false, which will scale the content to fit the paper size.
printBackground optional boolean Set to true to print background graphics. true
scale optional number Scales the rendering of the web page. Amount must be between 0.1 and 2. 1
timeout optional number Timeout in milliseconds. Pass 0 to disable timeout. 30_000
width optional string | number Sets the width of paper. You can pass in a number or a string with a unit.
headless optional boolean | string Sets Chromium launch mode. new
args optional array Sets Chromium flags mode. ['--no-sandbox', '--disable-setuid-sandbox']
authorization optional string HTTP header to be sent with every request.
headers optional { [key]: value } HTTP header to be sent with every request.
browserWSEndpoint optional string WS Endpoint(wss://chrome.browserless.io?token=YOUR_TOKEN).
executablePath optional string Executable path(C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe).

Format

The sizes of each format are as follows:

  • Letter: 8.5in x 11in

  • Legal: 8.5in x 14in

  • Tabloid: 11in x 17in

  • Ledger: 17in x 11in

  • A0: 33.1in x 46.8in

  • A1: 23.4in x 33.1in

  • A2: 16.54in x 23.4in

  • A3: 11.7in x 16.54in

  • A4: 8.27in x 11.7in

  • A5: 5.83in x 8.27in

  • A6: 4.13in x 5.83in

Margin

Property Modifiers Type
bottom optional string | number
left optional string | number
right optional string | number
top optional string | number

Linux Troubleshooting

Install chromium

sudo apt update
sudo apt install chromium

After chromium installation, if you still get missing dependencies issue. Install below dependencies.

sudo apt install ca-certificates fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils

https://pptr.dev/troubleshooting#chrome-headless-doesnt-launch-on-unix

puppeteer-html-pdf's People

Contributors

luisabarca avatar rjordan avatar ultimateakash avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

puppeteer-html-pdf's Issues

Issue still persists on ubuntu environment with alpine

          Issue still persists

I have used same dependencies in my docker file on ubuntu environment

Alpine image version : FROM node:14.17.6-alpine

Install necessary dependencies

for Puppeteer
RUN apk add --no-cache
chromium
nss
freetype
freetype-dev
harfbuzz
ca-certificates
ttf-freefont

In NODE JS i am using below code

const htmlPDF = new PuppeteerHTMLPDF();
        const htmloptions = {
            executablePath: '/usr/bin/chromium-browser',
            format: "A4",
            path: config.filepath + newFilename, // you can pass path to save the file
            headless: false
          };
          htmlPDF.setOptions(htmloptions);
          const htmlPdfContent = html;
            try {
                console.log("PDF PRINTED")
                //await htmlPDF.create(htmlPdfContent);
                htmlPDF.create(htmlPdfContent, (err, result) => {
                    if (err) {
                        logger.log(err, constants.logLevels.ERROR);
                        deferred.reject(err);
                    } else {
                        console.log(result)
                        deferred.resolve({ filePath: config.apiUrl + '/' + newFilename, fileName: newFilename });
                    }
                });
               
            } catch (error) {
                console.log("PuppeteerHTMLPDF error", error);
         }


It is showing nothing on server console and not printing any PDF and loader is continuously spinning

**Here is error showing on server console** 

**(node:24) UnhandledPromiseRejectionWarning: Error: Failed to connect to browser: Failed to launch the browser process! undefined

[47:47:0509/134018.681473:ERROR:browser_main_loop.cc(1485)] Unable to open X display.

TROUBLESHOOTING: https://pptr.dev/troubleshooting

at PuppeteerHTMLPDF.initializeBrowser (/app/node_modules/puppeteer-html-pdf/lib/index.js:143:13)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async PuppeteerHTMLPDF.create (/app/node_modules/puppeteer-html-pdf/lib/index.js:31:5)

(node:24) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)**

Note : same code is working fine on my windows machine.

[Question] Conditional header content?

Is there any way to provide conditional header content?

In my case, I want a logo and an invoice #, etc. at the top of every page.

On the first page, I want shipping details.

On subsequent pages, a partial header, but no shipping details.

I can see how to achieve headers and footers, but is there a way to set a portion of a header as "conditional" - such that it only shows on page 1?

Alternatively, is there any method to paginate before generation?

Does this work with ES6?

It's so weird to still see code that uses require instead of import. Even puppeteer, which this library depends on, is ES6 compatible. I tried using require but for whatever reason it's undefined.

ReferenceError: ReadableStream is not defined

ReferenceError: ReadableStream is not defined
at getReadableFromProtocolStream (/home/nanonino/lms/star-academy-content/node_modules/puppeteer-core/lib/cjs/puppeteer/common/util.js:241:5)
at CdpPage.createPDFStream (/home/nanonino/lms/star-academy-content/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Page.js:853:66)
at async CdpPage.pdf (/home/nanonino/lms/star-academy-content/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Page.js:857:26)
at async PuppeteerHTMLPDF.generatePDF (/home/nanonino/lms/star-academy-content/node_modules/puppeteer-html-pdf/lib/index.js:160:18)
at async PuppeteerHTMLPDF.create (/home/nanonino/lms/star-academy-content/node_modules/puppeteer-html-pdf/lib/index.js:48:23)
at async /home/nanonino/lms/star-academy-content/routes/services/common-service.js:764:33

const puppeteerHtmlToPdf = require('puppeteer-html-pdf');

let htmlPDF = new puppeteerHtmlToPdf();

            let option = {
                format: "A4",
                margin: {
                    top: '1in',
                    right: '0.1in',
                    bottom: '0in',
                    left: '0.1in',
                },
                displayHeaderFooter: true,
                footerTemplate: footerTpl,
                headerTemplate: headerTpl,
                args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'],                   
            }

            htmlPDF.setOptions(option);

            let pdfBuffer = await htmlPDF.create(htmlContent);

node v-16
how to solve this issue 

Example 2 gives me an error

[vite] Internal server error: /myfile.svelte:25:20 Unterminated string constant

   23 |      htmlPDF.setOptions(options);
   24 |
   25 |      const content = "<style> h1 {color:red;}
                             ^
   26 |   *{}</style> <h1>Welcome to puppeteer-html-pdf</h1>";
   27 |   (x2)

React 18

Is there a plan to get this package to work with react 18 with out needing to use npm legacy peers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.