1.安装两个包
pip install PyMuPDF PySimpleGUI
2.pdf转图片
import fitz
def pdf2img(pdf_path, img_dir):
doc = fitz.open(pdf_path)
for page in doc:
zoom_x = 2.0
zoom_y = 2.0
mat = fitz.Matrix(zoom_x, zoom_y)
pix = page.get_pixmap(matrix=mat)
pix.save(r"{}page-{}.png".format(img_dir, page.number))
if __name__ == '__main__':
pdf_path = r"./赵季平影视音乐成功因素分析.pdf"
img_dir = r"./img/"
pdf2img(pdf_path, img_dir)
ps:将缩放因子 zoom_x 和 zoom_y 设为 2.0 之后,可以将转换出来的图片大小提高四倍
3.图片转pdf
import os, fitz
import PySimpleGUI as psg
def img2pdf(pdf_path, imgdir):
doc = fitz.open()
imglist = os.listdir(imgdir)
imgcount = len(imglist)
for i, f in enumerate(imglist):
img = fitz.open(os.path.join(imgdir, f))
rect = img[0].rect
pdfbytes = img.convert_to_pdf()
img.close()
imgPDF = fitz.open("tar_pdf", pdfbytes)
page = doc.new_page(width=rect.width,
height=rect.height)
page.show_pdf_page(rect, imgPDF, 0)
psg.OneLineProgressMeter("Import Images",
i + 1, imgcount)
doc.save(pdf_path)
def clear_dir(imgdir):
imglist = os.listdir(imgdir)
for img in imglist:
os.remove(imgdir+img)
if __name__ == '__main__':
img_dir = r"./img/"
pdf_path = r"./赵季平影视音乐成功因素分析.pdf"
img2pdf(pdf_path, img_dir)
ps:其实这个 PyMuPDF 包还有很多功能,具体可以参考官网文档 https://pymupdf.readthedocs.io/en/latest/faq.html#how-to-make-images-from-document-pages
|