-
Notifications
You must be signed in to change notification settings - Fork 12
/
export_layers.py
373 lines (313 loc) · 13.8 KB
/
export_layers.py
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env python3
import contextlib
import copy
from dataclasses import dataclass
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from typing import List, Tuple
if sys.platform == 'linux': sys.path.append('/usr/share/inkscape/extensions') # noqa
if sys.platform == 'win32': sys.path.append(r'c:\Program Files\Inkscape\share\inkscape\extensions') # noqa
import inkex
# inkex.localization.localize()
@dataclass
class Group:
id: str
label: str # tag + name
name: str
tag: str
is_visible: bool
@dataclass
class Export:
visible_layers: List[str]
file_name: str
FIXED = '[fixed]'
F = '[f]'
EXPORT = '[export]'
E = '[e]'
PDF = 'pdf'
SVG = 'svg'
PNG = 'png'
JPEG = 'jpeg'
class LayerExport(inkex.Effect):
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument('-o', '--output-dir',
type=Path,
default='~/',
help='Path to output directory')
parser.add_argument('--prefix',
default='',
help='Prefix for exported file names')
parser.add_argument('--visible-only',
type=inkex.Boolean,
help="Export visible layers only")
parser.add_argument('--enumerate',
type=inkex.Boolean,
help="Extra prefix for exported file names")
parser.add_argument('-f', '--file-type',
choices=(PDF, PNG, SVG, JPEG),
help='Exported file type')
parser.add_argument('--fit-contents',
type=inkex.Boolean,
help='Fit output to content bounds')
parser.add_argument('--dpi',
type=int,
help="Export DPI value")
parser.add_argument('--show-layers-below',
type=inkex.Boolean,
help="Show exported layers below the current layer")
def effect(self):
output_dir = self.options.output_dir
# If a directory is not specified, Inkscape passes '~'.
# Inkscape treats relative paths w.r.t. the extension directory,
# which is working directory at the same time.
# Possible cases (user input -> extension input -> extension output):
# User: '' -> input: '~' -> output: '/svg_dir'
# User: '~' -> input: '/ext_dir/~' -> output: '/home_dir'
# User: 'rel_path' -> input: '/ext_dir/rel_path' -> output: '/svg_dir/rel_path'
# User: '.' -> input: '/ext_dir' -> output: '/svg_dir'
# User: 'abs_path' -> input: '/abs_path' -> output: '/abs_path'
if output_dir == Path('~'):
# Output directory is unspecified by a user
output_dir = Path(self.svg_path())
else:
try:
# Make the directory relative to the SVG directory
# self.ext_path() is empty in Inkscape 1.2.1 so calculate
ext_path = Path(__file__).parent.absolute()
output_dir = output_dir.relative_to(ext_path)
# Expand possible '~' in the middle of the path
output_dir = output_dir.expanduser()
if not output_dir.is_absolute():
# No ~ in the middle, truly relative path
output_dir = self.svg_path() / output_dir
except ValueError:
pass
output_dir.mkdir(parents=True, exist_ok=True)
# Check if there are erroneously tagged groups
tagged_group_list = self.get_group_list(layers=False)
if tagged_group_list:
print('WARNING!\n'
f'Only {"visible " if self.options.visible_only else ""}'
'tagged layers participate in exporting.\n'
'These groups are tagged perhaps by mistake:\n'
f'{", ".join(group.label for group in tagged_group_list)}\n',
file=sys.stderr)
layer_list = self.get_group_list(layers=True)
# print('Found layers: ' +
# ', '.join(f'{layer.id}/{layer.name}' for layer in layer_list),
# file=sys.stderr)
export_list = self.get_export_list(
layer_list, self.options.show_layers_below, self.options.visible_only)
if not export_list:
print('WARNING!\n'
'Nothing to export.\n'
'There are no '
f'{"visible " if self.options.visible_only else ""}'
f'layers tagged with {EXPORT} or {E}\n',
file=sys.stderr)
with _make_temp_directory() as tmp_dir:
for export_idx, export in enumerate(export_list):
# print(f'({export_idx}/{len(export_list)})'
# f' Exporting layers [{", ".join(export.visible_layers)}]'
# f' as {export.file_name}... ', end='', file=sys.stderr)
remove_layers = (self.options.file_type == SVG)
svg_file = self.export_to_svg(export, tmp_dir, remove_layers)
if self.options.file_type == PNG:
if not self.convert_svg_to_png(svg_file, output_dir,
self.options.prefix):
break
elif self.options.file_type == SVG:
if not self.convert_svg_to_svg(svg_file, output_dir,
self.options.prefix):
break
elif self.options.file_type == PDF:
if not self.convert_svg_to_pdf(svg_file, output_dir,
self.options.prefix):
break
elif self.options.file_type == JPEG:
if not self.convert_png_to_jpeg(
self.convert_svg_to_png(svg_file, tmp_dir,
self.options.prefix),
output_dir,
prefix=''):
break
def get_group_list(self, layers: bool) -> List[Group]:
"""
Make a list of groups in source svg file
"""
if layers:
xpath_query = '//svg:g[@inkscape:groupmode="layer"]'
else:
xpath_query = '//svg:g[not(@inkscape:groupmode="layer")]'
group_xml_list = self.document.xpath(xpath_query, namespaces=inkex.NSS)
group_list = []
for group_xml in group_xml_list:
label_attrib_name = '{%s}label' % group_xml.nsmap['inkscape']
if label_attrib_name not in group_xml.attrib:
continue
id = group_xml.attrib['id']
label = group_xml.attrib[label_attrib_name]
is_visible = group_xml.attrib.get('style') == 'display:inline'
tag = ''
label_lower = label.lower()
if label_lower.startswith(FIXED):
tag = FIXED
name = label[len(FIXED):].lstrip()
elif label_lower.startswith(F):
tag = FIXED
name = label[len(F):].lstrip()
elif label_lower.startswith(EXPORT):
tag = EXPORT
name = label[len(EXPORT):].lstrip()
elif label_lower.startswith(E):
tag = EXPORT
name = label[len(E):].lstrip()
if not tag:
continue
group_list.append(Group(id=id,
label=label,
name=name,
tag=tag,
is_visible=is_visible))
return group_list
def get_export_list(self,
layer_list: List[Group],
show_layers_below: bool,
visible_only: bool) -> List[Export]:
"""
Select layers that should be visible.
Each element of this list will be exported as a separate file
"""
export_list: List[Export] = []
for counter, layer in enumerate(layer_list):
# each layer marked as '[export]' is the basis for making a figure that will be exported
if visible_only and not layer.is_visible:
continue
if layer.tag == FIXED:
# Fixed layers are not the basis of exported figures
continue
elif layer.tag == EXPORT:
# determine which other layers should appear in this figure
visible_layers = set()
layer_is_below = True
for other_layer in layer_list:
if other_layer.tag == FIXED:
# fixed layers appear in all figures
# irrespective of their position relative to other layers
visible_layers.add(other_layer.id)
elif other_layer.id == layer.id:
# the basis layer for this figure is always visible
visible_layers.add(other_layer.id)
# all subsequent layers will be above
layer_is_below = False
elif layer_is_below and show_layers_below:
visible_layers.add(other_layer.id)
layer_name = layer.name
if self.options.enumerate:
layer_name = '{:03d}_{}'.format(counter + 1, layer_name)
export_list.append(Export(visible_layers, layer_name))
else:
# layers not marked as FIXED of EXPORT are ignored
pass
return export_list
def export_to_svg(self, export: Export, output_dir: Path,
remove_layers: bool) -> Path:
"""
Export a current document to an Inkscape SVG file.
:arg Export export: Export description.
:arg str output_dir: Path to an output directory.
:arg boo remove_layers: Remove non-exported layers.
:return Output file path.
"""
document = copy.deepcopy(self.document)
# Only process high-level layers, treat sub-layers as groups
svg_layers = document.xpath('/svg:svg/svg:g[@inkscape:groupmode="layer"]',
namespaces=inkex.NSS)
for layer in svg_layers:
if layer.attrib['id'] in export.visible_layers:
layer.attrib['style'] = 'display:inline'
elif remove_layers:
document.getroot().remove(layer)
else:
layer.attrib['style'] = 'display:none'
output_file = output_dir / (export.file_name + '.svg')
document.write(str(output_file))
return output_file
def convert_svg_to_png(self, svg_file: Path, output_dir: Path,
prefix: str) -> Path:
"""
Convert an SVG file into a PNG file.
:param str svg_file: Path an input SVG file.
:param str output_dir: Path to an output directory.
:return Output file path.
"""
return self._convert_svg(svg_file, output_dir, prefix, 'png')
def convert_svg_to_svg(self, svg_file: Path, output_dir: Path,
prefix: str) -> Path:
"""
Convert an [Inkscape] SVG file into a standard (plain) SVG file.
:param str svg_file: Path an input SVG file.
:param str output_dir: Path to an output directory.
:return Output file path.
"""
return self._convert_svg(svg_file, output_dir, prefix, 'svg',
['--export-plain-svg', '--vacuum-defs'])
def convert_svg_to_pdf(self, svg_file, output_dir, prefix):
"""
Convert an [Inkscape] SVG file into a PDF.
:param str svg_file: Path an input SVG file.
:param str output_dir: Path to an output directory.
:return Output file path.
"""
return self._convert_svg(svg_file, output_dir, prefix, 'pdf')
def _convert_svg(self, svg_file: Path, output_dir: Path,
prefix: str, out_type: str, extra_args=()) -> Path:
output_file = output_dir / (prefix + svg_file.stem + '.' + out_type)
command = [
'inkscape', str(svg_file),
'--export-area-drawing' if self.options.fit_contents else
'--export-area-page',
'--export-dpi=' + str(self.options.dpi),
'--export-type', out_type,
'--export-filename', str(output_file),
] + list(extra_args)
try:
subprocess.check_call(command)
except Exception as e:
raise Exception(
f'Failed to convert {svg_file} to {output_file}.\n{e}')
return output_file
def convert_png_to_jpeg(self,
png_file: Path,
output_dir: Path,
prefix: str) -> Path:
"""
Convert a PNG file into a JPEG file.
:param str png_file: Path an input PNG file.
:param str output_dir: Path to an output directory.
:return Output file path.
"""
output_file = output_dir / (prefix + png_file.stem + '.jpeg')
from PIL import Image
image = Image.open(png_file)
image = image.convert('RGB')
image.save(output_file, quality=95)
return output_file
@contextlib.contextmanager
def _make_temp_directory():
temp_dir = tempfile.mkdtemp(prefix='tmp-inkscape')
try:
yield Path(temp_dir)
finally:
shutil.rmtree(temp_dir)
if __name__ == '__main__':
try:
LayerExport().run(output=False)
except Exception as e:
import traceback
inkex.errormsg(traceback.format_exc(e))
sys.exit(1)