环境参考:Python+pymupdf处理PDF文档案例6则 - 云+社区 - 腾讯云 (tencent.com)
参考原文有一些函数过时了,本文对其进行更新
import fitz
import pdfplumber
母文件地址
fn = r'D:\Desktop\highlight_test.pdf'
一、提取pdf文件中的文本,写入文本文件
方法一:plumber 库
with pdfplumber.open("D:\Desktop\highlight_test.pdf") as pdf:
for page in pdf.pages:
text = page.extract_text()
txt_file = open("D:\Desktop\a.txt",mode='a',encoding='utf-8')
txt_file.write(text)
方法二:fitz 库
with fitz.open(fn) as doc,\
open('D:\Desktop\aa.txt','w',encoding='utf8') as fp:
for page in doc :
fp.write(page.get_text()+'\n')
二、合并pdf文件
with fitz.open() as fpMerge:
for t in (fn,)*3:
with fitz.open(t) as fpSrc:
fpMerge.insert_pdf(fpSrc)
fpMerge.save('D:\Desktop\合并结果.pdf')
三、把pdf文件的每一页转换为独立的图片文件
with fitz.open(fn) as doc:
for page in doc:
mat = fitz.Matrix(2,2)
pix = page.get_pixmap(matrix= mat)
pix.save(f'{page.number}.png')
四、将pdf文件以图片形式保存为pdf
with fitz.open() as fpMerge:
for pic in ('0.png',)*5:
t = fitz.open('pdf',fitz.open(pic).convert_to_pdf())
fpMerge.insert_pdf(t)
fpMerge.save('D:\Desktop\内容转换为图片.pdf')
五、提取pdf文件中的图片
with fitz.open(fn) as doc:
for page in doc:
for item in page.get_images():
xref = item[0]
img = doc.extract_image(xref)
with open(f'{xref}.{img["ext"]}','wb') as fpPic:
fpPic.write(img['image'])
六、添加文本注释为关键词添加高亮、删除线、下划线注释
word1,word2,word3 = ('高亮','删除线','注释')
with fitz.open(fn) as doc:
for page in doc:
page.add_text_annot((200,200),'文本注释')
for txt in page.search_for(word1):
page.add_highlight_annot(txt)
for txt in page.search_for(word2):
page.add_strikeout_annot(txt)
for txt in page.search_for(word3):
page.add_underline_annot(txt)
doc.save('D:\Desktop\添加注释.pdf')
如果对高亮部分进行颜色的修改(高亮部分颜色是遵循RGB标准):
with fitz.open("D:\Desktop\文字.pdf") as doc:
for page in doc:
for txt in page.search_for(w):
highlight = page.add_highlight_annot(txt)
highlight.set_colors(stroke=[1, 1, 1])
highlight.update()
doc.save('D:\Desktop\add_annotion.pdf')
这里 stroke 其实就代表了,[ 1*255, 1*255,1*255 ] 所以,[1,1,1 ] 在这里是清除高亮的效果。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)