Skip to content

Instantly share code, notes, and snippets.

@swinghu
Last active April 20, 2018 10:05
Show Gist options
  • Save swinghu/3eec3bd800252798cba0a845e48a5a6e to your computer and use it in GitHub Desktop.
Save swinghu/3eec3bd800252798cba0a845e48a5a6e to your computer and use it in GitHub Desktop.
# coding:utf-8
import os
import sys
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from PIL import Image
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
"""
convert all the image file(in one directory) to one pdf file
"""
def createPdf(dstpath,fileList):
img = Image.open(fileList[0])
c = canvas.Canvas(dstpath, pagesize=landscape(A4)) # A4
(w,h) = landscape(A4)
pdfmetrics.registerFont(TTFont('simfang','simfang.ttf')) #font
fontheight= h / (len(fileList) +2)
c.setFont('simfang',fontheight)
height=fontheight
num=1
for i in fileList:
# show the table of contents
c.drawString(fontheight, height, str(num)+"/"+str(len(fileList)))
c.drawString(fontheight+50, height, os.path.split(i)[1])
num += 1
height+=fontheight
c.showPage()
for i in fileList:
c.drawImage(i, 0, 0, w, h) # A4 w,h
c.showPage()
c.save()
def transferPdf(filePath,dstpath):
filepathList = listDir(filePath)
createPdf(os.path.join(dstpath, "output.pdf"), filepathList)
def listDir(rootDir):
result = []
files = os.listdir(rootDir)
for i in range(0,len(files)):
print(files[i])
path = os.path.join(rootDir, files[i])
if os.path.isfile(path):
result.append(path)
return result
filePath = "E:\\pic-book\\big\\" #source image file fold
dstpath="E:\\pic-book\\big\\" #the save pdf file fold
transferPdf(filePath,dstpath)
@swinghu
Copy link
Author

swinghu commented Apr 20, 2018

convert images to pdf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment