puppeteer: [Bug]: Error when parsing page to PDF: ProtocolError: Protocol error (Page.printToPDF): Printing failed

Bug description

I am trying to generate a pdf from a big html file with lots of images. The HTML file itself is 15MB and the total amount of images it is trying to load is ~500MB. When trying this on my local machine it works. But when trying to execute the script in a lambda or as a Docker container it outputs this error constantly.

Steps to reproduce the problem:

  1. Build the docker image. You can find my Dockerfile: https://gist.github.com/sefasenturk95/0eb0f4feead25c236e059b5afd18f75a and the code that I’m running here: https://gist.github.com/sefasenturk95/cc85f18aa53bf56c816a5b12cd9ec04f
  2. Run the docker image
  3. After a while the script stops and outputs the error.

Puppeteer version

13.4.0

Node.js version

14.16.1

npm version

6.14.12

What operating system are you seeing the problem on?

Linux

Relevant log output

➜  pdf-gen git:(develop) ✗ docker run pdf-gen
{"level":30,"time":1645893676687,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"starting puppeteer"}
Fontconfig warning: "/etc/fonts/fonts.conf", line 100: unknown element "blank"
[0226/164117.009189:ERROR:bus.cc(397)] Failed to connect to the bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory
[0226/164117.009584:ERROR:bus.cc(397)] Failed to connect to the bus: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory

