Skip to content

Instantly share code, notes, and snippets.

@hminle
Created November 3, 2021 13:35
Show Gist options
  • Save hminle/06b2dc804cfe8f881a3803047d9a4843 to your computer and use it in GitHub Desktop.
Save hminle/06b2dc804cfe8f881a3803047d9a4843 to your computer and use it in GitHub Desktop.
merge pdf files in a given path with password. Replace your <path> and <password> to use
import PyPDF2
from pathlib import Path
root = Path(r"<path>")
pdf_files = list(root.glob('*.pdf'))
writer = PyPDF2.PdfFileWriter()
for file in pdf_files:
with open(file, mode='rb') as f:
reader = PyPDF2.PdfFileReader(f)
if reader.isEncrypted:
reader.decrypt('<password>')
for pageNum in range(reader.getNumPages()):
writer.addPage(reader.getPage(pageNum))
with open("merged_output.pdf", "wb") as out:
writer.write(out)