欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现批量把SVG格式转成png、pdf格式的代码分享

程序员文章站 2023-11-22 12:21:58
需要提前安装cairosvg模块,下载地址 code: #! encoding:utf-8 import cairosvg import os  ...

需要提前安装cairosvg模块,下载地址

code:

#! encoding:utf-8
import cairosvg
import os
 
loop = true
while loop:
    svgdir = raw_input("请输入svg文件目录")
    if os.path.exists(svgdir) and os.path.isdir(svgdir):
        loop = false
    else:
        print "错误:您输入的svg文件目录不存在或者不是一个有效的目录,请重新输入"
 
loop = true
while 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 = true
while 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