1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import fitz import os from PIL import Image
''' # 将PDF转化为图片 pdfPath pdf文件的路径 imgPath 图像要保存的文件夹 zoom_x x方向的缩放系数 zoom_y y方向的缩放系数 rotation_angle 旋转角度 '''
def pdf_image(pdfPath,imgPath,zoom_x,zoom_y,rotation_angle): pdf = fitz.open(pdfPath) for pg in range(0, pdf.pageCount): page = pdf[pg] trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle) pm = page.getPixmap(matrix=trans, alpha=False) pm.writePNG(imgPath+str(pg)+".png") pdf.close()
''' 将上一步生成的图片合成为长图 output_path为长图的输出路径 '''
def generate_long_image(output_path): picture_path = output_path[:output_path.rfind('.')] print(picture_path) last_dir = os.path.dirname(picture_path)
imagename = [] ims = [] for fn in os.listdir(picture_path): if fn.endswith('.png'): ims.append(Image.open(os.path.join(picture_path, fn))) imagename.append(os.path.join(picture_path, fn)) width, height = ims[0].size long_canvas = Image.new(ims[0].mode, (width, height * len(ims)))
for i, image in enumerate(ims): long_canvas.paste(image, box=(0, i * height))
for j, name in enumerate(imagename): os.remove(name) long_canvas.save(os.path.join(last_dir, 'long-image.png'))
pdf_image(r"C:\Users\nwx\Desktop\xxxxx.pdf",r"C:\Users\nwx\Desktop\\",5,5,0)
generate_long_image(r"C:\Users\nwx\Desktop\\")
|