1

I am using pdfkit to create a PDF from a HTML file... like so:

import pdfkit
pdfkit.from_file([source], target + '.pdf')

I create the HTML file myself before doing this conversion. What I'm now trying to do is find a way to impleet a page break. The HTML file doesn't use page breaks because ... well, it's basic html. But PDF's are page type structures.

So how can I pickup something in the HTML as a marker, and then use that to implement a page break in the PDF?

Of course pdfkit.from_file([source], target + '.pdf') is a simple single line... there's no parsing of the content..... so I don't see how I could tell it what to look for.

Any ideas?

EDIT With some advice from @Nathanial below, I've added to my CSS

@media print {
  h2 { 
    page-break-before: always;
  }

But I don't see pdfkit.from_file([source], target + '.pdf') picking it up?

Opening the html file in the browser and printing to PDF works perfectly. so this is more of a pdfkit issue.

Found a similar question here: How to insert a page break in HTML so wkhtmltopdf parses it?

I think the pdfkit wrapper for wkhtmltopdf is limited. On the commnd line, this works perfectly.

wkhtmltopdf --print-media-type 10100005.html 10100005.pdf

But how do I replicate that in python? It's not my first choice to doa os.execute....:/

Maxcot
  • 1,513
  • 3
  • 23
  • 51

1 Answers1

1

After some fiddling, this worked for me. I'm putting this here to help the next person.

Thanks @Nathaniel Flick for pointing me to use media print and print only styles.

Example 11 on this page also helped https://www.programcreek.com/python/example/100586/pdfkit.from_file

In the style sheet

@media print {
  h2 { 
    page-break-before: always;
     }
      }

Then in the python code

pdfkit_options = {
   'print-media-type': '',
}


>>> print (source)
c:/users/maxcot/desktop/Reports/10100001.html

>>> print (target)
c:/users/maxcot/desktop/Reports/10100001.pdf

>>> print (pdfkit_options)
{'print-media-type': ''}

pdfkit.from_file(source, target, options=pdfkit_options)
Maxcot
  • 1,513
  • 3
  • 23
  • 51