gpt4 book ai didi

python - 通过坐标提取 PDF 页面的区域

转载 作者:太空狗 更新时间:2023-10-30 01:03:24 31 4
gpt4 key购买 nike

我正在寻找一种工具来提取 1 页 PDF 文件的给定矩形区域(按坐标)并生成具有指定区域的 1 页 PDF 文件:

# in.pdf is a 1-page pdf file
extract file.pdf 0 0 100 100 > out.pdf
# out.pdf is now a 1-page pdf file with a page of size 100x100
# it contains the region (0, 0) to (100, 100) of file.pdf

我可以将 PDF 转换为图像并使用 convert,但这意味着生成的 PDF 将不再是矢量的,这是 Not Acceptable (我希望能够缩放)。

理想情况下,我希望使用命令行工具或 Python 库来执行此任务。

谢谢!

最佳答案

使用 pyPdf ,你可以这样做:

import sys
import pyPdf

def extract(in_file, coords, out_file):
with open(in_file, 'rb') as infp:
reader = pyPdf.PdfFileReader(infp)
page = reader.getPage(0)
writer = pyPdf.PdfFileWriter()
page.mediaBox.lowerLeft = coords[:2]
page.mediaBox.upperRight = coords[2:]
# you could do the same for page.trimBox and page.cropBox
writer.addPage(page)
with open(out_file, 'wb') as outfp:
writer.write(outfp)

if __name__ == '__main__':
in_file = sys.argv[1]
coords = [int(i) for i in sys.argv[2:6]]
out_file = sys.argv[6]

extract(in_file, coords, out_file)

关于python - 通过坐标提取 PDF 页面的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986876/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com