Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Batch rotate pdf with PyPDF2

Tags:

python

pdf

pypdf

I've been working on a code to batch rotate PDF files inside a folder, but I can't find a way to iterate and change the destination folder of the rotated file.

My intention is to save the new file with the same name in another folder.

from os import listdir

from PyPDF2 import PdfReader, PdfWriter

# Collect files
root = "C:\z_PruebPy\pdf"
archs = []
for x in listdir(root):
    archs.append(root + x)

# Batch rotate
for arch in archs:
    pdf_in = open(arch, "rb")
    reader = PdfReader(pdf_in)
    writer = PdfWriter()

    for page in reader.pages:
        page.rotate_clockwise(270)
        writer.add_page(page)

    with open(arch, "wb") as pdf_out:  # ????????
        writer.write(pdf_out)
    pdf_in.close()
like image 367
fcr Avatar asked Dec 24 '22 13:12

fcr


1 Answers

You have to give PdfFileWriter a file pointer to the new location. Also you don't need to create a list and iterate on the list, just iterate on os.listdir results. Finally you had unused variables, like loc. I cleaned your code a bit.

So this should work, assuming you create the output folder :

from os import listdir
from PyPDF2 import PdfReader, PdfWriter

input_dir  = "C:\\z_PruebPy\\pdf\\"
output_dir = "C:\\z_PruebPy\\output_pdf\\"

for fname in listdir(input_dir):
    if not fname.endswith(".pdf"):  # ignore non-pdf files
        continue
    reader = PdfReader(input_dir + fname)
    writer = PdfWriter()
    for page in reader.pages:
        page.rotate_clockwise(270)
        writer.add_page(page)
    with open(output_dir + fname, "wb") as pdf_out:
        writer.write(pdf_out)
like image 78
Loïc Avatar answered Dec 28 '22 09:12

Loïc