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.
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Custom Authentication Login And Registration Using Laravel 8
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- Google Login or Sign In with Angular Application
- How to Convert MySQL Data to JSON using PHP
- How to change date format in PHP?
- Image Lazy loading Using Slick Slider
- Slick Slider Basic With Example
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- Slick Slider Center Mode With Example
- How to Scroll to an Element with Vue 3 and ?
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- Slick Slider Multiple Items With Example
Total Views: 539