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:
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.
HTML Content Setup:
createHtmlContent(base64Data)
: Constructs HTML content with the embedded base64 image data within animg
tag.
PDF Generation:
generatePdf(filePath)
: Main function that orchestrates the process by first callingencodeImageToBase64
and thencreateHtmlContent
, followed by creating a PDF viaIronPdf
.- Uses
IronPdf.PdfDocument.fromHtml
to generate a PDF document from the HTML content. - Saves the generated PDF using
pdf.saveAs
.
- Execution:
- Calls
generatePdf
with the path to the desired image file.
- Calls
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!