"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Downloading Webpages As PDFs With PHP And JavaScript

Downloading Webpages As PDFs With PHP And JavaScript

Published on 2024-11-08
Browse:660

Downloading Webpages As PDFs With PHP And JavaScript

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!

Release Statement This article is reproduced at: https://dev.to/nifty-little-me/downloading-webpages-as-pdfs-with-php-and-javascript-56hh?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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