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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more