简体   繁体   中英

HTML/CSS to PDF, background image on all pages

I'm generating PDFs from user submitted HTML/CSS. The client has requested that the PDFs have a background image to add some branding. The PDF library is wkhtmltopdf11RC1.

I can make the images print in the background using the PDF conversion library but the real problem is that the height of the body is not guaranteed to be a multiple of the paper height, and so the last page usually get's cut off and the background image isn't shown.

The PDF library does have javascript support but the element.offsetHeight doesn't seem accurate, and so I can't check how much to pad the body by in order to make a full page.

Has anyone had a similar experience or does anyone have a bright idea?

If the plugin is relying on the height of the body to make printing decisions, than perhaps this will work. What it does is set the height of the body to a multiple of the page height. You are going to have to figure out what the paper height is - the standard is 72 pixels per inch. So 11.5 inches is something like 841 pixels, but you may have to adjust for margin.

var paperHeight = 841;

var currentDocHeight = $(document).height();

var pages = Math.ceil(currentDocHeight / paperHeight);

var newBodyHeight = pages * paperHeight;

$('body').css('height', newBodyHeight);

I've used jQuery to condense the answer, but this can all be done in jQuery-less javascript as well.

CSS:

body {
  margin:0
}

Unfortunately var currentBodyHeight = $('body').height(); doesn't give an accurate indication of the height of the body for some reason, as mentioned in the original post. I've used PDFtk as suggested by Nenotlep.

It wasn't too tricky, just had to ensure that files were being saved and erased properly and I always kept a reference to the temporary files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM