I have a script that modifies pdf files so that they comply with some specifications that are required to be uploaded to some other app (grayscale or black and white, 300 dpi, letter sized, etc.). I'm using pdf2image, img2pdf. PIL.Image and fitz.
The problem is that when I'm done modifying the files, the pdf version upgrades from 1.4 to 1.7 and I need it to be specifically 1.4. After reading online, I found out that PyPDF2 automatically converts pdf files to 1.3. I tried that thinking that 1.3 could work, but to my surprise it did not. It HAS to be 1.4. Here is my code if it helps:
import os
from os.path import join
from tempfile import TemporaryDirectory
from pdf2image import convert_from_path
from img2pdf import convert
import PIL.Image as Image
import fitz
from PyPDF2 import PdfFileWriter, PdfFileReader
#Here's where the source pdf is located.
pdf_input = os.path.join("PDF")
#Converting pdf to images
with TemporaryDirectory() as temp_dir:
for file in os.listdir(pdf_input):
pdfName = os.fsdecode(file)
pdf_to_open = os.path.join(pdf_input, pdfName)
images = convert_from_path(
pdf_to_open,
dpi=282, #For some reason, if I put 300dpi I end up with 325 dpi.
output_folder=temp_dir,
grayscale=True,
fmt="png",
thread_count=4
)
#Iterating through images
image_list = list()
for page_number in range(1, len(images) + 1):
path = join(temp_dir, "page_" + str(page_number) + ".png")
image_list.append(path)
images[page_number-1].save(path, "PNG")
#Converting to Black and WHite
image_file = Image.open(path)
image_file = image_file.convert('1')
image_file.save(path)
#Converting images to pdf
if not os.path.exists(pdf_input):
os.mkdir(pdf_input)
pdfPath = os.path.join(pdf_input, pdfName)
with open(pdfPath, "bw") as gray_pdf:
gray_pdf.write(convert(image_list))
#Changing pdf size
src = fitz.open(gray_pdf)
doc = fitz.open()
for ipage in src:
fmt = fitz.paper_rect("Letter")
page = doc.new_page(width=fmt.width, height=fmt.height)
page.show_pdf_page(page.rect, src, ipage.number)
src.close()
doc.save(gray_pdf)
#Downgrading with PyPDF2
infile = PdfFileReader(pdfPath, 'rb')
output = PdfFileWriter()
for i in range(infile.getNumPages()):
p = infile.getPage(i)
output.addPage(p)
with open(pdfPath, 'wb') as f:
output.write(f)