python剪切文件到另一个文件夹_Python+PyPdf:裁剪页面区域并将其粘贴到另一个页面中...

本文介绍如何使用Python的PyPdf库裁剪PDF页面的特定区域,并将其粘贴到另一个PDF页面上。代码示例展示了如何实现这一功能,包括提取和合并页面的操作。
摘要由CSDN通过智能技术生成

假设您有一个包含各种复杂元素的pdf页面。

目标是裁剪页面的一个区域(只提取其中一个元素),然后将其粘贴到另一个pdf页面中。

Oy6BA.png

以下是我的代码的简化版本:

import PyPDF2

import PyPdf

def extract_tree(in_file, out_file):

with open(in_file, 'rb') as infp:

# Read the document that contains the tree (in its first page)

reader = pyPdf.PdfFileReader(infp)

page = reader.getPage(0)

# Crop the tree. Coordinates below are only referential

page.cropBox.lowerLeft = [100,200]

page.cropBox.upperRight = [250,300]

# Create an empty document and add a single page containing only the cropped page

writer = pyPdf.PdfFileWriter()

writer.addPage(page)

with open(out_file, 'wb') as outfp:

writer.write(outfp)

def insert_tree_into_page(tree_document, text_document):

# Load the first page of the document containing 'text text text text...'

text_page = PyPDF2.PdfFileReader(file(text_document,'rb')).getPage(0)

# Load the previously cropped tree (cropped using 'extract_tree')

tree_page = PyPDF2.PdfFileReader(file(tree_document,'rb')).getPage(0)

# Overlay the text-page and the tree-crop

text_page.mergeScaledTranslatedPage(page2=tree_page,scale='1.0',tx='100',ty='200')

# Save the result into a new empty document

output = PyPDF2.PdfFileWriter()

output.addPage(text_page)

outputStream = file('merged_document.pdf','wb')

output.write(outputStream)

# First, crop the tree and save it into cropped_document.pdf

extract_tree('document1.pdf', 'cropped_document.pdf')

# Now merge document2.pdf with cropped_document.pdf

insert_tree_into_page('cropped_document.pdf', 'document2.pdf')

“提取树”的方法似乎是可行的。它生成一个只包含裁剪区域(在示例中是树)的pdf文件。

问题在于,当我试图将树粘贴到新页面时,原始图像的星和房子仍然被粘贴

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值