1.所需要的环境和工具包
PyMuPDF,reportlab,PIL
import os
import sys
import fitz
from reportlab.lib.pagesizes import portrait
from reportlab.pdfgen import canvas
from PIL import Image
2. pdf转图片
def pdf2img(filename):
doc = fitz.open(filename)
print("共",doc.pageCount,"页")
for pg in range(doc.pageCount):
print("\r转换为图片",pg+1,"/",doc.pageCount,end="")
page = doc[pg]
rotate = int(0)
zoom_x = 8.0
zoom_y = 8.0
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG(filename+'_tu'+'{:02}.png' .format(pg))
print()
if __name__ == '__main__':
filename='0.pdf'
pdf2img(filename)
3.图片转pdf
def img2pdf(img_name,outputpath):
(maxw, maxh) = Image.open(img_name).size
c = canvas.Canvas(outputpath, pagesize=portrait((maxw, maxh)))
c.drawImage(img_name, 0, 0, maxw, maxh)
c.showPage()
c.save()
if __name__ == "__main__":
img2pdf(img_name='E:\wm_workspace\pdf2img\data\实习证明.png',outputpath='E:\wm_workspace\pdf2img\data\实习证明.pdf')
print("\n转换完成!")
|