PDF to PNG to PDF
PDF 2 PNG
step 1, install PyMuPDF
pip install pymupdf -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
step 2, code
# encoding:utf8
import sys
import os
import fitz
if __name__ == '__main__':
if len(sys.argv) < 3:
print('Usage: python3 pdf2pic.py input.pdf output-dir')
exit()
pdf_file_path, output_dir = sys.argv[1], sys.argv[2]
doc = fitz.open(pdf_file_path)
for pg in range(doc.pageCount):
page = doc[pg]
rotate = int(0)
zoom_x = 2.0
zoom_y = 2.0
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG(output_dir + os.sep + "%d.png" % pg)
step 3, run the command
python3 pdf2png.py ../pdf/cwmt14_tutorial.pdf ../png/
PNG 2 PDF
step 1, install fitz
pip install fitz -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
step 2, code
import fitz
import os
import sys
def cmp(x):
idx, file_type = x.split('.')
return int(idx)
if __name__ == '__main__':
if len(sys.argv) < 3:
print('Uage: python3 png2pdf.py pic-dir output.pdf')
exit()
pic_dir, output_file = sys.argv[1], sys.argv[2]
doc = fitz.open()
for pic_name in sorted(os.listdir(pic_dir), key=cmp):
pic_file = pic_dir + os.sep + pic_name
print(pic_file)
imgdoc = fitz.open(pic_file)
pdfbytes = imgdoc.convertToPDF()
imgpdf = fitz.open("pdf", pdfbytes)
doc.insertPDF(imgpdf)
doc.save(output_file)
step 3, run the command
python3 png2pdf.py ../pic/ ../pdf/cwmt14_tutorial_lite.pdf