pdfkit create pages using from_string
Asked Answered
A

2

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

Abdul answered 18/4, 2017 at 5:34 Comment(3)
Why not put in a string and call github.com/JazzCore/python-pdfkit/blob/… ? Seems like the library has somewhat support for what you want. If you need each text per page, inject HTML instead of raw text.Cachet
@Cachet didn't get you.Pressman
@Cachet by inject html instead of raw text do you mean, to pass file name list?Pressman
E
4

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)
Eardrum answered 6/4, 2021 at 1:16 Comment(0)
F
-4

You can concatenate strings like this:

pdfkit.from_string('ABC' + 'XYZ', 'output.pdf')
Francenefrances answered 21/7, 2020 at 16:23 Comment(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.Cabman

© 2022 - 2024 — McMap. All rights reserved.