9

I am using pdfkit to generate pdf files from strings.

ASK: Each string i pass to pdfkit i want it as a new page in the output pdf.

i know this is possible using from_file like below. But, i do not want to write it to a file and use it.

pdfkit.from_file(['file1', 'file2'], 'output.pdf') This creates output.pdf file with 2 pages.

is something similar like below possible?

pdfkit.from_string(['ABC', 'XYZ'], 'output.pdf') 

It should write "ABC" in page 1 and "XYZ" in page 2 of output.pdf file

Headrun
  • 129
  • 1
  • 11
  • 3
    Why not put in a string and call https://github.com/JazzCore/python-pdfkit/blob/452b9ea1183bc10b45beef7be75d51ed3c4c7e01/pdfkit/api.py#L52 ? Seems like the library has somewhat support for what you want. If you need each text per page, inject HTML instead of raw text. – justderb Apr 18 '17 at 05:41
  • @justderb didn't get you. – suhailvs Jan 21 '19 at 08:52
  • @justderb by `inject html instead of raw text` do you mean, to pass file name list? – suhailvs Jan 21 '19 at 09:22

2 Answers2

3

I know this is old, but in case anyone else finds themselves here, I thought I would share what I did. I had to implement PyPDF2 to do what was specified above. My analogous solution was:

from PyPDF2 import PdfFileReader, PdfFileWriter
import io


with open('output.pdf', 'wb') as output_file:
    writer = PdfFileWriter()
    for s in ['ABC', 'XYZ']:
        stream = io.BytesIO()
        stream.write(pdfkit.from_string(s, False))
        # This line assumes the string html (or txt) is only 1 page.
        writer.addPage(PdfFileReader(stream).getPage(0))
    writer.write(output_file)
Chase
  • 321
  • 2
  • 6
-4

You can concatenate strings like this:

pdfkit.from_string('ABC' + 'XYZ', 'output.pdf')
  • 1
    But that's just the same as passing the content as a single string. It's not gonna start 'XYZ' on a new page. – RTF Mar 31 '21 at 11:35