User Agents

Web browsers and everyday web tech, explained

Embed Images in PDFs with Pug, Node.js & Headless Chrome

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to generate PDFs with images embedded directly into them using Pug (a template engine), Node.js, and headless Chrome (via Puppeteer). Instead of linking to external images (which may break or slow down loading), you'll embed them as base64 data URIs or by using file paths that Chrome can access locally. By the end, you'll have a reusable Node.js script that renders a Pug template with images and outputs a fully self-contained PDF.

What You'll Need

  • Node.js installed (version 12 or later recommended)
  • npm (comes with Node.js)
  • A basic understanding of JavaScript and HTML
  • An image file (JPEG, PNG, SVG, etc.) you want to embed

Step-by-Step

  1. Set up your project
    Create a new directory and initialize it: mkdir pdf-embed && cd pdf-embed && npm init -y
  2. Install required packages
    Run: npm install pug puppeteer. Puppeteer downloads a compatible version of Chrome automatically.
  3. Create a Pug template
    Create a file named template.pug with a simple HTML structure. For example:
    doctype html
    html
      head
        title My PDF
        style
          body { font-family: Arial; }
          img { max-width: 100%; }
      body
        h1 Embedded Image Example
        p This image is embedded directly into the PDF.
        img(src=imageSrc alt="Embedded Image")
  4. Write the Node.js script
    Create a file named generate.js. This script will compile the Pug template with data (including the image source) and then use Puppeteer to convert the resulting HTML to PDF.
  5. Embed the image as a base64 data URI
    In your script, read the image file, convert it to base64, and construct a data URI. For example:
    const fs = require('fs');
    const path = require('path');
    const pug = require('pug');
    const puppeteer = require('puppeteer');
    
    // Read image and encode as base64
    const imagePath = path.join(__dirname, 'sample.jpg');
    const imageBase64 = fs.readFileSync(imagePath).toString('base64');
    const imageSrc = `data:image/jpeg;base64,${imageBase64}`;
    
    // Compile Pug template
    const template = pug.compileFile('template.pug');
    const html = template({ imageSrc: imageSrc });
  6. Generate the PDF with Puppeteer
    Continue the script to launch headless Chrome, create a page, set the HTML content, and generate the PDF:
    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.setContent(html, { waitUntil: 'networkidle0' });
      await page.pdf({ path: 'output.pdf', format: 'A4' });
      await browser.close();
      console.log('PDF generated successfully!');
    })();
  7. Run the script
    Execute node generate.js in your terminal. You should see a success message and an output.pdf file in your project directory.
  8. Verify the PDF
    Open output.pdf with any PDF viewer. The image should appear exactly as in the HTML. If you want to confirm it's embedded (not linked), try opening the PDF without internet access—it will still display.

Common Mistakes

  • Using relative paths for images – If you use src="/images/pic.jpg" in Pug, Chrome may not resolve it because there's no server. Always use absolute file paths or data URIs.
  • Forgetting to wait for images to load – If your images are large or loaded asynchronously, the PDF may be generated before they finish loading. Use waitUntil: 'networkidle0' to ensure all resources are loaded.
  • Not encoding the image correctly – For PNG, use data:image/png;base64,; for JPEG, use data:image/jpeg;base64,. Using the wrong MIME type can cause the image not to display.
  • Using page.setContent with a large HTML string – If your HTML is huge, it may slow down. It's fine for most cases, but for very large documents, consider using page.goto with a local server.

Tips

  • Use SVG for vector graphics – SVG images can be embedded as data URIs and scale perfectly in PDFs without losing quality.
  • Compress images before embedding – Base64 encoding increases file size by about 33%. Compress your images beforehand to keep the PDF size reasonable.
  • Set print options – You can customize margins, page size, and print background using Puppeteer's page.pdf() options. For example, { printBackground: true } to include background colors.
  • Use a local file path instead of base64 – If you'd rather not inline the image, you can use file:// URLs in the src attribute, but ensure Chrome has access to the file. This is simpler for local development but makes the PDF dependent on the file being present.
  • Cache the compiled template – If you generate many PDFs, compile the Pug template once and reuse it to improve performance.

Troubleshooting

  • Image not showing in PDF – Check the data URI in the generated HTML. Open the HTML in a browser to see if the image loads. If not, verify the MIME type and that the base64 string is correct.
  • PDF is blank – Ensure that page.setContent is called before page.pdf. Also, check that your HTML has a proper doctype and body content.
  • Chrome fails to launch – If Puppeteer can't launch Chrome, try installing missing dependencies on Linux: sudo apt-get install gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils
  • Images load slowly or not at all – If you're using external URLs, Chrome may block them due to CORS or network issues. Embed them as base64 to avoid this.
  • PDF has extra blank pages – Adjust the page.pdf options: set preferCSSPageSize: true if your template has CSS page size, or manually set width and height.

Frequently Asked Questions

Can I embed multiple images in one PDF?

Yes, simply include multiple img tags in your Pug template, each with its own data URI or file path. Generate the data URIs for each image and pass them as an array or object to the template.

Will the PDF file size be much larger with embedded images?

Yes, base64 encoding increases the image size by about 33%. However, the PDF itself may compress images depending on the PDF generation settings. You can reduce size by using compressed images (e.g., JPEG instead of PNG for photos).

Can I use remote images from a URL?

Yes, you can use http:// or https:// URLs directly in the src attribute. But ensure that the images are accessible and that you wait for them to load (using networkidle0). However, for a self-contained PDF, embedding is safer.

Does this work with other template engines like EJS?

Yes, the principle is the same: render the HTML with your template engine, then pass the HTML string to Puppeteer. The image embedding technique (base64 or file paths) works regardless of the template engine.

Can I generate PDFs on a server without a display?

Yes, Puppeteer runs headless Chrome, which doesn't require a display. It works on Linux servers, but you may need to install additional libraries as mentioned in Troubleshooting.

How do I handle dynamic images (e.g., user-uploaded files)?

Read the uploaded file, convert to base64, and pass it to the template. This is a common pattern for generating invoices or reports with logos and user photos.