Skip to content

从多个pdf文档中截取部分区域拼接成一个pdf文档

zephyrmao edited this page Mar 1, 2019 · 3 revisions

提取合并多个pdf页面中的子区域,形成一个没有分页符的页面。

输入input:多个pdf的Rect区域 areas in pdf

输出output:一页(只是一页)完整的pdf文档 a page of pdf doc

*******************************

使用的工具及步骤tools and steps:

  1. 使用fitz.open()函数打开pdf
  2. **使用page.searchFor(“特征字符串”)函数找到特征字符串位置(两个对角定点的坐标),得到需要剪切的位置。如果知道位置这一步可以省略
  3. 使用page = DOC.newPage(页面宽,页面高)创建新的页面
  4. 使用page.showPDFpage()函数插入区域
  5. 使用doc.save()函数保存文档

example: #step 1

import fitz                
DOC1 = fitz.open("c:/内容文件1.pdf") # 打开pdf文件,为提取这个文件的内容做准备
DOC2 = fitz.open("c:/内容文件2.pdf") # 打开pdf文件,为提取这个文件的内容做准备
DOC3 = fitz.open()  # empty new PDF (output)建立一个空文档,用于存放提取出来的pdf上的区域

#step 3 创建一个新的空页面

page = DOC3.newPage(width=DOC1[0].rect.width, 
                    height=y) #文档总共的高度

4、使用page.showPDFpage()函数插入区域

page.showPDFpage(DOC1[0].rect, DOC1, 0) # 把DOC1文档的 page 0页 的DOC1[0].rect 区域插入DOC3新创建的页面
page.showPDFpage(DOC3rect, DOC2, 1, clip=rect1) # 把DOC2 第一页中的rect1 区域 插入DOC3rect区域  page 1, rect1
page.showPDFpage(nr2, DOC2, 2, clip=rect2) #同上

5、使用doc.save()函数保存文档

DOC3.save('E:/我的新文档.pdf', garbage=4, deflate=True)  #保存文档到'E:/我的新文档.pdf'

代码样例

import fitz
DOC1 = fitz.open('E:/定义3.pdf')
DOC2 = fitz.open('E:/含义.pdf')
DOC3 = fitz.open()  

page = DOC3.newPage(width=DOC1[0].rect.width, 
                    height=DOC1[0].rect.height + DOC2[0].rect.height)
page.showPDFpage(DOC1[0].rect, DOC1, 0) 
placerect = fitz.Rect([0,DOC1[0].rect[3],DOC1[0].rect[2],DOC1[0].rect[3]+DOC2[0].rect[3]])
page.showPDFpage(placerect, DOC2, 0, clip=DOC2[0].rect) 
DOC3.save('E:/我的新文档.pdf', garbage=4, deflate=True)

`

感谢Jorj McKie

西风2019.3.1

Clone this wiki locally