Skip to content

Commit

Permalink
更新一个pdf压缩代码
Browse files Browse the repository at this point in the history
  • Loading branch information
Leroll committed Mar 20, 2024
1 parent c88c5c2 commit babe636
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
*.xmind

*.DS_Store
46 changes: 46 additions & 0 deletions utils/pdf_compress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import fitz
import os

def covert2pic(zoom):
if os.path.exists('.pdf'):
os.removedirs('.pdf')
os.mkdir('.pdf')
for pg in range(totaling):
page = doc.load_page(pg)
zoom = int(zoom)
lurl = '.pdf/%s.png' % str(pg+1)
trans = fitz.Matrix(zoom/100.0,zoom/100.0)
pm = page.get_pixmap(matrix=trans,alpha=False)
pm.save(lurl)
print(page)
doc.close()

def pic2pdf(obj):
doc = fitz.open()
for pg in range(totaling):
img = '.pdf/%s.png' % str(pg+1)
imgdoc = fitz.open(img)
pdfbytes = imgdoc.convert_to_pdf()
imgpdf = fitz.open("pdf",pdfbytes)
os.remove(img)
doc.insert_pdf(imgpdf)
if os.path.exists(obj):
os.remove(obj)
doc.save(obj)
doc.close()

def pdfz(sor,obj,zoom):
covert2pic(zoom)
pic2pdf(obj)

if __name__ == "__main__":
# ===============================================
# 运行前修改以下三个参数, 测试了下,效果不是太好
zoom = 20 #50代表缩小50%,200代表放大200%,100代表既不放大也不缩小
sor = 'xx.pdf' #输入文件名
obj = 'c_xx.pdf' #输出文件名
# ===============================================
doc = fitz.open(sor)
totaling = doc.page_count
pdfz(sor,obj,zoom)
os.removedirs('.pdf')

0 comments on commit babe636

Please sign in to comment.