此方法不能指定大小,压缩比例为1/7
目前只针对纯PDF图片压缩
实现原理: 主要通过PYMUPDF进行图片提取,图片压缩,再合并生成一个新的PDF。
# 压缩PDF大小def compress_pdf(filepath, tmpdir):if os.path.splitext(filepath)[-1] not in ['.pdf', 'PDF']:print('非PDF文件')return filepathelse:# 先把PDF转成图片pdffile = filepathdoc = fitz.open(pdffile)width, height = fitz.PaperSize("a4")totaling = doc.pageCount# 清空临时文件夹if not os.path.exists(tmpdir):os.makedirs(tmpdir) # 创建文件夹tmpic = os.path.join(tmpdir, 'tmpic')if not os.path.exists(tmpic):os.makedirs(tmpic) # 创建文件夹images = []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 = os.path.join(tmpic, os.path.splitext(os.path.basename(filepath))[0] + 'tmp%s.jpg' % str(pg + 1))images.append(lurl)pm.writePNG(lurl)doc.close()# 再把图片合并成PDFdoc = fitz.open()for img in images: # 读取图片,确保按文件名排序print(img)imgdoc = fitz.open(img) # 打开图片pdfbytes = imgdoc.convertToPDF() # 使用图片创建单页的 PDFimgpdf = fitz.open("pdf", pdfbytes)doc.insertPDF(imgpdf) # 将当前页插入文档outfile = os.path.join(tmpdir, os.path.basename(filepath))if os.path.exists(outfile): # 若文件存在先删除os.remove(outfile)doc.save(outfile) # 保存pdf文件doc.close()return outfile
