python圖片轉換pdf
阿新 • • 發佈:2018-12-26
#!/home/chao/anaconda3/envs/test_py2/bin/python
#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
#需要預告安裝支援中文的字型,如simfang從win拷貝過來安裝
def createPdf(dstpath,fileList):
img = Image.open( fileList[0].decode('UTF-8') )
c = canvas.Canvas(dstpath, img.size)#第一張圖片的尺寸新建pdf
pdfmetrics.registerFont(TTFont('simfang','simfang.ttf')) #註冊字型
fontheight=15
c.setFont('simfang',fontheight)
#c.drawString(100, 300, u'宋體宋體')
height=fontheight
num=1
for i in fileList:#標明本pdf的檔案列表
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.decode('UTF-8'), 0, 0)#轉換為中文路徑名稱開啟
c.showPage()
c.save()
def transferPdf(filePath,dstpath):
#將一個目錄下所有圖片生成一個pdf
fileList=[]
#result=os.popen(" ls -l "+filePath+"| awk \'{print $9}\' | sort -t _ -k1,1 -k2n,2 ").read()
result=os.popen(" ls "+filePath+"| sort -t _ -k1,1 -k2n,2 ").read()
currentIndex=0
pdfIndex=0
for i in result.split("\n"):
if i.strip()!='':
print i
fileList.append(os.path.join(filePath, i))
currentIndex+=1
if currentIndex == 100:#每幾頁一建立
currentIndex=0
pdfIndex+=1
createPdf( os.path.join(dstpath, str(pdfIndex)+".pdf") ,fileList)
fileList=[]
filePath = "/home/chao/img"#源圖片資料夾
dstpath="/home/chao/tmp1"#轉換出的pdf資料夾存放地址
transferPdf(filePath,dstpath)
#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
#需要預告安裝支援中文的字型,如simfang從win拷貝過來安裝
def createPdf(dstpath,fileList):
img = Image.open( fileList[0].decode('UTF-8') )
c = canvas.Canvas(dstpath, img.size)#第一張圖片的尺寸新建pdf
pdfmetrics.registerFont(TTFont('simfang','simfang.ttf')) #註冊字型
fontheight=15
c.setFont('simfang',fontheight)
#c.drawString(100, 300, u'宋體宋體')
height=fontheight
num=1
for i in fileList:#標明本pdf的檔案列表
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.decode('UTF-8'), 0, 0)#轉換為中文路徑名稱開啟
c.showPage()
c.save()
def transferPdf(filePath,dstpath):
#將一個目錄下所有圖片生成一個pdf
fileList=[]
#result=os.popen(" ls -l "+filePath+"| awk \'{print $9}\' | sort -t _ -k1,1 -k2n,2 ").read()
result=os.popen(" ls "+filePath+"| sort -t _ -k1,1 -k2n,2 ").read()
currentIndex=0
pdfIndex=0
for i in result.split("\n"):
if i.strip()!='':
print i
fileList.append(os.path.join(filePath, i))
currentIndex+=1
if currentIndex == 100:#每幾頁一建立
currentIndex=0
pdfIndex+=1
createPdf( os.path.join(dstpath, str(pdfIndex)+".pdf") ,fileList)
fileList=[]
filePath = "/home/chao/img"#源圖片資料夾
dstpath="/home/chao/tmp1"#轉換出的pdf資料夾存放地址
transferPdf(filePath,dstpath)