Embedding Bitmaps and Images

To ensure that HTML content does not require an internet connection to retrieve data, images can be embedded into HTML as base64. Embedding an image in HTML as base64 requires loading the image and converting its information to base64.

Below is a complete example that demonstrates how to read an image file, convert it to a base64 string, and then embed it into an HTML document. Finally, it shows how to generate a PDF from this HTML using IronPDF.

Explanation:

  1. Image to Base64 Encoding:

    • encodeImageToBase64(filePath): A function that reads the image file and converts it to a base64 string asynchronously.
    • Uses fs.readFile to read the image file. If successful, converts the data to a base64 string and resolves it.
  2. HTML Content Setup:

    • createHtmlContent(base64Data): Constructs HTML content with the embedded base64 image data within an img tag.
  3. PDF Generation:

    • generatePdf(filePath): Main function that orchestrates the process by first calling encodeImageToBase64 and then createHtmlContent, followed by creating a PDF via IronPdf.
    • Uses IronPdf.PdfDocument.fromHtml to generate a PDF document from the HTML content.
    • Saves the generated PDF using pdf.saveAs.
  4. Execution:
    • Calls generatePdf with the path to the desired image file.

This script effectively combines reading an image, converting it to base64 for HTML embedding, and rendering a PDF using IronPDF.

Discover the Complete Example of Embedding Images in PDF with IronPDF for Node.js!

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?