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.

// Import the required modules
const fs = require('fs');
const IronPdf = require('iron-pdf');

// Function to encode image file data to base64
function encodeImageToBase64(filePath) {
    return new Promise((resolve, reject) => {
        // Read the image file asynchronously
        fs.readFile(filePath, (err, data) => {
            if (err) {
                reject(err);
            } else {
                // Convert binary data to base64 string
                const base64Image = data.toString('base64');
                resolve(base64Image);
            }
        });
    });
}

// Function to create an HTML string with the base64 image
function createHtmlContent(base64Data) {
    // Construct HTML content with embedded base64 image
    return `
    <html>
        <body>
            <h1>Embedded Image</h1>
            <img 
                src="data:image/png;base64,${base64Data}"
                alt="Embedded Image" />
        </body>
    </html>
    `;
}

// Main logic to generate PDF from HTML with embedded image
async function generatePdf(filePath) {
    try {
        const base64Image = await encodeImageToBase64(filePath);
        const htmlContent = createHtmlContent(base64Image);

        // Create a PDF document from HTML content using IronPDF
        const pdf = await IronPdf.PdfDocument.fromHtml(htmlContent);

        // Save the resulting PDF to the desired location
        await pdf.saveAs('EmbeddedImage.pdf');

        console.log('PDF generated successfully.');
    } catch (error) {
        console.error('An error occurred:', error);
    }
}

// Call the function with the path to your image file
generatePdf('path/to/your/image.png');
// Import the required modules
const fs = require('fs');
const IronPdf = require('iron-pdf');

// Function to encode image file data to base64
function encodeImageToBase64(filePath) {
    return new Promise((resolve, reject) => {
        // Read the image file asynchronously
        fs.readFile(filePath, (err, data) => {
            if (err) {
                reject(err);
            } else {
                // Convert binary data to base64 string
                const base64Image = data.toString('base64');
                resolve(base64Image);
            }
        });
    });
}

// Function to create an HTML string with the base64 image
function createHtmlContent(base64Data) {
    // Construct HTML content with embedded base64 image
    return `
    <html>
        <body>
            <h1>Embedded Image</h1>
            <img 
                src="data:image/png;base64,${base64Data}"
                alt="Embedded Image" />
        </body>
    </html>
    `;
}

// Main logic to generate PDF from HTML with embedded image
async function generatePdf(filePath) {
    try {
        const base64Image = await encodeImageToBase64(filePath);
        const htmlContent = createHtmlContent(base64Image);

        // Create a PDF document from HTML content using IronPDF
        const pdf = await IronPdf.PdfDocument.fromHtml(htmlContent);

        // Save the resulting PDF to the desired location
        await pdf.saveAs('EmbeddedImage.pdf');

        console.log('PDF generated successfully.');
    } catch (error) {
        console.error('An error occurred:', error);
    }
}

// Call the function with the path to your image file
generatePdf('path/to/your/image.png');
JAVASCRIPT

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.