使用Python批量转换SVG文件为PNG或PDF文件

使用Python批量转换SVG文件为PNG或PDF文件

  • 使用Python批量转换SVG文件为PNG或PDF文件
    • 使用模块
      • 1 模块单独使用
      • 2 模块用于代码
    • 实例
      • 1 命令行方式
      • 2 python脚本

使用Python批量转换SVG文件为PNG或PDF文件。

1. 使用模块

cairosvg模块可以对svg格式图片进行转换和处理的python模块,下载地址( http://cairosvg.org/download/),安装方法:pip install cairosvg

1.1 模块单独使用

Usage: cairosvg.py filename [options]

Options:
-h, –help show this help message and exit
-v, –version show version and exit
-f FORMAT, –format=FORMAT
output format
-d DPI, –dpi=DPI ratio between 1in and 1px
-o OUTPUT, –output=OUTPUT
output filename

1.2 模块用于代码

提供API接口:
svg2pdf
svg2png

2. 实例

2.1 命令行方式

# Convert to pdf, standard output
cairosvg test.svg

# Convert to png, standard output
cairosvg test.svg -f png

# Convert to ps, write to test.ps
cairosvg test.svg -o test.ps

# Convert an SVG string to pdf, standard output
echo "<svg height='30' width='30'>\
      <text y='10'>123</text>\
      </svg>" | cairosvg -

2.2 python脚本

#! encoding:UTF-8
import cairosvg
import os

def exportsvg(fromDir, targetDir, exportType):
    print "开始执行转换命令..."
    num = 0
    for a,f,c in os.walk(fromDir):#使用walk遍历源目录
        for fileName in c:
            path = os.path.join(a,fileName)#获得文件路径
            if os.path.isfile(path) and fileName[-3:] == "svg":#判断文件是否为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":
                    try:
                        cairosvg.svg2png(bytestring=svg, write_to=exportPath)#转换为png文件
                    except:
                        print "error in convert svg file : %s to png."%(path)                   

                elif exportType == "pdf":
                    try:
                        cairosvg.svg2pdf(bytestring=svg, write_to=exportPath)#转换为pdf文件
                    except:
                        print "error in convert svg file: %s to pdf."%(path)                   

                exportFileHandle.close()
                print "Success Export ", exportType, " -> " , exportPath

    print "已导出 ", num, "个文件"#统计转换文件数量
#---------------------------------------
svgDir = '/home//tools/icons'#svg文件夹路径
exportDir = '/home/ubuntu/tools/icons1'#目的文件夹路径
exportFormat = 'png'#pdf#转换类型
if not os.path.exists(exportDir):
    os.mkdir(exportDir)
exportsvg(svgDir, exportDir, exportFormat)#转换主函数
#---------------------------------------

cairosvg使用简单,转换方便。

猜你喜欢

转载自www.linuxidc.com/Linux/2017-01/139975.htm