Menu Close

Create PDF from HTML using Node Js

htmlto-pdf

Here, we will see how to create a PDF from HTML using Node.js. with the puppeteer library. Here’s a simple example to get you started:

Initialize a new Node.js project:

npm init -y 

Install the puppeteer library:

npm install puppeteer 

Create a JavaScript file (e.g., createPDF.js) and add the following code:

const puppeteer = require('puppeteer');

async function createPDF() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Your HTML content goes here
  const htmlContent = `
    <html>
    <head>
      <title>My PDF</title>
    </head>
    <body>
      <h1>Hello, this is an example HTML</h1>
      <p>Replace this with your actual HTML content</p>
    </body>
    </html>
  `;

  await page.setContent(htmlContent);

  // Generate PDF
  await page.pdf({
    path: 'output.pdf',
    format: 'A4',
  });

  await browser.close();

  console.log('PDF generated successfully!');
}

createPDF();
 

Replace the htmlContent variable with your actual HTML content.

Run the script:

node createPDF.js 

This script uses puppeteer to launch a headless browser, create a new page, set the HTML content, and generate a PDF file named output.pdf in your project directory.

Feel free to customize the HTML content and adjust the script according to your specific needs.

Posted in NodeJs, Web Technologies

You can also read...