DevTools listening on ws://127.0.0.1:45607/devtools/browser/95372895-7025-4e0c-9b2b-d3d2aaffc70a
[0226/164117.038525:WARNING:bluez_dbus_manager.cc(248)] Floss manager not present, cannot set Floss enable/disable.
{"level":30,"time":1645893677087,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"done starting puppeteer"}
{"level":30,"time":1645893677087,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"new page"}
[0226/164117.104284:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process.
{"level":30,"time":1645893677153,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"done new page"}
{"level":30,"time":1645893677153,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"emulate media type"}
{"level":30,"time":1645893677154,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"done emulate media type"}
{"level":30,"time":1645893677154,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"go to page"}
{"level":30,"time":1645893702349,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"done go to page"}
{"level":30,"time":1645893702350,"pid":8,"hostname":"5200a5499cd2","name":"app-name","msg":"generate pdf"}
(node:8) UnhandledPromiseRejectionWarning: ProtocolError: Protocol error (Page.printToPDF): Printing failed
    at /node_modules/puppeteer/lib/cjs/puppeteer/common/Connection.js:230:24
    at new Promise (<anonymous>)
    at CDPSession.send (/node_modules/puppeteer/lib/cjs/puppeteer/common/Connection.js:226:16)
    at Page.createPDFStream (/node_modules/puppeteer/lib/cjs/puppeteer/common/Page.js:2074:50)
    at Page.pdf (/node_modules/puppeteer/lib/cjs/puppeteer/common/Page.js:2103:37)
    at /index.js:77:20
    at Generator.next (<anonymous>)
    at fulfilled (/index.js:24:58)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 14
  • Comments: 45

Most upvoted comments

This is working for me on my local machine ( which is Linux) but don’t work on docker was anyone able to solve this?

EDIT: Solved for me I increased the memory requests and limits of the pod and was able to render A large HTML with big tables

I have a small img src data:image/png;base64,... with a single pixel in it and plenty of RAM for an empty HTML content.

Tested on:

  • Previous version: v23.3.1 (2025-03-03) with Chrome/133.0.6943.141 OK
  • Latest version: v24.4.0 (2025-03-05) with Chrome/134.0.6998.35 Crash with error as per this title

Latest v24.4.0 exactly makes no image is possible in PDF header.

Reproduce:

  • Add small base64 data in image src in headerTemplate. e.g.
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="test" />
    
  • page.setContent() with just basic HTML hello world.

This should be reopen for tracking upstream chrome.

Since the latest version, any image on PDF header is impossible.


Update:

I can use latest version by using old headless chrome

browser = await puppeteer.launch({ headless: "shell" });

More about the announcement here I feel confident to use latest version now, all my tests are passing with slight minor differences.

Unable to print html file larger than 1Mb. This is a bug in Chrome for Testing version 114.0.5735.90. If you take Chromium 116.0.5834.0, then everything works.

puppeteer@19.7.0 node@18.18.2

ProtocolError: Protocol error (Page.printToPDF): Printing failed at /usr/src/app/node_modules/puppeteer-core/src/common/Connection.ts:400:16 at new Promise (<anonymous>) at CDPSessionImpl.send (/usr/src/app/node_modules/puppeteer-core/src/common/Connection.ts:396:12) at CDPPage.createPDFStream (/usr/src/app/node_modules/puppeteer-core/src/common/Page.ts:1515:46) at CDPPage.pdf (/usr/src/app/node_modules/puppeteer-core/src/common/Page.ts:1549:33)

This happened to me when I (unintentionally) closed the page prior to finishing the PDF conversion. (I forgot to await the .pdf() call).

i had a huge html file with 316 pages and this solved my problem

maybe the code is not perfect and has some performance issues, feel free to change it

thank me later ✌️

import puppeteer, { Browser, GoToOptions, Page, PDFOptions } from 'puppeteer';
import { PDFDocument } from 'pdf-lib'; 
    const pdfChunks = await this.generatePDFInChunks({
      pagesChunk: 60,
      browser,
      options,
      fileName,
    });

    return this.mergePDFChunks(pdfChunks);
  async generatePDFInChunks(config: GeneratePDFInChunksConfig) {
    const { browser, pagesChunk, options, fileName } = config;

    const pdfChunks: Uint8Array[] = [];

    const firstLoadPage = await this.openPage(browser, fileName);

    const totalPages = await this.getTotalPages(firstLoadPage);

    for (
      let currentPage = 1;
      currentPage <= totalPages;
      currentPage += pagesChunk
    ) {
      // avoid extra load
      const page =
        currentPage === 1
          ? firstLoadPage
          : await this.openPage(browser, fileName);

      await page.setViewport({
        width: 720,
        height: 1200,
        deviceScaleFactor: 1,
      });

      const endPage = Math.min(currentPage + pagesChunk - 1, totalPages);

      const pdfBuffer = await page.pdf({
        ...options,
        pageRanges: `${currentPage}-${Math.min(endPage, totalPages)}`,
      });

      pdfChunks.push(pdfBuffer);

      await page.close();
    }

    await browser.close();

    return pdfChunks;
  }

  async mergePDFChunks(pdfChunks: Uint8Array[]) {
    const mergedPdf = await PDFDocument.create();

    for (const chunk of pdfChunks) {
      const pdf = await PDFDocument.load(chunk);
      const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
      copiedPages.forEach((page) => mergedPdf.addPage(page));
    }

    return mergedPdf.save();
  }


  getTotalPages(page: Page) {
    return page.evaluate(() => {
      const bodyHeight = document.body.scrollHeight;
      const pageHeight = 1200;
      return Math.ceil(bodyHeight / pageHeight);
    });
  }

  getPageConfig(fileName: string) {
    const url = `file://${PATH_DATAFILES}html/${fileName}.html`;
    const goToOptions: GoToOptions = {
      waitUntil: 'networkidle0',
      timeout: 0,
    };

    return { url, goToOptions };
  }

  async openPage(browser: Browser, fileName: string) {
    const { goToOptions, url } = this.getPageConfig(fileName);

    const page = await browser.newPage();

    await page.goto(url, goToOptions);

    return page;
  }

I’m facing this issue, too, I feel confused, sorry.

Reading over comments, there are multiple issues here:

  1. make sure you await the pdf call and do not close the browser too early.
  2. make sure the browser has sufficient memory and cpu, especially, if the generation works locally but not working once deployed to a different environment.

If after that you get a Protocol error (Page.printToPDF): Printing failed please file an issue for Chrome at https://crbug.com and include the HTML page it fails to print. Also, please try printing to PDF using the regular print dialog in the desktop chrome.

I found an old docker container from a year ago and it works on a payload that is failing today. So the bug must have been introduced in the last year some time. In the mean time I’ll use my old container.

This is still an active issue.

On our side (running on Lambda) it seem to happen frequently when our users load pages that contain more than 50MB of images. I don’t have an exact number regarding the total weight or the number of images, but we do see it freqently.

At least a more accurate error message would be useful 🙂

Janka55 If chrome prints your html in windowed mode, then the puppeteer should. Where can i see your file?

Sorry, my file contains lots of private information, I can’t provide it to you. What is windowed mode? Do you mean non-headless mode? I have set headless: true to launch my broswer.

@brombomb older puppeteersharp library (via nuget) and possibly older version of chrome.

@apexdodge

I found an old docker container from a year ago and it works on a payload that is failing today. So the bug must have been introduced in the last year some time. In the mean time I’ll use my old container.

Any insight in to what changed in your docker image?

In our case, is not working running on Cloud Run.

We did some tests where all resources were increased (more RAM, CPU…) and so increasing the memory requests and limits, but the problem is persisting…

Is there any news related to this bug? Anyone who could solve this?