Search code examples
pythonpdfglobfpdf

adding 2 pages per pdf with filename


I am volunteering in creating ID card for one organization. wrote a script using various resources in Python and created the images. Now I am converting those images to pdf file that contains front and back of the ID card as a single pdf file with the card holder name. I could get the names, but all the images are adding to a single pdf. I want it to be split at every 2 pages at the time of image to pdf conversion itself.

from fpdf import FPDF
import glob

for image in image_list:
    print(image.title())
    # print(image.index(1))
    filename = image.rstrip("_front.png")
    filename = filename.rstrip("_back.png")
    print(filename)
    filename = filename.lstrip("\\D:\\pythonex\\Achyutaashrama\\")
    print("final filename--->"+filename)
    pdf.add_page()
    pdf.image(image, 50, 110, 110)
    if (len(pdf.pages)) / 2 == 0:
        pdf.output(filename + ".pdf", "F")
        break
    else:
        continue

if I put the pdf.output line outside the for loop, it gets to a single file and the above code is running without any errors but not producing any file.

please help.


Solution

  • If I correctly understood, the question is how to create a new pdf every 2 pages. If you are sure about the position of the image inside the list, here there is an example of how to split the pdf files in a very silly way, probably there are more better ideas. The concept is: create a new instance of FPDF().
    In the following code, I have only written how to split the files, inside of every page there is just a string : "Hello" with a number.

    from fpdf import FPDF
    
    def createpdf():
        # here I just create a fake list, just to explain how to split the pdf files
        image_list_fake = range(10)
        count = 1
        pdf = FPDF()
        for imag in image_list_fake:
            pdf.add_page()
            pdf.set_font('Arial', 'B', 16)
            pdf.cell(40, 10, 'Hello '+ str(imag))
            if count%2 == 0:
                # you have to close it ...
                pdf.output(str(imag)+'.pdf', 'F')
                # ... and open a new FPDF instance
                pdf = FPDF()
                count = 1
            else:
                count += 1