Home > Mobile >  Create a pdf from an image list
Create a pdf from an image list

Time:11-29

I am developing a program in python to produce raffle tickets. The program creates as many tickets as required from a reference image by modifying only the ticket number. I have a list of images with potentially several hundred items. I would like to resize my images and save them in a pdf to allow printing. The user has to choose the number of tickets per row and per column on an A4 page

PIL_img_list = [...]
nbr_per_line = input("Number of ticket per line")
nbr_per_column = input("Number of ticket per column")

Does anyone have an idea?

CodePudding user response:

For working with images, I recommend the PIL library, here is a link: https://pillow.readthedocs.io/en/stable/

I think this library also includes conversion to pdf. I hope it works!

CodePudding user response:

disclaimer: I am the author of borb, the library used in this answer

You can simply add the Image to a Document (use absolute positioning), and then add a Paragraph of text (containing the raffle number) at the position you want to have it.

from borb.pdf import Document
from borb.pdf import Page
from borb.pdf import Image
from borb.pdf import Paragraph
from borb.pdf import PDF
from borb.pdf.canvas.geometry.rectangle import Rectangle

# create empty document
doc: Document = Document()

# add empty page
pge: Page = Page()
doc.add_page(pge)

# define a Rectangle on which we want to draw content
# fmt: off
r: Rectangle = Rectangle(
    Decimal(59),                # x: 0   page_margin
    Decimal(848 - 84 - 100),    # y: page_height - page_margin - height_of_textbox
    Decimal(595 - 59 * 2),      # width: page_width - 2 * page_margin
    Decimal(100),               # height
)
# fmt: on

# add Image
Image("path_to_image.png", 
      width=Decimal(100), 
      height=Decimal(100)).paint(pge, r)

# add Paragraph
Paragraph("00001").paint(pge, r)

# store
with open("output.pdf", "wb" as fh:
    PDF.dumps(fh, doc)

borb is an open source, pure Python PDF library that creates, modifies and reads PDF documents. You can download it using:

pip install borb

Alternatively, you can build from source by forking/downloading the GitHub repository.

  • Related