r/code • • Nov 17 '20

Working with .PDF files on Python (please help!!)

I'm looking for the best way to create and edit a pdf using python. My project involves delivering a pdf catalog of thousands of products and I need a way of automating the proccess or else I'll go crazy going though them one by one.

Thanks in advance :)

9 Upvotes

2 comments sorted by

1

u/adnanholy1998 Nov 17 '20 edited Nov 17 '20

Here's a code that isn't great but gets the job done. I stored all the paths to my images in a list called files.

Cols and Rows are the number of images you want in column and rows per page.

figsize is a tuple that defines the image size (for example figsize=(20,20))

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.image as img

pp = PdfPages('name.pdf')
npages = int(len(files)/cols/rows)
it_file = 0 #image iterator

for it_page in range(npages):
    j = 0
    fig = plt.figure(figsize=figsize)
    for i in range(rows*cols):
    	j+=1
    	ax = fig.add_subplot(rows,cols,j)
    	file = files[it_file]
    	im = img.imread(file)
    	ax.imshow(im)
    	ax.get_xaxis().set_visible(False)
    	ax.get_yaxis().set_visible(False)
    	ax.set_title('insert title here')
    	it_file+=1
    plt.close(fig)
    pp.savefig(fig)
pp.close()

1

u/ramib3lsito2 Nov 17 '20

Thanks for sharing the code! I'm storing my data in and excel so I was thinking of using pandas, define the variables I need to change from image to image and then create a preset with a library like reportlab were I would be able to use a "for" to run multiple times the code replacing the variable with the that's in each row of the pandas database. I don't know if I was able to explain myself, if something it's not clear please let me know.