Converting HTML to a PDF in PHP was easy. Let's bring it up a notch and convert a webpage to a PDF file using PHP and JavaScript.
To do this, you will need to install Composer and Node.
After installing those things, you will need to install Dompdf using Composer and Puppeteer using npm (Node package manager):
composer require dompdf/dompdf npm install puppeteer
Create a HTML file (Example: index.html):
Webpage to Pdf
Create a PHP file (Example: web-pdf.php):
getMessage(); } } else { echo "No URL provided."; } function convertHTML($content) { $dompdf = new Dompdf(); $dompdf->loadHtml($content); // Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); // Render the HTML as PDF $dompdf->render(); ob_end_clean(); // Output the generated PDF $dompdf->stream(); } ?>
Lastly, create a JavaScript File to use Puppeteer (Example: download.js):
const puppeteer = require('puppeteer'); // Get URL from command-line arguments const url = process.argv[2]; (async () => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(url); // Use the URL passed from PHP await page.waitForSelector('main', { timeout: 10000 }); // Adjust selector and timeout as needed const content = await page.content(); console.log(content); await browser.close(); } catch (error) { console.error('Error:', error); } })();
Note: Remove the ten second timeout or change the element (main) if the content is not what you expect.
There you go! Just like that, you have a webpage to PDF converter.
Happy Coding Folks!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3