This repository has been archived by the owner on Sep 25, 2023. It is now read-only.
/
bmconverter.py
executable file
·2071 lines (1875 loc) · 79.7 KB
/
bmconverter.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Michael Goerz
#
# 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 <http://www.gnu.org/licenses/>.
"""
This script converts between the bookmark description formats used by different
pdf and djvu bookmarking tools such as pdftk, the iText toolbox, pdfLaTeX,
pdfWriteBookmarks, jpdftweak, djvused, and the DJVU Bookmark Tool.
It operates on text files in the various supported formats that describe the
bookmark structure in pdf or djvu files. You can then use the aforementioned
tools to add the described bookmarks to the pdf or djvu file.
The script includes some rudimentary functionality to extract the bookmarks
directly from a pdf file (writing to any of the supported text formats). This
functionality depends on the pdfminer library. Advanced features like
formatting of the bookmark titles are not supported in the extraction.
In addition to converting between the different formats, the script can also
shift the page numbers associated with the bookmarks. This is useful if you need
to work on a file obtained from a table of contents, where the page numbers in
the pdf might not match the page numbers in the original document, for example.
When used as a module from python, this script provides a toolbox for making
arbitrary modifications to the bookmark data
Script Usage
============
Usage: bmconverter.py options inputfile [outputfile]
Command Line Options
--mode in2out Sets the script's operation mode. This option is required.
-m in2out Short for --mode
--offset integer Shifts all pagenumber by integer
-o integer Short for --offset
--long When used with the 'text' output format, enables the use
of full destinations, instead of just page numbers
-l Short for --long
--pdf FILENAME Set metadata['pdf'] to the given filename. When used
together with the latex output mode, the resulting tex
file will reference the given filename.
--help Displays full help
-h Short for -help
In the mode option, 'in' and 'out' can be any of the supported formats:
'xml', 'text', 'pdftk', 'csv', 'djvused', 'latex', or 'html'
Additionally, 'in' can be 'pdf', in which case the bookmarks are read directly
from the given pdf file. The pdfminer library must be installed for this to
work.
An example usage is 'bmconverter.py --offset 2 --mode xml2text bm.xml bm.txt'
All data is read and written in UTF-8 encoding, with the exception of xml files,
which are read in the encoding declared in their header, but always written in
UTF-8
The XML Format
==============
The XML format supports more of the pdf bookmark than any of the other tools.
It is used by the iText toolbox.
Two examples of such XML files would be
<?xml version="1.0" encoding="ISO8859-1"?>
<Bookmark>
<Title Action="GoTo" Page="1 XYZ 300 800 0" >root
<Title Action="GoTo" Open="false" Page="1 FitH 500" >sub 1
<Title Action="GoTo" Page="1 FitBV 100" >sub 2.1</Title>
<Title Action="GoTo" Page="1 Fit" >sub 2.2</Title>
</Title>
<Title Action="GoTo" Page="1 FitR 200 300 400 500" >sub 2</Title>
</Title>
</Bookmark>
<?xml version="1.0" encoding="ISO8859-1"?>
<Bookmark>
<Title Action="GoTo" Named="Title" >Go to the top of the page</Title>
<Title Color="0 0.50196 0.50196" Style="bold" >
Toggle the state of the answers</Title>
<Title Open="false" >Useful links
<Title Action="URI" URI="http://www.lowagie.com/iText" >
Bruno's iText site</Title>
<Title Action="URI" URI="http://itextpdf.sourceforge.net/" >
Paulo's iText site</Title>
<Title Action="URI" URI="http://sourceforge.net/projects/itext/" >
iText @ SourceForge</Title>
</Title>
<Title >빈집</Title>
<Title Action="GoTo" Style="italic" Page="2 FitB" >
What's on page 2?</Title>
</Bookmark>
For more details, see the iText documentation.
The Text Format
===============
The text format's purpose is to provide a format that is easier to write by hand
than the XML format that iText can put in a PDF file. The text format cannot
handle all the features the XML format can. It is intended to be used for only
basic bookmarks: a hirarchy of bookmarks, each pointing a page, without further
formatting, external destinations, etc.
The format is used by the pdfWriteBookmarks tool.
The format of the text file is simple: each bookmark is represented by a single
line. The bookmark's level is taken from the indentation. There must be exactly
4 spaces indentation per level. Next is the title of the Bookmark, then a double
colon, and lastly the pagenumber, optionally followed by a destination.
An example bookmark text file is:
Page 1 :: 1
Page 2 :: 2 XYZ null null null
Page 3 :: 3
Sublevels on page 4 :: 4
Sub1 :: 5 XYZ 0 10 null
Sub2 :: 5 XYZ 0 20 null
Sub3 :: 6 XYZ 0 30 null
SubSub1 :: 6
SubSub2:: 6
Sub4 :: 7
SubSub1 :: 8
SubSub2 :: 9
Sub5 :: 10
Page 11 :: 11
Specifically, each line is matched by the following regular expression:
(?P<indent>\s*)
(?P<text>\S.*) :: [ ]* (?P<page>[0-9]*)
[ ]* (?P<dest> (XYZ.*) | (Fit.*))? [ ]*
The full destinations (e.g. 'XYZ 0 10 null') are only printed if if the --long
option is used.
Note that this format is very limited: it does not express actions other than
GoTo, preserve leading or trailing whitespace in a title, or express titles
that consist only of whitespaces.
The pdftk Format
===============
In the pdftk format, each bookmark is described by three lines, like this:
BookmarkTitle: Page1
BookmarkLevel: 1
BookmarkPageNumber: 1
Lines not belonging to this structure are discarded.
The format is the direct output of the pdftk utility, when run as
#> pdftk file.pdf dumpdata
The html Format
===============
This format is a HTML file with a special structure. Such files are produced by
Adobe Acrobat when you export a PDF file to HTML. They are also used as the
input for the DJVU Bookmark Tool.
An example of the format is the following:
<html>
<body>
<ul>
<li><a href="#1">Link to page 1</a></li>
<li><a href="#2">Link to page 2</a></li>
<li><a href="#3">Chapter 1</a>
<ul>
<li><a href="#4">Link to page 4</a></li>
<li><a href="#5">Link to page 5</a></li>
</ul>
</li>
<li><a href="">Chapter 2, no link here</a>
<ul>
<li><a href="#6">Subsection</a>
<ul>
<li><a href="#7">Link to page 7</a></li>
<li><a href="#8">Link to page 8</a></li>
</ul>
</li>
<li><a href="#9">Link to page 9</a></li>
</ul>
</li>
<li><a href="book.djvu#10">Link to page 10 in book.djvu</a></li>
<li><a href="http://windjview.sourceforge.net">Web link</a></li>
</ul>
</body>
</html>
The csv Format
==============
The csv format is read and writen by the jpdftweak program. Each bookmark is a
line of fields seperated by semicolon. Specifically, the structure of each line
is described by the following extended regular expression:
(?P<depth> -?[0-9]+);
(?P<flags> O?B?I?); # open, bold, italic
(?P<title> [^;]*);
(?P<page> -?[0-9]+)
(?P<destination> [ ][^;]+)? # e.g. FitBV 100
(?P<moreopts> ;[^;]*)? # key1=value1 key2=value2 ...
moreopts keys can be:
Action if action is not GoTo
File for GoToR actions
Page for GoToR actions (the page group is 0 in this case,
Page consists of page number and destination)
URI for URI actions
Color
Also, the contents of all fields in the csv is escaped: all nonprintable
characters (ascii < 32) and the characters [\:"'] are replaced by '\HH', where
HH is the two digit ascii hex code (in upper case) for that character.
The djvused Format
==================
This format is read and written by the djvused program.
The outline syntax is a single list of the form
(bookmarks ...)
The first element of the list is symbol bookmarks. The subsequent elements are
lists representing the toplevel outline entries. Each outline entry is
represented by a list with the following form:
(title url ... )
The string title is the title of the outline entry. The string url is composed
of the hash character ("#") followed by either the component file identifier or
the page number corresponding to the outline entry. The remaining expressions
describe subentries of this outline entry.
An example of the format is the following:
(bookmarks
("level1"
"#1"
("level2"
"#11"
("level3"
"#20" ) ) )
("Bookmark \\"In Quotes\\""
"../external.djvu#2"
("Unicode \\303\\215\\303\\261\\305\\244\\304\\230\\320"
"www.google.com" ) ) )
Note how the target url can be the pagenumber, an external reference, or a url.
Quotes inside the title have to be escaped. Non-ascii characters are written as
escaped octal UTF-8
The latex Format
================
The latex format results in a standalone tex file that adds the bookmarks to
the target pdf when compiled with pdflatex (after a few edits). This is
possible by using the pdfpages, hyperref, and bookmark packages. See especially
the documentation of the bookmark package to see how bookmarks are expressed.
An example of the format is the following:
\\bookmark[view={XYZ null null null}, page=1,level=0]{level 1 bookmark}
For parsing the latex format, each \\bookmark entry must be written entirely
one a single line
Interactive Usage
=================
This script was designed to provide a toolbox for working on bookmark
structures when used as module from Python.
The Bookmark class is the central data structure, representing a bookmark tree.
Each nodes holds all the attributes of the bookmark, and a list of all its
children. A number of methods is provided to modify the tree structure.
Note that each bookmark tree has a dummy root, which does not hold any data
(and is ignored in output)
The Tree is iterable in a preorder traversion.
For more information, read the Bookmark class documentation.
Apart from the Bookmark data structure, the module provides importers and
exporters for all the supported formats.
An example of an interactive usage is shown below. It reads the bookmark
structure from a text file, sets the appearance of all bookmarks at a level
deeper than 2 to 'closed' in Acrobat Reader, and write the resulting structure
to an iText xml file.
>>> from bmconverter import *
>>> bm, md = read_text("bookmarks.txt")
>>> for node in bm:
... if node.level() > 2:
... node.open = False
... else:
... node.open = True
...
>>> write_xml(bm, "bookmarks.xml")
For the full documentation, run
>>> import bmconverter
>>> help(bmconverter)
inside the python interpretor
"""
# TODO: improve support for handling metadata
# TODO: add support for jpdfbookmarks
import sys
import re
import codecs
from xml.sax import saxutils
def warn(msg):
""" print a warning message to stderr """
sys.stderr.write(str(msg))
sys.stderr.write("\n")
def die(msg):
""" print a warning message to stderr and exit"""
sys.stderr.write(str(msg))
sys.stderr.write("\n")
exit(2)
def escape_latex(unistring):
'''Escape a unicode string for LaTeX. '''
_latex_special_chars = {
u'$': u'\\$',
u'%': u'\\%',
u'&': u'\\&',
u'#': u'\\#',
u'_': u'\\_',
u'{': u'\\{',
u'}': u'\\}',
u'[': u'{[}',
u']': u'{]}',
u'"': u"{''}",
u'\\': u'\\textbackslash{}',
u'~': u'\\textasciitilde{}',
u'<': u'\\textless{}',
u'>': u'\\textgreater{}',
u'^': u'\\textasciicircum{}',
u'`': u'{}`', # avoid ?` and !`
}
return u''.join(_latex_special_chars.get(c, c) for c in unistring)
class Bookmark:
""" Tree ADT for the bookmarks
Every node has the following attributes:
action Kind of bookmark (unicode string):
"GoTo" Link to destination in same file (regular)
"GoToR" Link to destination in external file
"URI" Link to an internet address
"Launch" Link to a local file
title Title of the Bookmark (unicode string)
page Page number the bookmark is pointing to (integer)
destination Page Destination (unicode string)
The Destination can take the following forms:
XYZ left top zoom Link to position
Fit Fit page
FitH top Horiz. Fit
FitV left Vert. Fit
FitR left bottom right top Fit Rectangle
FitB Fit Bounding box
FitBH top Fit bounding box, horiz.
FitBV left Fit bounding box, vert.
left, top zoom, bottom right, left are floats, or 'null'
named Named Destination (unicode string)
namedn Named Destination, as a name (unicode string)
file The file a GoToR or Launch action are referring to
(unicode string)
newwindow Should file be opened in a new window? (boolean)
uri URI that an URI action is referring to (unicode string))
italic Should the title be displayed in italics? (boolean)
bold Should the title be displayed in bold? (boolean)
color Color of the bookmark (unicode string)
open Should the bookmark appear open or closed? (boolean)
There are certain dependencies between the action and the other attributes:
"Action" = "GoTo" - "Page" | "Named"
* "Page" = "3 XYZ 70 400 null" - page number followed by a destination
(/XYZ is also accepted)
* "Named" = "named_destination"
"Action" = "GoToR" - "Page" | "Named" | "NamedN", "File", ["NewWindow"]
* "Page" = "3 XYZ 70 400 null" - page number followed by a destination
(/XYZ is also accepted)
* "Named" = "named_destination_as_a_string"
* "NamedN" = "named_destination_as_a_name"
* "File" - "the_file_to_open"
* "NewWindow" - "true" or "false"
"Action" = "URI" - "URI"
* "URI" = "http://sf.net" - URI to jump to
"Action" = "Launch" - "File"
* "File" - "the_file_to_open_or_execute"
For the dependencies listed above, cf.
http://itext.ugent.be/library/api/com/lowagie/text/pdf/SimpleBookmark.html
For details on the destinations, see p. 552 of the PDF Reference
http://www.adobe.com/devnet/pdf/pdfs/PDFReference16.pdf
Bookmark has two compiled regular expressions as class attributes (see
below) that define the structure of the color attribute and the
destination attribute, respectively. You can use them to parse the string
data in these fields.
The expression for the color is:
(?P<red> [0-9]?.?[0-9]+) [ ]+
(?P<green> [0-9]?.?[0-9]+) [ ]+
(?P<blue> [0-9]?.?[0-9]+)
The expression for the destination is:
(/?XYZ [ ]*
(?P<XYZ_left> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<XYZ_top> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<XYZ_zoom> null | [+-]?[0-9]?.?[0-9]+)
) |
(/?Fit) |
(/?FitH [ ]* (?P<FitH_top> null | [+-]?[0-9]?.?[0-9]+)) |
(/?FitV [ ]* (?P<FitV_left> null | [+-]?[0-9]?.?[0-9]+)) |
(/?FitR [ ]*
(?P<FitR_left> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<FitR_bottom> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<FitR_right> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<RitR_top> null | [+-]?[0-9]?.?[0-9]+)
) |
(/?FitB) |
(/?FitBH [ ]* (?P<FitBH_top> null | [+-]?[0-9]?.?[0-9]+))|
(/?FitBV [ ]* (?P<FitBV_left> null | [+-]?[0-9]?.?[0-9]+))
"""
_colorpattern_str = r'''
(?P<red> [0-9]?.?[0-9]+) [ ]+
(?P<green> [0-9]?.?[0-9]+) [ ]+
(?P<blue> [0-9]?.?[0-9]+)
'''
_destpattern_str = r'''
(/?XYZ [ ]*
(?P<XYZ_left> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<XYZ_top> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<XYZ_zoom> null | [+-]?[0-9]?.?[0-9]+)
) |
(/?Fit) |
(/?FitH [ ]* (?P<FitH_top> null | [+-]?[0-9]?.?[0-9]+)) |
(/?FitV [ ]* (?P<FitV_left> null | [+-]?[0-9]?.?[0-9]+)) |
(/?FitR [ ]*
(?P<FitR_left> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<FitR_bottom> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<FitR_right> null | [+-]?[0-9]?.?[0-9]+) [ ]*
(?P<RitR_top> null | [+-]?[0-9]?.?[0-9]+)
) |
(/?FitB) |
(/?FitBH [ ]* (?P<FitBH_top> null | [+-]?[0-9]?.?[0-9]+))|
(/?FitBV [ ]* (?P<FitBV_left> null | [+-]?[0-9]?.?[0-9]+))
'''
colorpattern = re.compile(_colorpattern_str, re.X)
destpattern = re.compile(_destpattern_str, re.X)
def __init__(self):
self.action = None
self._level = 0
self.title = u""
self.page = 0
self.destination = None
self.named = None
self.namedn = None
self.file = None
self.newwindow = None
self.uri = None
self.italic = False
self.bold = False
self.color = None
self.open = True
self._children = []
self._parent = None
self._childnumber = 0 # the index this node has in its parent's
# children array
self._seen = {} # keeps track of what iterations this node has been seen
# in. key is the id of the starting node, value is an
# int numbering the iteration.
self._iteritem = None # the node that the currently running iteration
# that started from self is at.
self._delete = False
def __setattr__(self, name, value):
"""Enforce integrity of attribute data"""
if name == 'page':
if not isinstance(value, int) or (value < 0):
warn("page must be an integer greater than zero. "
+"Set to zero.")
value = 0
if name in ['italic', 'bold', 'open', 'newwindow']:
if not isinstance(value, bool):
if not ( (name == 'newwindow') and (value is None) ):
warn("The attributes 'italic', 'bold', 'open', "
+ "'newwindow' must be boolean values. "
+ "%s not set." % name)
return None
if name in ['title', 'file', 'uri', 'destination', 'color', 'action']:
if value is not None:
if not isinstance(value, unicode):
if name in ['title', 'file', 'uri']:
warn("The attribute '%s' " % name \
+ "must be a unicode string. Trying to convert.")
try:
value = unicode(value)
except UnicodeDecodeError:
warn("Could not convert to unicode. " \
+ "%s not set." % name)
return None
if name == 'action':
if value not in [None, 'GoTo', 'GoToR', 'URI', 'Launch']:
warn("%s is not a recognized action. " % value \
+ "action must be 'GoTo', 'GoToR', 'URI', or 'Launch'. " \
+ "action not set.")
return None
if name == 'destination' and value is not None:
value = value.strip()
if not self.destpattern.match(value):
warn("'%s' is not a valid destination. " % value
+ "Destinations must have the following pattern:")
warn(self._destpattern_str)
warn("Not set.")
return None
if name == 'color' and value is not None:
value = value.strip()
if not self.colorpattern.match(value):
warn("'%s' is not a valid color declaration. " % value
+ "Colors must have the following pattern:")
warn(self._colorpattern_str)
warn("Not set.")
return None
self.__dict__[name] = value
def level(self):
"""Return the level this bookmark is in"""
return self._level
def children(self):
"""Return a list of all the children"""
return self._children
def child(self, i):
"""Return the child with index i or throw an IndexError
The indexes run from zero to (self.number_of_children()-1). You can also
use negetive indexes, e.g. i=-1 to address the last child"""
return self._children[i]
def parent(self):
"""Return the parent node"""
return self._parent
def is_root(self):
"""Check if the node is the root of the bookmark tree"""
return (self._parent is None)
def has_children(self):
"""Check if the node has any children"""
return (len(self._children) > 0)
def number_of_children(self):
"""Return the number of children"""
return len(self._children)
def newchild(self):
"""Create and return a new child.
"""
child = Bookmark()
self._children.append(child)
child._level = self.level() + 1
child._parent = self
child._childnumber = len(self._children)-1
return self.child(-1)
def set_child(self, i, node):
"""Set the i'th child child to node.
Raise an IndexError if there is no child with index i
"""
self._children[i] = node
oldlevel = node.level()
node._level = self.level() + 1
for child in node:
child._level = self.level() + (child.level() - oldlevel) + 1
node._parent = self
node._childnumber = i
def _obliterate_child(self, childnumber):
"""Remove a child from its parent
Preferably, use 'delete' and 'flush'
"""
try:
# readjust the siblings' childnumbers
for child in self._children[childnumber:]:
child._childnumber -= 1
# cut link to parent
self.child(childnumber)._parent = None
# remove from parent's children array
del self._children[childnumber]
except IndexError:
warn("Node does not have a child with index %s" % childnumber)
warn("Can't delete")
def __str__(self):
"""The string representation is a multiline listing of all attributes"""
return ( self.unicode() ).encode('ascii','replace')
def unicode(self):
"""Return a unicode string representation.
The unicode string representation is a multiline listing of all
attributes"""
s = []
s.append(u"action = %s" % self.action)
s.append(u"level = %s" % self.level())
s.append(u"title = %s" % self.title)
s.append(u"page = %s" % self.page)
s.append(u"destination = %s" % self.destination)
s.append(u"named = %s" % self.named)
s.append(u"namedn = %s" % self.namedn)
s.append(u"file = %s" % self.file)
s.append(u"newwindow = %s" % self.newwindow)
s.append(u"uri = %s" % self.uri)
s.append(u"italic = %s" % self.italic)
s.append(u"bold = %s" % self.bold)
s.append(u"color = %s" % self.color)
s.append(u"open = %s" % self.open)
s.append(u"childnumber = %s" % self._childnumber)
s.append(u"length = %s" % len(self))
for i in xrange(len(s)):
s[i] = u" " * self.level() + s[i] + "\n"
return ''.join(s)
def debug(self):
"""Print out a representation of the tree, similar to the text output
format"""
if not self.is_root():
print " " * ( self.level() - 1 ) \
+ (unicode(self.title)).encode('ascii','replace') + " :: " \
+ str(self.page)
for child in self.children():
child.debug()
def long_debug(self):
"""Print each node in the tree, recursively"""
self.reset()
for node in self:
print str(node)
self.reset()
def _obliterate(self):
"""Remove the node from the tree
Note that you cannot obliterate inside an iterator loop.
"""
if not self.is_root():
self._parent._obliterate_child(self._childnumber)
def delete(self):
"""Flag the node for deletion. You have to call 'flush' to have it
actually deleted"""
self._delete = True
def flush(self):
"""Obliterate all nodes flagged for deletion"""
self.reset()
dellist = []
for node in self:
if node._delete:
dellist.append(node)
self.reset()
for node in dellist:
node._obliterate()
def __iter__(self):
"""The iterator for this class is defined via the next() method"""
return self
def next(self):
"""Return the next node in a preorder traversion"""
def seen_in_run(node, startnode):
"""Checks if the node was seen in the iteration currently running
from startnode """
node_iter_nr = node._seen.setdefault(id(startnode), 0)
return (node_iter_nr >= startnode._seen[id(startnode)])
def make_seen(node, startnode):
"""Mark node as seen in the iteration currently running from
startnode """
node._seen[id(startnode)] = startnode._seen[id(startnode)]
if self._iteritem is None:
# start a new iteration run
self._seen[id(self)] = self._seen.setdefault(id(self), 0) + 1
self._iteritem = self
# are there unseen children? If not, find unseen siblings
if self._iteritem.has_children():
# finding unseen children is the same as finding the first child's
# unseen siblings, so we go down one level
self._iteritem = self._iteritem.child(0)
# find unseen siblings (i.e. unseen parent's children)
while not self._iteritem.is_root():
self._iteritem = self._iteritem.parent()
if not seen_in_run(self._iteritem.child(-1), self):
for child in self._iteritem.children():
if not seen_in_run(child, self):
self._iteritem = child
make_seen(self._iteritem, self)
return self._iteritem
# end of iteration
self.reset()
raise StopIteration
def reset(self):
"""Reset the traversion status of the node if it is halfway through an
iteration run, so that a new iteration can restart"""
self._iteritem = None
def shift_pagenumber(self, offset):
"""Shift the pagenumbers in the bookmark tree below this node by the
specified offset. The starting node is left untouched, except that its
traversion status is reset.
"""
self.reset()
for node in self:
if isinstance(node.page, int):
node.page += offset
self.reset()
def __iadd__(self, other):
"""Handle the expression 'self += other'
All the children of other are appended as children of self
"""
for child in other.children():
self.newchild()
self.set_child(-1, child)
return self
def __add__(self, other):
"""Handle the expression 'self + other'
Return a copy of self, with all all the children of other appended as
children of self
"""
result = self.copy()
result += other
return result
def __len__(self):
"""Return the number of bookmarks in this tree.
The root does not count as a bookmark
"""
l = len(self._children)
for child in self._children:
l += len(child)
return l
def has_same_attrs_as(self, other):
"""Test if self has the same attributes as other. This comparison is not
recursive: self and other can have different children
"""
result = True
result &= (self.action == other.action)
result &= (self.title == other.title)
result &= (self.page == other.page)
result &= (self.destination == other.destination)
result &= (self.named == other.named)
result &= (self.namedn == other.namedn)
result &= (self.file == other.file)
result &= (self.newwindow == other.newwindow)
result &= (self.uri == other.uri)
result &= (self.italic == other.italic)
result &= (self.bold == other.bold)
result &= (self.color == other.color)
result &= (self.open == other.open)
return result
def __eq__(self, other):
"""Handle the expression 'self == other'
Two nodes are equal if all their attributes are equal and all there
respective children are equal.
"""
result = ( len(self) == len(other) )
if result:
result &= (self.has_same_attrs_as(other))
if result:
for (selfchild, otherchild) \
in zip(self._children, other._children):
result &= selfchild.has_same_attrs_as(otherchild)
return result
def __ne__(self, other):
"""Handle the expression 'self != other'
This simply negeates 'self == other'
"""
return not (self == other)
def __lt__(self, other):
""" Handle the expression 'self < other'
'self < other' is equivalent to 'len(self) < len(other)'"""
return ( len(self) < len(other) )
def __le__(self, other):
""" Handle the expression 'self <= other'
'self <= other' is equivalent to
'(len(self) < len(other)) or (self == other)'
"""
return ( (len(self) < len(other)) or (self == other) )
def __gt__(self, other):
""" Handle the expression 'self > other'
'self > other' is equivalent to 'len(self) < len(other)'"""
return ( len(self) > len(other) )
def __ge__(self, other):
""" Handle the expression 'self >= other'
'self >= other' is equivalent to
'(len(self) > len(other)) or (self == other)'
"""
return ( (len(self) > len(other)) or (self == other) )
def copy(self):
""" Return copy """
newnode = Bookmark()
newnode.action = self.action
newnode.title = self.title
newnode.page = self.page
newnode.destination = self.destination
newnode.named = self.named
newnode.namedn = self.namedn
newnode.file = self.file
newnode.newwindow = self.newwindow
newnode.uri = self.uri
newnode.italic = self.italic
newnode.bold = self.bold
newnode.color = self.color
newnode.open = self.open
for child in self.children():
newnode.newchild()
newnode.set_child(-1, child.copy())
return newnode
def usage():
"""Display Program Usage"""
print """
bmconverter.py
(c) 2011 Michael Goerz - This program is provided under the terms of the GPL.
Usage: bmconverter.py options inputfile [outputfile]
Command Line Options
====================
--mode in2out Sets the script's operation mode. This option is required.
-m in2out Short for --mode
--offset integer Shifts all pagenumber by integer
-o integer Short for --offset
--long When used with the 'text' output format, enables the use
of full destinations, instead of just page numbers
-l Short for --long
--pdf FILENAME Set metadata['pdf'] to the given filename. When used
together with the latex output mode, the resulting tex
file will reference the given filename.
--help Displays full help
-h Short for -help
In the mode option, 'in' and 'out' can be any of the supported formats:
'xml', 'text', 'pdftk', 'csv', 'djvused', 'latex', or 'html'
Additionally, 'in' can be 'pdf', in which case the bookmarks are read directly
from the given pdf file. The pdfminer library must be installed for this to
work.
An example usage is 'bmconverter.py --offset 2 --mode xml2text bm.xml bm.txt'
All data is read and written in UTF-8 encoding, with the exception of xml files,
which are read in the encoding declared in their header, but always written in
UTF-8
"""
def show_help():
"""Display full help"""
print __doc__
def main():
"""Command line program for converting between bookmark formats"""
# command line parsing / initialization
import getopt
import os.path
global warn
if len(sys.argv) < 2:
usage()
exit(2)
try:
opts, files = getopt.getopt(sys.argv[1:], "hm:o:l",
["help", "mode=", "offset=",
"pdf=", "long"])
except getopt.GetoptError, details:
die(details)
pdf = None
mode = ""
offset = 0
text_long = False
for o, a in opts:
if o in ("-h", "--help"):
show_help()
sys.exit()
if o in ("-m", "--mode"):
mode = a
if o in ("-o", "--offset"):
try:
offset = int(a)
except ValueError:
die("Offset must be an integer.")
if o in ("-l", "--long"):
text_long = True
if o == "--pdf":
pdf = a
# deal with the input- and output file
if len(files) < 1:
die("You must provide an input file")
infilename = files[0]
if not os.path.isfile(infilename):
die ("The input file '%s' does not exist" % infilename)
outfilename = infilename
if len(files) < 2:
warn ("You did not provide an output file. "
+"The input file will be overwritten")
answer = raw_input("Do you want to overwrite? Yes [No]: ").lower()
if answer != "yes":
exit(0)
else:
outfilename = files[1]
if os.path.exists(outfilename):
warn("The output filename '%s' already exists." % outfilename)
answer = raw_input("Do you want to overwrite? Yes [No]: ").lower()
if answer != "yes":
exit(0)
# parse the mode, to find out what we have to do
handlers = {
'csv' : (read_csv, write_csv),
'html' : (read_html, write_html),
'pdftk' : (read_pdftk, write_pdftk),
'text' : (read_text, write_text),
'xml' : (read_xml, write_xml),
'djvused' : (read_djvused, write_djvused),
'latex' : (read_latex, write_latex),
'pdf' : (read_pdf, None),
}
from_format = None
to_format = None
mode_pattern = re.compile(r'([a-z]+)2([a-z]+)')
mode_match = mode_pattern.match(mode)
if mode_match: