phpwordpressdompdf

Images Not Displaying in PDF Generated using DOMPDF and WordPress


I'm working on a WordPress plugin where I generate a PDF using DOMPDF. The generation process works, but I'm running into an issue where the images aren't being displayed in the generated PDF.

Here's a brief overview of my implementation:

  1. I retrieve a series of images (meta values) linked with a post in WordPress.
  2. I construct an HTML string embedding these images.
  3. I pass this HTML string to DOMPDF to generate the PDF.

The PDF generates correctly, and all text contents are shown perfectly. However, the images are missing. I've already ensured that the images exist and the links are correct.

Here's a relevant snippet of my PHP code:

function my_generate_pdf_callback() {
    $response_data = array(
        'success' => true,
        'pdf_data' => '',
        'image_data' => array(),
        'html_content' => '',
        'error_message' => ''
    );

    try {
        require_once(plugin_dir_path(__FILE__) . 'dompdf/autoload.inc.php');
        $post_id = isset($_POST['post_id']) ? intval(sanitize_text_field($_POST['post_id'])) : 0;

        if ($post_id <= 0) {
            throw new Exception('Nieprawidłowy post_id');
        }

        $post_title = get_the_title($post_id);
        $post_date = get_the_date('Y-m-d', $post_id);

        $meta_pictures = array();

        for ($i = 1; $i <= 10; $i++) {
            $meta_key = 'picture_' . $i;
            $meta_value = get_post_meta($post_id, $meta_key, true);
            if (!empty($meta_value)) {
                $meta_pictures[] = $meta_value;
            }
        }

        $html_content = "
        <html>
            <head>
                <style>
                    body {
                        font-family: 'DejaVu Sans', sans-serif;
                    }
                </style>
            </head>
            <body>
                <h1>Tytuł posta: " . $post_title . "</h1>
                <p>Data utworzenia: " . $post_date . "</p>";

        foreach ($meta_pictures as $pic) {
            $image_src = wp_get_attachment_url($pic);
            if ($image_src) {
                $html_content .= "<img src='" . $image_src . "' width='42' height='42'>";
                $response_data['image_data'][] = $image_src;
            }
        }

        $html_content .= "</body></html>";

        $dompdf = new \Dompdf\Dompdf();
        $options = $dompdf->getOptions();
        $options->setIsRemoteEnabled(true);
        $dompdf->setOptions($options);


        $dompdf->loadHtml($html_content, 'UTF-8');
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $pdf_output = $dompdf->output();
        $response_data['pdf_data'] = base64_encode($pdf_output);
        $response_data['html_content'] = $html_content;

    } catch (Exception $e) {
        $response_data['success'] = false;
        $response_data['error_message'] = 'Error: ' . $e->getMessage() . ' File ' . $e->getFile() . ' Line ' . $e->getLine();
    }

    $response = new WP_REST_Response($response_data);
    $response->set_status(200);

    wp_send_json($response);
}
add_action('wp_ajax_my_generate_pdf', 'my_generate_pdf_callback');

I tried generating a PDF document containing embedded images using DOMPDF within a WordPress environment. Given that the images exist and the links are correct, I expected the images to be displayed within the generated PDF alongside the text content.

However, the actual result is a PDF document where all the text content displays perfectly, but the images are entirely missing. To troubleshoot this, I implemented a pre-validation step using JavaScript to ensure all image links were accessible before the PDF generation, and they were indeed valid. Despite this, the images still don't show up in the final PDF.

DomPDF version: 2-0-3


Solution

  • I managed to resolve the issue with the images not displaying in the generated PDF. The solution was to embed the images as base64 data URLs directly within the HTML content before passing it to DOMPDF. Here's the updated code snippet that worked for me:

            foreach ($meta_pictures as $pic) {
                $image_src = wp_get_attachment_url($pic);
                if ($image_src) {
                    $image_data = file_get_contents($image_src);
                    $html_content .= '<img src="data:image/png+xml;base64,' . base64_encode($image_data) . '" ...>';
                    $response_data['image_data'][] = $image_src;
                }
            }