Issue:
I recently encountered an issue when trying to create a PDF from a print preview using Puppeteer. Everything worked perfectly on my local Windows machine, but when I deployed the scripts to an Ubuntu server, I received the following error:
This error appeared when I attempted to send an email with an attached PDF file generated by Puppeteer.
Troubleshooting:
After extensive research, I found very little information online about what could be causing this problem. I initially suspected a permissions or settings issue on the server, so I went through the process of uninstalling and reinstalling Puppeteer and Chromium several times. Unfortunately, this didn’t resolve the issue.
Next, I considered the possibility that the content might be corrupt or that something in the HTML page generated by Puppeteer was causing the failure. To test this, I created a bare-bones HTML template and ran the script again.
To my surprise, it worked! This confirmed that something in my original HTML template was causing Chrome to fail when generating the PDF.
Root Cause:
The problem was traced back to a script in the HTML header that automatically loaded the print preview when the page was loaded. This single action was the cause of the Puppeteer printToPDF failure.
Solution:
If you’re experiencing similar issues with Puppeteer’s printToPDF not working, I recommend checking the content of the HTML template you’re using to create the print preview. Specifically, ensure that there are no scripts running that could disrupt Puppeteer’s operation.
In my case, removing or disabling the script that triggered the print preview on page load resolved the issue, and Puppeteer was able to generate the PDF without any errors.
Summary:
When using Puppeteer to generate PDFs, be cautious about any scripts included in the HTML template that might interfere with the process. Removing problematic scripts, particularly those that manipulate the print preview, can solve issues that arise on different operating systems, such as the error I encountered on Ubuntu.