svg to png or pdf


将svg转化成png或者pdf.不过性能不好.如果svg有几十M,会很慢.

# ! encoding:UTF-8
import cairosvg
import os


def svg_to_png(from_dir, target_dir):
    """
    very slow
    :param from_dir:
    :param target_dir:
    :return:
    """
    return _export(from_dir, target_dir, "png")


def _export(from_dir, target_dir, export_type):
    files = os.listdir(from_dir)
    for fileName in files:
        path = os.path.join(from_dir, fileName)
        if os.path.isfile(path) and fileName[-3:] == "svg":
            file_handle = open(path)
            svg = file_handle.read()
            file_handle.close()
            export_path = os.path.join(target_dir, fileName[:-3] + export_type)
            export_file_handle = open(export_path, 'w')

            if export_type == "png":
                cairosvg.svg2png(bytestring=svg, write_to=export_path)
            elif export_type == "pdf":
                cairosvg.svg2pdf(bytestring=svg, write_to=export_path)

            export_file_handle.close()
,

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: