File: svg2pdf

package info (click to toggle)
python-svglib 1.5.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 332 kB
  • sloc: python: 2,736; sh: 6; makefile: 3
file content (129 lines) | stat: -rw-r--r-- 3,687 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/bin/env python
"""A simple converter from SVG to PDF.

For further information please check the file README.txt!
"""

import sys
import argparse
import textwrap
from datetime import datetime
from os.path import dirname, basename, splitext, exists

from reportlab.graphics import renderPDF

from svglib import svglib


def svg2pdf(path, outputPat=None):
    "Convert an SVG file to a PDF one."

    # derive output filename from output pattern
    file_info = {
        'dirname': dirname(path) or '.',
        'basename': basename(path),
        'base': basename(splitext(path)[0]),
        'ext': splitext(path)[1],
        'now': datetime.now(),
        'format': 'pdf'
    }
    out_pattern = outputPat or '%(dirname)s/%(base)s.%(format)s'
    # allow classic %%(name)s notation
    out_path = out_pattern % file_info
    # allow also newer {name} notation
    out_path = out_path.format(**file_info)

    # generate a drawing from the SVG file
    try:
        drawing = svglib.svg2rlg(path)
    except:
        print('Rendering failed.')
        raise

    # save converted file
    if drawing:
        renderPDF.drawToFile(drawing, out_path, showBoundary=0)


# command-line usage stuff

def _main():
    ext = 'pdf'
    ext_caps = ext.upper()
    args = dict(
        prog=basename(sys.argv[0]),
        version=svglib.__version__,
        author=svglib.__author__,
        license=svglib.__license__,
        copyleft_year=svglib.__date__[:svglib.__date__.find('-')],
        ts_pattern="{{dirname}}/out-"\
                   "{{now.hour}}-{{now.minute}}-{{now.second}}-"\
                   "%(base)s",
        ext=ext,
        ext_caps=ext_caps
    )
    args['ts_pattern'] += ('.%s' % args['ext'])
    desc = '{prog} v. {version}\n'.format(**args)
    desc += 'A converter from SVG to {} (via ReportLab Graphics)\n'.format(ext_caps)
    epilog = textwrap.dedent('''\
        examples:
          # convert path/file.svg to path/file.{ext}
          {prog} path/file.svg

          # convert file1.svg to file1.{ext} and file2.svgz to file2.{ext}
          {prog} file1.svg file2.svgz

          # convert file.svg to out.{ext}
          {prog} -o out.{ext} file.svg

          # convert all SVG files in path/ to PDF files with names like:
          # path/file1.svg -> file1.{ext}
          {prog} -o "%(base)s.{ext}" path/file*.svg

          # like before but with timestamp in the PDF files:
          # path/file1.svg -> path/out-12-58-36-file1.{ext}
          {prog} -o {ts_pattern} path/file*.svg

        issues/pull requests:
            https://github.com/deeplook/svglib

        Copyleft by {author}, 2008-{copyleft_year} ({license}):
            https://www.gnu.org/licenses/lgpl-3.0.html'''.format(**args))
    p = argparse.ArgumentParser(
        description=desc,
        epilog=epilog,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    p.add_argument('-v', '--version',
        help='Print version number and exit.',
        action='store_true')

    p.add_argument('-o', '--output',
        metavar='PATH_PAT',
        help='Set output path (incl. the placeholders: dirname, basename,'
             'base, ext, now) in both, %%(name)s and {name} notations.'
    )

    p.add_argument('input',
        metavar='PATH',
        nargs='*',
        help='Input SVG file path with extension .svg or .svgz.')

    args = p.parse_args()

    if args.version:
        print(svglib.__version__)
        sys.exit()

    if not args.input:
        p.print_usage()
        sys.exit()

    paths = [a for a in args.input if exists(a)]
    for path in paths:
        svg2pdf(path, outputPat=args.output)


if __name__ == '__main__':
    _main()