我基本上试图使用 python 抓取两页并将它们放在另一页旁边,因为我想在一些 A4 页面上打印一本小册子。我发现的问题是,右侧页面的平移不断使页面消失(我将平移限制为页面宽度的一半,以便在运行代码时可以清楚地看到消失)。
我将不胜感激任何帮助!
import PyPDF2
from PyPDF2 import PdfWriter, PdfReader, PageObject, Transformation
def process_pdf(input_pdf_path, output_pdf_path):
# Open the input PDF file
pdf_reader = PdfReader(input_pdf_path)
pdf_writer = PdfWriter()
num_pages = len(pdf_reader.pages)
page1 = pdf_reader.pages[0]
page2 = pdf_reader.pages[1]
merged_page = merge_pages(page1, page2)
pdf_writer.add_page(merged_page)
with open(output_pdf_path, 'wb') as output_pdf_file:
pdf_writer.write(output_pdf_file)
def merge_pages(page_left, page_right):
# Get the dimensions of the pages
page_width = page_left.mediabox.width
page_height = page_left.mediabox.height
# Create a new blank page with double width
merged_page = PageObject.create_blank_page(width=page_width*2, height=page_height)
# Merge the left page on the left side of the new page
merged_page.merge_page(page_left)
# Apply translation transformation to the right page
translation = Transformation().translate(tx=page_width/2, ty=0)
page_right.add_transformation(translation)
# Merge the right page on the right side of the new page
merged_page.merge_page(page_right,expand=True)
return merged_page
# Test
input_pdf = 'input.pdf' # Path to the input PDF file
output_pdf = 'output.pdf' # Path to the output PDF file
process_pdf(input_pdf, output_pdf)
您可以使用任何至少 2 页的 pdf 尝试此操作,您就会看到问题所在。
以下修改解决了问题,有同样问题的人都可以使用:
# Function to merge two pages side by side
def merge_pages(page_left, page_right):
# Get the dimensions of the pages
page_width = page_left.mediabox.width
page_height = page_left.mediabox.height
# Create a new blank page with double width
merged_page = PageObject.create_blank_page(width=page_width*2, height=page_height)
# Merge the right page to the new page
merged_page.merge_page(page_right)
# Add a translation of 1 width to the right of all contents of merge_page
merged_page.add_transformation(Transformation()\
.translate(tx=page_width,ty=0))
# Merge the left page on the left side of the new page
merged_page.merge_page(page_left)
# The new page is ready
return merged_page