# How to Load Images by Reference Instead of Embedding with html-to-pdfmake

> Easily load images by reference in html-to-pdfmake by setting imagesByReference true. Generate placeholder keys instead of embedding Base64 data for efficient PDF creation.

- Repository: [Aymeric/html-to-pdfmake](https://github.com/aymkdn/html-to-pdfmake)
- Tags: how-to-guide
- Published: 2026-02-26

---

**Set `imagesByReference: true` in the options object when calling `htmlToPdfMake()` to generate placeholder keys in a separate `images` map rather than embedding Base64 data directly in the content tree.**

The `aymkdn/html-to-pdfmake` library converts HTML strings into pdf-make document definitions. By default, it embeds image data directly into the content nodes, which can bloat your PDF when the same asset appears multiple times. Enabling reference mode allows you to externalize image handling and supply URLs, buffers, or custom descriptors during PDF generation.

## Enabling the imagesByReference Option

To switch from embedded mode to reference mode, pass `imagesByReference: true` in the options argument. According to the source code in [`index.js`](https://github.com/aymkdn/html-to-pdfmake/blob/main/index.js) (lines 15–18), this boolean flag toggles whether the parser stores raw image data or generates symbolic references.

```javascript
const htmlToPdfMake = require('html-to-pdfmake');

const html = `
  <p>Company Report</p>
  <img src="https://example.com/logo.png" alt="Company Logo">
`;

const result = htmlToPdfMake(html, { imagesByReference: true });

```

When active, the function returns an object with two properties instead of a plain content array:

- **`content`**: The standard pdf-make document definition nodes
- **`images`**: A map where keys are generated reference IDs (format: `img_ref_<random><index>`) and values are the original `src` or `data-src` strings

## How the Reference System Works

The implementation processes image references in three distinct phases as defined in [`index.js`](https://github.com/aymkdn/html-to-pdfmake/blob/main/index.js):

**1. Detection and Key Generation (lines 332–347)**

During HTML parsing, the converter intercepts every `<img>` element. If `imagesByReference` is enabled, it generates a unique reference key and assigns it to the node's `image` property instead of fetching or embedding the data.

**2. Source Storage**

The original URL (from the `src` attribute) or JSON descriptor (from `data-src`) is stored in an internal `this.imagesRef` accumulator. This keeps the binary data out of the content tree entirely.

**3. Result Construction (lines 662–672)**

After the HTML traversal completes, the library wraps the generated content and the accumulated image map into the final return structure:

```javascript
{
  content: [ /* pdf-make nodes */ ],
  images: {
    img_ref_ab12cd0: 'https://example.com/logo.png',
    img_ref_ab12cd1: 'https://example.com/chart.svg'
  }
}

```

This separation allows pdf-make to resolve images at build time rather than bake them into the definition.

## Supplying References to pdf-make

When building the PDF, you must pass the images map as the fourth argument to `pdfMake.createPdf()`, or include it in the document object depending on your pdf-make version:

```javascript
const pdfMake = require('pdfmake');

// Method 1: Four-argument signature
pdfMake.createPdf(result.content, null, null, result.images).download('report.pdf');

// Method 2: Object with content and images properties (modern pdf-make)
pdfMake.createPdf({
  content: result.content,
  images: result.images
}).download('report.pdf');

```

Using references reduces the document definition's memory footprint and allows you to supply images that are not Base64-encoded, such as remote URLs, local file buffers, or processed descriptors.

## Advanced: Using data-src for Complex Definitions

For scenarios requiring additional metadata (dimensions, fit settings, or custom processing), store a JSON descriptor in a `data-src` attribute:

```html
<img data-src='{"url":"https://example.com/header.png","width":200,"height":50}' />

```

The converter preserves the raw string in the images map. You can then parse and transform these entries before PDF generation:

```javascript
const doc = htmlToPdfMake(html, { imagesByReference: true });

// Transform JSON strings into pdf-make image objects
const processedImages = {};
for (const [key, value] of Object.entries(doc.images)) {
  try {
    processedImages[key] = JSON.parse(value);
  } catch (e) {
    processedImages[key] = value; // Fallback to raw URL
  }
}

pdfMake.createPdf(doc.content, null, null, processedImages).download();

```

## Summary

- **Enable reference mode** by setting `imagesByReference: true` in the options object passed to `htmlToPdfMake()`.
- **Receive separate objects**: The function returns `{content, images}` instead of a plain content array.
- **Implementation** is handled in [`index.js`](https://github.com/aymkdn/html-to-pdfmake/blob/main/index.js) at lines 15–18 (option declaration), 332–347 (image node processing), and 662–672 (result wrapping).
- **Supply to pdf-make** via the fourth argument of `createPdf()` or within the document object.
- **Use `data-src`** attributes to pass complex image descriptors as JSON strings for post-processing.

## Frequently Asked Questions

### What is the benefit of loading images by reference instead of embedding?

Loading images by reference keeps the PDF document definition lightweight. When the same image appears multiple times in the HTML, embedding creates duplicate Base64 strings in the content tree, significantly increasing file size. References allow pdf-make to resolve the image once during PDF generation and reuse it throughout the document, reducing memory usage and output size.

### Can I use remote URLs when imagesByReference is enabled?

Yes. The `imagesByReference` option specifically enables support for non-Base64 image sources. The converter stores the original URL string (from `src` or `data-src`) in the images map, which pdf-make can then resolve during the build process. This eliminates the need to download and encode images as Base64 before conversion.

### How do I handle images that require authentication or custom headers?

Store a JSON descriptor in the `data-src` attribute containing your metadata. The library preserves the raw string in the images map (e.g., `img_ref_xyz0: '{"url":"...", "headers":{...}}'`). Before calling `pdfMake.createPdf()`, iterate through the images object, parse the JSON, and transform each entry into a format pdf-make accepts, such as a buffer retrieved via an authenticated request.

### Does enabling imagesByReference change the return type of the function?

Yes. Without the option, `htmlToPdfMake()` returns a content array suitable for direct use as `pdfMake.createPdf({content: result})`. When `imagesByReference` is true, it returns an object with `content` and `images` properties. You must adjust your pdf-make integration to account for this structure, typically by passing the images map as the fourth argument or merging both properties into a single document object.