#!/usr/bin/env python3 # Copyright 2016 Søren Hauberg # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys from subprocess import call import xml.etree.ElementTree as ET import tempfile import shutil import os.path def convert(infile, outfile): sozi_namespace = 'http://sozi.baierouge.fr' svg_namespace = 'http://www.w3.org/2000/svg' tree = ET.parse(infile) root = tree.getroot() ## Find frames frames = [] hide_frame = [] for elem in root.findall('{'+sozi_namespace+'}frame'): frames.append(elem.get('{'+sozi_namespace+'}refid')) hide_frame.append(elem.get('{'+sozi_namespace+'}hide')=='true') ## Make the frames hidden for layer in root.findall('{'+svg_namespace+'}g'): for rect in layer.findall('{'+svg_namespace+'}rect'): fid = rect.get('id') if fid in frames: if hide_frame[frames.index(fid)]: style = rect.get('style') style = style + ';display:none' #style = style + ';visibility:hidden' rect.set('style', style) ## Print each frame dirpath = tempfile.mkdtemp() tmpsvg = os.path.join(dirpath, 'tmp.svg') framefns = [] for layer in root.findall('{'+svg_namespace+'}g'): for rect in layer.findall('{'+svg_namespace+'}rect'): fid = rect.get('id') if fid in frames: ## Set page to match current frame framenum = frames.index(fid) x = rect.get('x') y = rect.get('y') width = rect.get('width') height = rect.get('height') viewbox = '{} {} {} {}'.format(x, y, width, height) root.set('viewBox', viewbox) root.set('height', height) root.set('width', width) ## Write temporary SVG and print frame tree.write(tmpsvg) framefn = os.path.join(dirpath, 'frame_{num:05d}.pdf'.format(num=framenum)) framefns.append(framefn) call(['inkscape', '-f', tmpsvg, '--export-pdf='+framefn]) framefns.sort() ## Join individual PDFs to the requested output PDF cmd = framefns cmd.insert(0, 'pdfunite') cmd.append(outfile) call(cmd) ## Clean up shutil.rmtree(dirpath) if __name__ == "__main__": progname = 'sozi2pdf' if len(sys.argv) < 2: print('{}: not enough input arguments.\nSyntax: {} inputfile [outputfile]\n'.format(progname, progname)) sys.exit(-1) infn = sys.argv[1] if len(sys.argv) < 3: if infn[-3:] == 'svg': outfn = infn[:-3] + 'pdf' else: outfn = infn + '.pdf' else: outfn = sys.argv[2] convert(infn, outfn)