需要提前安裝cairosvg模組,下載地址http://cairosvg.org/download/
Code:
#! encoding:UTF-8import cairosvgimport os loop = Truewhile loop: svgDir = raw_input("請輸入SVG檔案目錄") if os.path.exists(svgDir) and os.path.isdir(svgDir): loop = False else: print "錯誤:您輸入的SVG檔案目錄不存在或者不是一個有效目錄,請重新輸入" loop = Truewhile loop: exportDir = raw_input("請輸入匯出目錄") if os.path.exists(exportDir): loop = False else: print "錯誤:您輸入的匯出目錄[" , exportDir , "] 不存在,是否要建立這個目錄?" loops = True while loops: msg = "" cmd = raw_input("建立 (Y) 重新 (R)") if cmd.upper() == "R": loops = False elif cmd.upper() == "Y": os.makedirs(exportDir, True) if os.path.exists(exportDir): loop = False loops = False else: print "建立目錄失敗[",exportDir,"], 請重新輸入" else: print "找不到您輸入的命令,請重新輸入" cate = ("png", "pdf")print "匯出類型:"for i in cate: print i loop = Truewhile loop: exportFormat = raw_input("請輸入匯出類型") if exportFormat.lower() in cate: loop = False else: print "您輸入的類型不存在,請重新輸入" def export(fromDir, targetDir, exportType): print "開始執行轉換命令..." files = os.listdir(fromDir) num = 0 for fileName in files: path = os.path.join(fromDir,fileName) if os.path.isfile(path) and fileName[-3:] == "svg": num += 1 fileHandle = open(path) svg = fileHandle.read() fileHandle.close() exportPath = os.path.join(targetDir, fileName[:-3] + exportType) exportFileHandle = open(exportPath,'w') if exportType == "png": cairosvg.svg2png(bytestring=svg, write_to=exportPath) elif exportType == "pdf": cairosvg.svg2pdf(bytestring=svg, write_to=exportPath) exportFileHandle.close() print "Success Export ", exportType, " -> " , exportPath print "已匯出 ", num, "個檔案"export(svgDir, exportDir, exportFormat)
使用:
複製代碼 代碼如下:
請輸入SVG檔案目錄d:\svg
請輸入匯出目錄d:\images
錯誤:您輸入的匯出目錄[ d:\images ] 不存在,是否要建立這個目錄?
建立 (Y) 重新 (R)Y
匯出類型:
png
pdf
請輸入匯出類型png
開始執行轉換命令...
Success Export png -> d:\images\a.png
Success Export png -> d:\images\db2.png
Success Export png -> d:\images\db3.png
已匯出 3 個檔案
複製代碼 代碼如下:
D:\>tree svg /F
Folder PATH listing
Volume serial number is 4603-09B2
D:\SVG
a.svg
db2.svg
db3.svg
No subfolders exist
D:\>tree images /F
Folder PATH listing
Volume serial number is 4603-09B2
D:\IMAGES
a.png
db2.png
db3.png
No subfolders exist