需要安装两个模块
pip install fitz
pip install PyMuPDF
import glob
import fitz
import os
import time
# 1.提取原PDF关键代码
def pdf2pic(filename):
image_floder='pdf'+str(time.time())
os.mkdir(image_floder)
pdffile = filename
doc = fitz.open(pdffile)
width, height = fitz.PaperSize("a4")
totaling = doc.pageCount
for pg in range(totaling):
page = doc[pg]
zoom = int(100)
rotate = int(0)
print(page)
trans = fitz.Matrix(zoom / 100.0, zoom / 100.0).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
lurl=image_floder+'/%s.jpg' % str(pg+1)
pm.writePNG(lurl)
doc.close()
return image_floder
# 2.合并图片生成PDF
def pic2pdf(image_floder):
doc = fitz.open()
for img in sorted(glob.glob(image_floder+"/*")): # 读取图片,确保按文件名排序
print(img)
imgdoc = fitz.open(img) # 打开图片
pdfbytes = imgdoc.convertToPDF() # 使用图片创建单页的 PDF
imgpdf = fitz.open("pdf", pdfbytes)
doc.insertPDF(imgpdf) # 将当前页插入文档
if os.path.exists("newpdf.pdf"): # 若文件存在先删除
os.remove("newpdf.pdf")
doc.save("newpdf.pdf") # 保存pdf文件
doc.close()
image_floder=pdf2pic(filename='paper.pdf')
pic2pdf(image_floder)