Code

640c9ede4c1979dbc3818bd595b3243cefb31ed4
[inkscape.git] / share / extensions / svg_and_media_zip_output.py
1 #!/usr/bin/env python
2 """
3 svg_and_media_zip_output.py
4 An extention which collects all images to the documents directory and
5 creates a zip archive containing all images and the document
7 Copyright (C) 2005 Pim Snel, pim@lingewoud.com
8 Copyright (C) 2008 Aaron Spike, aaron@ekips.org
9 this is  the first Python script  ever created
10 its based on embedimage.py
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 Version 0.5 (Nicolas Dufour, nicoduf@yahoo.fr)
27     Fix a bug related to special caracters in the path (LP #456248).
29 TODO
30 - fix bug: not saving existing .zip after a Collect for Output is run
31      this bug occurs because after running an effect extention the inkscape:output_extension is reset to svg.inkscape
32      the file name is still xxx.zip. after saving again the file xxx.zip is written with a plain .svg which
33      looks like a corrupt zip
34 - maybe add better extention
35 - consider switching to lzma in order to allow cross platform compression with no encoding problem...
36 """
38 import inkex
39 import urlparse
40 import urllib
41 import os, os.path
42 import string
43 import zipfile
44 import shutil
45 import sys
46 import tempfile
47 import gettext
48 _ = gettext.gettext
50 class SVG_and_Media_ZIP_Output(inkex.Effect):
51     def __init__(self):
52         inkex.Effect.__init__(self)
53         if os.name == 'nt':
54             self.encoding = "cp437"
55         else:
56             self.encoding = "latin-1"     
58     def output(self):
59         out = open(self.zip_file,'rb')
60         if os.name == 'nt':
61             try:
62                 import msvcrt
63                 msvcrt.setmode(1, os.O_BINARY)
64             except:
65                 pass
66         sys.stdout.write(out.read())
67         out.close()
68         self.clear_tmp()
70     def clear_tmp(self):
71         shutil.rmtree(self.tmp_dir)
73     def effect(self):
74         ttmp_orig = self.document.getroot()
76         docname = ttmp_orig.get(inkex.addNS('docname',u'sodipodi'))
77         if docname is None: docname = self.args[-1]
79         #create os temp dir
80         self.tmp_dir = tempfile.mkdtemp()
82         #fixme replace whatever extention
83         docstripped = docname.replace('.zip', '')
84         docstripped = docstripped.replace('.svg', '')
85         docstripped = docstripped.replace('.svgz', '')
86         
87         # create destination zip in same directory as the document
88         self.zip_file = os.path.join(self.tmp_dir, docstripped) + '.zip'
89         z = zipfile.ZipFile(self.zip_file, 'w')
91         #read tmpdoc and copy all images to temp dir
92         for node in self.document.xpath('//svg:image', namespaces=inkex.NSS):
93             self.collectAndZipImages(node, docname, z)
95         ##copy tmpdoc to tempdir
96         dst_file = os.path.join(self.tmp_dir, docstripped)
97         stream = open(dst_file,'w')
99         self.document.write(stream)
101         stream.close()
103         z.write(dst_file,docstripped.encode(self.encoding)+'.svg')
105         z.close()
107     def collectAndZipImages(self, node, docname, z):
108         xlink = node.get(inkex.addNS('href',u'xlink'))
109         if (xlink[:4]!='data'):
110             absref=node.get(inkex.addNS('absref',u'sodipodi'))
111             url=urlparse.urlparse(xlink)
112             href=urllib.url2pathname(url.path)
113             
114             if (href != None):
115                 absref=os.path.realpath(href)
117             absref=unicode(absref, "utf-8")
119             if (os.path.isfile(absref)):
120                 shutil.copy(absref, self.tmp_dir)
121                 z.write(absref, os.path.basename(absref).encode(self.encoding))
122             elif (os.path.isfile(os.path.join(self.tmp_dir, absref))):
123                 #TODO: please explain why this clause is necessary
124                 shutil.copy(os.path.join(self.tmp_dir, absref), self.tmp_dir)
125                 z.write(os.path.join(self.tmp_dir, absref),
126                         os.path.basename(absref).encode(self.encoding))
127             else:
128                 inkex.errormsg(_('Could not locate file: %s') % absref)
130             node.set(inkex.addNS('href',u'xlink'),os.path.basename(absref))
131             node.set(inkex.addNS('absref',u'sodipodi'),os.path.basename(absref))
134 if __name__ == '__main__':   #pragma: no cover
135     e = SVG_and_Media_ZIP_Output()
136     e.affect()
139 # vim: expandtab shiftwidth=4 tabstop=8 softtabstop=4 fileencoding=utf-8 textwidth=99