Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdfkit create pages using from_string

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

like image 201
Headrun Avatar asked Apr 18 '17 05:04

Headrun


1 Answers

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)
like image 111
Chase Avatar answered Sep 21 '22 17:09

Chase