DEV Community

It's Just Nifty
It's Just Nifty

Posted on • Originally published at niftylittleme.com on

2

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →