DEV Community

It's Just Nifty
It's Just Nifty

Posted on • Originally published at niftylittleme.com on

Converting HTML To PDF With HTML Button

Converting HTML to PDF Part 3 - Original Image

It's easy to convert HTML into a PDF with the help of libraries. Sometimes starting a download once you've navigated to a page is needed; however, let's give people the option to download the PDF or not. You can do that by adding HTML to your converter. Here's how.

HTML code (Example: index.php):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Html to Pdf</title>
</head>
<body>
    <?php
        $content = '<h1>Hello World</h1>';
        echo $content;
    ?>
    <main>
        <a href='html-php.php?download=true&content=<?php echo addslashes($content); ?>'>Create PDF</a>
    </main>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

PHP code (Example: html-php.php):

<?php
    require 'vendor/autoload.php';

    // reference the Dompdf namespace
    use Dompdf\Dompdf;


    if (isset($_GET['download'])) {
        $content = $_GET['content'];
        try {
            convertHTML($content);
        } catch ( Exception $e) {
            echo "some error:" . $e->getMessage();
        }
    }

    function convertHTML($content){

        // instantiate and use the dompdf class
        $dompdf = new Dompdf();
        $dompdf->loadHtml($content);

        // (Optional) Setup the paper size and orientation
        $dompdf->setPaper('A4', 'landscape');

        // Render the HTML as PDF
        $dompdf->render();

        ob_end_clean();

        // Output the generated PDF to Browser
        $dompdf->stream();
    }
    ?>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)