Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

png images to one pdf in python

Tags:

python

pdf

png

fpdf

I have a list of .png images. I need to convert all of them into one pdf, 9 images per page , but not to place them one after another vertically, but fill in all the width, and only then continue to next row. Amount of pictures can be different each time (12, ... 15)

I have tried fpdf

from fpdf import FPDF

list_of_images = [1.png, 2.png, ... 15.png]
w = 70
h = 60
pdf = FPDF(orientation = 'L')
for image in list_of_images:
    pdf.image(image, w=sizew, h=sizeh)
pdf.output("Memory_usage.pdf", "F")

and also wkhtmltopdf

template = Template('''<!doctype html>
<html>
<body>
        <div style="display: flex; flex-direction: row">
        {% for image in images %}
            <img src="{{ image }}" />
        {% endfor %}
        </div>
</body>
</html>''')
list_of_images = [1.png, 2.png, ... 15.png]
html = template.render(images=list_of_pict)
with open("my_new_file.html", "wb") as fh:
    fh.write(html)

p = subprocess.Popen(['wkhtmltopdf', '-', 'Memory_usage.pdf'], stdin=subprocess.PIPE, universal_newlines=True)
p.communicate(html)
p.wait()

but both of them place each picture one under another

like image 714
Yuliya Avatar asked Dec 01 '16 09:12

Yuliya


People also ask

How do I save multiple images as one PDF in Python?

The first thing you do is create the FPDF() object and set the source directory where you have the images stored. sdir is that variable. You also need to set two variables to capture the height and width of the images respectively.


1 Answers

Just place each image at required coordinates using FPDF:

pdf.image(image, x=50, y=100, w=sizew, h=sizeh)

More info on FPDF documentation: image

like image 172
FelixEnescu Avatar answered Sep 27 '22 22:09

FelixEnescu