Home > OS >  Have margins for content but not background on every page when converting/printing HTML to PDF
Have margins for content but not background on every page when converting/printing HTML to PDF

Time:11-27

I am working on a website that needs to export the content of a web page as a pdf but it has to respect the following conditions:

  • The background has to be fully printed on every page
  • The content must not overlap the background

Since the website uses PHP I tried to use mPDF which I previously used on another PHP website that had the same conditions. mPDF showed the full background on each page of the pdf file even when the page was not completely filled with content and I could set margins that affected the content but not the background which still covered the whole page.

Sadly, mPDF is not working with this new website, very likely because it uses bootstrap and flex layouts (it returned me a pdf with about a thousand pages, mostly blank, others with very zoomed in pieces of the page), on top of that part of the content is changed by javascript before presenting it to the user and that was not taken into account by mPDF (I noticed that was when I removed bootstrap.css which allowed me to see the result of the conversion).

So I switched to puppeteer https://github.com/puppeteer/puppeteer which prints the content just fine using chrome under the hood, but I am having some issues. The first issue was that I couldn't print the full background on every page, but I solved it while writing this question by creating a div with position: fixed and width and height at 100% that works as background

The second issue is that when I set the margins in puppeteer (which in the end are the same as printing margins in chrome) they affect the background too (this was an issue even before creating the fixed div) so I can't find a way to have the text not overlap the background

Here you can see an example: https://stackblitz.com/edit/web-platform-vlfqfz?file=index.html

If you open the preview in another tab and try to print it you can see the issue I'm facing

CodePudding user response:

So, apparently it's not possible to do what I was exactly asking in this question so I found an alternate solution.
I cut the top and bottom part of the background and used them as images inside puppeteer's header and footer. It took a while to make the images coincide with the position: fixed div that acts as background (which now contains only the sides of the background) but setting a fixed width on the body did the job

  • Related