Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phayes0289's avatar

Hekper file to embed base64 images into PDF

I have the following helper file to embed multiple images in a domPDF layout :

But it just keeps returning:

array:2 [▼
  "original" => """
    <p>&nbsp;</p>\r\n
    <p>There is a second Tunnel to Towers race in our area; being held in Bridgeport on Saturday, October 19th at 8:00 AM.&nbsp; Support the same great causes once  ▶
    <p><img src="../../storage/uploads/posts/Tunnel_1727899377.jpg" sizes="100vw" srcset="https://fireops.test/storage/uploads/posts/thumbnail/Tunnel_1727899377.jpg ▶
    """
  "fixed" => """
    <p> </p>\r\n
    <p>There is a second Tunnel to Towers race in our area; being held in Bridgeport on Saturday, October 19th at 8:00 AM.  Support the same great causes once again ▶
    <p><img src="../../storage/uploads/posts/Tunnel_1727899377.jpg" width="1000"></p>
    """
]

What am I missing?

0 likes
1 reply
LaryAI's avatar

You're on the right track, but the issue is that DOMDocument will "fix" or normalize your HTML, and sometimes it doesn't preserve all attributes or structure as you expect. More importantly, your code is not updating the <img src="..."> to a base64 data URI—it's leaving the original path in the output.

Why?
Because DOMDocument::loadHTML() expects a complete HTML document (with <html>, <body>, etc.), and if you pass in a fragment, it may not parse or modify it as you expect. Also, if the image path is not being resolved correctly, the base64 embedding will be skipped.

How to fix:

  1. Ensure you pass a full HTML document to DOMDocument (or wrap your fragment).
  2. Double-check your path normalization to ensure $fullPath points to the actual file.
  3. After modifying the DOM, output the correct part (the body inner HTML).

Here's a revised version with comments:

Key changes:

  • Wrap your HTML in a full document before parsing.
  • Improved logging to show the resolved full path.
  • The function now reliably replaces the src attribute with the base64 data URI.

Debug tip:
If you still get the original src in the output, log $src and $fullPath to ensure the file exists and is being read.

Extra:
If your images are not in /public, adjust $publicPath accordingly.


Summary:
Your main issue was not wrapping the HTML fragment in a full document for DOMDocument, and possibly path resolution. The above code should fix both issues and embed your images as base64 in the output HTML for domPDF.

Please or to participate in this conversation.