-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(v2.1):大幅优化几乎同等质量的 PDF 大小,并增加质量选择选项,以进一步降低 PDF 大小
- Loading branch information
1 parent
c969031
commit d0e00e6
Showing
4 changed files
with
62 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,35 @@ | ||
# coding:utf-8 | ||
import os | ||
import fitz | ||
import shutil | ||
from PIL import Image | ||
|
||
|
||
def img2pdf(imgs, pdf_path): | ||
def img2pdf(imgs, pdf_path, quality): | ||
""" | ||
利用图片生成pdf | ||
:param imgs: 图片列表, list类型 | ||
:param pdf_path: 保存的pdf路径(包含文件名) | ||
:param quality: 质量参数,默认为 10 | ||
:return: True 表示生成成功,False表示失败 | ||
""" | ||
intermediate_dir = os.path.join(os.path.dirname(pdf_path), 'intermediate') | ||
if not os.path.exists(intermediate_dir): | ||
os.mkdir(intermediate_dir) | ||
with fitz.open() as doc: | ||
page_count = len(imgs) | ||
for i, img in enumerate(imgs): | ||
print('正在转换: %d/%d' % (i, page_count)) | ||
imgdoc = fitz.open(img) | ||
print('正在转换: %d/%d' % (i+1, page_count)) | ||
# 生成相应质量的临时文件 | ||
tmp_img = os.path.join(intermediate_dir, os.path.basename(img)) | ||
img_obj = Image.open(img) | ||
w, h = img_obj.size | ||
img_obj.resize((int(w / 10 * quality), int(h / 10 * quality))).save(tmp_img, "JPEG") | ||
|
||
# 插入到 PDF 中 | ||
imgdoc = fitz.open(tmp_img) | ||
pdfbytes = imgdoc.convertToPDF() | ||
imgpdf = fitz.open("pdf", pdfbytes) | ||
doc.insertPDF(imgpdf) | ||
doc.save(pdf_path) | ||
shutil.rmtree(intermediate_dir) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
Pillow==8.1.1 | ||
requests==2.25.1 | ||
PyMuPDF==1.18.9 |