forked from ArtifexSoftware/mupdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
5327 lines (4750 loc) · 172 KB
/
utils.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
# ------------------------------------------------------------------------
# Copyright 2020-2021, Harald Lieder, mailto:harald.lieder@outlook.com
# License: GNU AFFERO GPL 3.0, https://www.gnu.org/licenses/agpl-3.0.html
#
# Part of "PyMuPDF", a Python binding for "MuPDF" (http://mupdf.com), a
# lightweight PDF, XPS, and E-book viewer, renderer and toolkit which is
# maintained and developed by Artifex Software, Inc. https://artifex.com.
# ------------------------------------------------------------------------
import io
import json
import math
import os
import random
import string
import typing
import warnings
import tempfile
from fitz import *
point_like = "point_like"
rect_like = "rect_like"
matrix_like = "matrix_like"
quad_like = "quad_like"
AnyType = typing.Any
OptInt = typing.Union[int, None]
OptFloat = typing.Optional[float]
OptStr = typing.Optional[str]
OptDict = typing.Optional[dict]
OptBytes = typing.Optional[typing.ByteString]
OptSeq = typing.Optional[typing.Sequence]
"""
This is a collection of functions to extend PyMupdf.
"""
def write_text(page: Page, **kwargs) -> None:
"""Write the text of one or more TextWriter objects.
Args:
rect: target rectangle. If None, the union of the text writers is used.
writers: one or more TextWriter objects.
overlay: put in foreground or background.
keep_proportion: maintain aspect ratio of rectangle sides.
rotate: arbitrary rotation angle.
oc: the xref of an optional content object
"""
if type(page) is not Page:
raise ValueError("bad page parameter")
s = {
k
for k in kwargs.keys()
if k
not in {
"rect",
"writers",
"opacity",
"color",
"overlay",
"keep_proportion",
"rotate",
"oc",
}
}
if s != set():
raise ValueError("bad keywords: " + str(s))
rect = kwargs.get("rect")
writers = kwargs.get("writers")
opacity = kwargs.get("opacity")
color = kwargs.get("color")
overlay = bool(kwargs.get("overlay", True))
keep_proportion = bool(kwargs.get("keep_proportion", True))
rotate = int(kwargs.get("rotate", 0))
oc = int(kwargs.get("oc", 0))
if not writers:
raise ValueError("need at least one TextWriter")
if type(writers) is TextWriter:
if rotate == 0 and rect is None:
writers.write_text(page, opacity=opacity, color=color, overlay=overlay)
return None
else:
writers = (writers,)
clip = writers[0].text_rect
textdoc = Document()
tpage = textdoc.new_page(width=page.rect.width, height=page.rect.height)
for writer in writers:
clip |= writer.text_rect
writer.write_text(tpage, opacity=opacity, color=color)
if rect is None:
rect = clip
page.show_pdf_page(
rect,
textdoc,
0,
overlay=overlay,
keep_proportion=keep_proportion,
rotate=rotate,
clip=clip,
oc=oc,
)
textdoc = None
tpage = None
def show_pdf_page(*args, **kwargs) -> int:
"""Show page number 'pno' of PDF 'src' in rectangle 'rect'.
Args:
rect: (rect-like) where to place the source image
src: (document) source PDF
pno: (int) source page number
overlay: (bool) put in foreground
keep_proportion: (bool) do not change width-height-ratio
rotate: (int) degrees (multiple of 90)
clip: (rect-like) part of source page rectangle
Returns:
xref of inserted object (for reuse)
"""
if len(args) not in (3, 4):
raise ValueError("bad number of positional parameters")
pno = None
if len(args) == 3:
page, rect, src = args
else:
page, rect, src, pno = args
if pno == None:
pno = int(kwargs.get("pno", 0))
overlay = bool(kwargs.get("overlay", True))
keep_proportion = bool(kwargs.get("keep_proportion", True))
rotate = float(kwargs.get("rotate", 0))
oc = int(kwargs.get("oc", 0))
reuse_xref = int(kwargs.get("reuse_xref", 0))
clip = kwargs.get("clip")
def calc_matrix(sr, tr, keep=True, rotate=0):
"""Calculate transformation matrix from source to target rect.
Notes:
The product of four matrices in this sequence: (1) translate correct
source corner to origin, (2) rotate, (3) scale, (4) translate to
target's top-left corner.
Args:
sr: source rect in PDF (!) coordinate system
tr: target rect in PDF coordinate system
keep: whether to keep source ratio of width to height
rotate: rotation angle in degrees
Returns:
Transformation matrix.
"""
# calc center point of source rect
smp = (sr.tl + sr.br) / 2.0
# calc center point of target rect
tmp = (tr.tl + tr.br) / 2.0
# m moves to (0, 0), then rotates
m = Matrix(1, 0, 0, 1, -smp.x, -smp.y) * Matrix(rotate)
sr1 = sr * m # resulting source rect to calculate scale factors
fw = tr.width / sr1.width # scale the width
fh = tr.height / sr1.height # scale the height
if keep:
fw = fh = min(fw, fh) # take min if keeping aspect ratio
m *= Matrix(fw, fh) # concat scale matrix
m *= Matrix(1, 0, 0, 1, tmp.x, tmp.y) # concat move to target center
return JM_TUPLE(m)
CheckParent(page)
doc = page.parent
if not doc.is_pdf or not src.is_pdf:
raise ValueError("not a PDF")
rect = page.rect & rect # intersect with page rectangle
if rect.is_empty or rect.is_infinite:
raise ValueError("rect must be finite and not empty")
if reuse_xref > 0:
warnings.warn("ignoring 'reuse_xref'", DeprecationWarning)
while pno < 0: # support negative page numbers
pno += src.page_count
src_page = src[pno] # load source page
if src_page.get_contents() == []:
raise ValueError("nothing to show - source page empty")
tar_rect = rect * ~page.transformation_matrix # target rect in PDF coordinates
src_rect = src_page.rect if not clip else src_page.rect & clip # source rect
if src_rect.is_empty or src_rect.is_infinite:
raise ValueError("clip must be finite and not empty")
src_rect = src_rect * ~src_page.transformation_matrix # ... in PDF coord
matrix = calc_matrix(src_rect, tar_rect, keep=keep_proportion, rotate=rotate)
# list of existing /Form /XObjects
ilst = [i[1] for i in doc.get_page_xobjects(page.number)]
ilst += [i[7] for i in doc.get_page_images(page.number)]
ilst += [i[4] for i in doc.get_page_fonts(page.number)]
# create a name not in that list
n = "fzFrm"
i = 0
_imgname = n + "0"
while _imgname in ilst:
i += 1
_imgname = n + str(i)
isrc = src._graft_id # used as key for graftmaps
if doc._graft_id == isrc:
raise ValueError("source document must not equal target")
# retrieve / make Graftmap for source PDF
gmap = doc.Graftmaps.get(isrc, None)
if gmap is None:
gmap = Graftmap(doc)
doc.Graftmaps[isrc] = gmap
# take note of generated xref for automatic reuse
pno_id = (isrc, pno) # id of src[pno]
xref = doc.ShownPages.get(pno_id, 0)
xref = page._show_pdf_page(
src_page,
overlay=overlay,
matrix=matrix,
xref=xref,
oc=oc,
clip=src_rect,
graftmap=gmap,
_imgname=_imgname,
)
doc.ShownPages[pno_id] = xref
return xref
def insert_image(page, rect, **kwargs):
"""Insert an image for display in a rectangle.
Args:
rect: (rect_like) position of image on the page.
alpha: (int, optional) set to 0 if image has no transparency.
filename: (str, Path, file object) image filename.
keep_proportion: (bool) keep width / height ratio (default).
mask: (bytes, optional) image consisting of alpha values to use.
oc: (int) xref of OCG or OCMD to declare as Optional Content.
overlay: (bool) put in foreground (default) or background.
pixmap: (Pixmap) use this as image.
rotate: (int) rotate by 0, 90, 180 or 270 degrees.
stream: (bytes) use this as image.
xref: (int) use this as image.
'page' and 'rect' are positional, all other parameters are keywords.
If 'xref' is given, that image is used. Other input options are ignored.
Else, exactly one of pixmap, stream or filename must be given.
'alpha=0' for non-transparent images improves performance significantly.
Affects stream and filename only.
Optimum transparent insertions are possible by using filename / stream in
conjunction with a 'mask' image of alpha values.
Returns:
xref (int) of inserted image. Re-use as argument for multiple insertions.
"""
CheckParent(page)
doc = page.parent
if not doc.is_pdf:
raise ValueError("not a PDF")
valid_keys = {
"alpha",
"filename",
"height",
"keep_proportion",
"mask",
"oc",
"overlay",
"pixmap",
"rotate",
"stream",
"width",
"xref",
}
s = set(kwargs.keys()).difference(valid_keys)
if s != set():
raise ValueError("bad key argument(s) %s" % s)
filename = kwargs.get("filename")
pixmap = kwargs.get("pixmap")
stream = kwargs.get("stream")
mask = kwargs.get("mask")
rotate = int(kwargs.get("rotate", 0))
width = int(kwargs.get("width", 0))
height = int(kwargs.get("height", 0))
alpha = int(kwargs.get("alpha", -1))
oc = int(kwargs.get("oc", 0))
xref = int(kwargs.get("xref", 0))
keep_proportion = bool(kwargs.get("keep_proportion", True))
overlay = bool(kwargs.get("overlay", True))
#jlib.log('{xref=} {filename=} {stream=} {pixmap=} {alpha=}')
#jlib.log('{filename=} {pixmap=} {stream=} {mask=} {overlay=}'
# ' {rotate=} {keep_proportion=} {oc=} {width=} {height=}'
# ' {xref=} {alpha=}')
if xref == 0 and (bool(filename) + bool(stream) + bool(pixmap) != 1):
raise ValueError("xref=0 needs exactly one of filename, pixmap, stream")
if filename:
if type(filename) is str:
pass
elif hasattr(filename, "absolute"):
filename = str(filename)
elif hasattr(filename, "name"):
filename = filename.name
else:
raise ValueError("bad filename")
if filename and not os.path.exists(filename):
raise FileNotFoundError("No such file: '%s'" % filename)
elif stream and type(stream) not in (bytes, bytearray, io.BytesIO):
raise ValueError("stream must be bytes-like / BytesIO")
elif pixmap and type(pixmap) is not Pixmap:
raise ValueError("pixmap must be a Pixmap")
if mask and not (stream or filename):
raise ValueError("mask requires stream or filename")
if mask and type(mask) not in (bytes, bytearray, io.BytesIO):
raise ValueError("mask must be bytes-like / BytesIO")
while rotate < 0:
rotate += 360
while rotate >= 360:
rotate -= 360
if rotate not in (0, 90, 180, 270):
raise ValueError("bad rotate value")
r = Rect(rect)
if r.is_empty or r.is_infinite:
raise ValueError("rect must be finite and not empty")
clip = r * ~page.transformation_matrix
# Create a unique image reference name.
ilst = [i[7] for i in doc.get_page_images(page.number)]
ilst += [i[1] for i in doc.get_page_xobjects(page.number)]
ilst += [i[4] for i in doc.get_page_fonts(page.number)]
n = "fzImg" # 'fitz image'
i = 0
_imgname = n + "0" # first name candidate
while _imgname in ilst:
i += 1
_imgname = n + str(i) # try new name
digests = doc.InsertedImages
#jlib.log('calling page._insert_image() {stream=}')
xref, digests = page._insert_image(
filename=filename,
pixmap=pixmap,
stream=stream,
imask=mask,
clip=clip,
overlay=overlay,
oc=oc,
xref=xref,
rotate=rotate,
keep_proportion=keep_proportion,
width=width,
height=height,
alpha=alpha,
_imgname=_imgname,
digests=digests,
)
#jlib.log('{xref=} {digests=}')
if digests != None:
doc.InsertedImages = digests
return xref
def search_for(*args, **kwargs) -> list:
"""Search for a string on a page.
Args:
text: string to be searched for
clip: restrict search to this rectangle
quads: (bool) return quads instead of rectangles
flags: bit switches, default: join hyphened words
textpage: a pre-created TextPage
Returns:
a list of rectangles or quads, each containing one occurrence.
"""
if len(args) != 2:
raise ValueError("bad number of positional parameters")
page, text = args
quads = kwargs.get("quads", 0)
clip = kwargs.get("clip")
textpage = kwargs.get("textpage")
if clip != None:
clip = Rect(clip)
flags = kwargs.get(
"flags", TEXT_DEHYPHENATE | TEXT_PRESERVE_WHITESPACE | TEXT_PRESERVE_LIGATURES
)
CheckParent(page)
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags) # create TextPage
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rlist = tp.search(text, quads=quads)
if textpage is None:
del tp
return rlist
def search_page_for(
doc,#: Document,
pno: int,
text: str,
quads: bool = False,
clip: rect_like = None,
flags: int = TEXT_DEHYPHENATE | TEXT_PRESERVE_LIGATURES | TEXT_PRESERVE_WHITESPACE,
textpage: TextPage = None,
) -> list:
"""Search for a string on a page.
Args:
pno: page number
text: string to be searched for
clip: restrict search to this rectangle
quads: (bool) return quads instead of rectangles
flags: bit switches, default: join hyphened words
textpage: reuse a prepared textpage
Returns:
a list of rectangles or quads, each containing an occurrence.
"""
return doc[pno].search_for(
text,
quads=quads,
clip=clip,
flags=flags,
textpage=textpage,
)
def get_text_blocks(
page: Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: TextPage = None,
sort: bool = False,
) -> list:
"""Return the text blocks on a page.
Notes:
Lines in a block are concatenated with line breaks.
Args:
flags: (int) control the amount of data parsed into the textpage.
Returns:
A list of the blocks. Each item contains the containing rectangle
coordinates, text lines, block type and running block number.
"""
CheckParent(page)
if flags is None:
flags = (
TEXT_PRESERVE_WHITESPACE | TEXT_PRESERVE_IMAGES | TEXT_PRESERVE_LIGATURES
)
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
blocks = tp.extractBLOCKS()
if textpage is None:
del tp
if sort is True:
blocks.sort(key=lambda b: (b[3], b[0]))
return blocks
def get_text_words(
page: Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: TextPage = None,
sort: bool = False,
) -> list:
"""Return the text words as a list with the bbox for each word.
Args:
flags: (int) control the amount of data parsed into the textpage.
"""
CheckParent(page)
if flags is None:
flags = TEXT_PRESERVE_WHITESPACE | TEXT_PRESERVE_LIGATURES
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
words = tp.extractWORDS()
if textpage is None:
del tp
if sort is True:
words.sort(key=lambda w: (w[3], w[0]))
return words
def get_textbox(
page: Page,
rect: rect_like,
textpage: TextPage = None,
) -> str:
tp = textpage
if tp is None:
tp = page.get_textpage()
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rc = tp.extractTextbox(rect)
if textpage is None:
del tp
return rc
def get_text_selection(
page: Page,
p1: point_like,
p2: point_like,
clip: rect_like = None,
textpage: TextPage = None,
):
CheckParent(page)
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=TEXT_DEHYPHENATE)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rc = tp.extractSelection(p1, p2)
if textpage is None:
del tp
return rc
def get_textpage_ocr(
page: Page,
flags: int = 0,
language: str = "eng",
dpi: int = 72,
full: bool = False,
) -> TextPage:
"""Create a Textpage from combined results of normal and OCR text parsing.
Args:
flags: (int) control content becoming part of the result.
language: (str) specify expected language(s). Deafault is "eng" (English).
dpi: (int) resolution in dpi, default 72.
full: (bool) whether to OCR the full page image, or only its images (default)
"""
CheckParent(page)
# if OCR for the full page, OCR its pixmap @ desired dpi
if full is True:
zoom = dpi / 72
mat = Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
ocr_pdf = Document("pdf", pix.pdfocr_tobytes(compress=False, language=language))
ocr_page = ocr_pdf.load_page(0)
unzoom = page.rect.width / ocr_page.rect.width
ctm = Matrix(unzoom, unzoom) * page.derotation_matrix
tpage = ocr_page.get_textpage(flags=flags, matrix=ctm)
ocr_pdf.close()
pix = None
tpage.parent = weakref.proxy(page)
return tpage
# for partial OCR, make a normal textpage, then extend it with text that
# is OCRed from each image.
tpage = page.get_textpage(flags=flags)
for block in page.get_text("dict")["blocks"]:
if block["type"] != 1:
continue
pix = Pixmap(block["image"]) # get image pixmap
imgdoc = Document("pdf", pix.pdfocr_tobytes()) # pdf with OCRed page
imgpage = imgdoc.load_page(0) # read image as a page
pix = None
# compute matrix to transform coordinates back to that of 'page'
imgrect = imgpage.rect # page size of image PDF
shrink = Matrix(1 / imgrect.width, 1 / imgrect.height)
mat = shrink * block["transform"]
imgpage.extend_textpage(tpage, flags=0, matrix=mat)
imgdoc.close()
return tpage
def get_image_info(page: Page, hashes: bool = False, xrefs: bool = False) -> list:
"""Extract image information only from a TextPage.
Args:
hashes: (bool) include MD5 hash for each image.
xrefs: (bool) try to find the xref for each image. Sets hashes to true.
"""
#jlib.log('{=hashes xrefs}')
doc = page.parent
#jlib.log('{=doc}')
if xrefs and doc.is_pdf:
hashes = True
#jlib.log('calling doc.is_pdf()')
if not doc.is_pdf:
#jlib.log('not doc.is_pdf; setting xrefs to false')
xrefs = False
#jlib.log('calling getattr()')
imginfo = getattr(page, "_image_info", None)
#jlib.log('{imginfo=}')
if imginfo and not xrefs:
#jlib.log('imginfo and not xrefs; returning {imginfo=}')
return imginfo
if not imginfo:
#jlib.log('{TEXT_PRESERVE_IMAGES=}')
tp = page.get_textpage(flags=TEXT_PRESERVE_IMAGES)
imginfo = tp.extractIMGINFO(hashes=hashes)
#jlib.log('tp.extractIMGINFO() => {imginfo=}')
del tp
if hashes:
page._image_info = imginfo
if not xrefs or not doc.is_pdf:
#jlib.log('not xrefs or not doc.is_pdf: returning {imginfo=}')
return imginfo
imglist = page.get_images()
digests = {}
for item in imglist:
xref = item[0]
pix = Pixmap(doc, xref)
digests[pix.digest] = xref
del pix
for i in range(len(imginfo)):
item = imginfo[i]
xref = digests.get(item["digest"], 0)
item["xref"] = xref
imginfo[i] = item
#jlib.log('returning {imginfo=}')
return imginfo
def get_image_rects(page: Page, name, transform=False) -> list:
"""Return list of image positions on a page.
Args:
name: (str, list, int) image identification. May be reference name, an
item of the page's image list or an xref.
transform: (bool) whether to also return the transformation matrix.
Returns:
A list of Rect objects or tuples of (Rect, Matrix) for all image
locations on the page.
"""
if type(name) in (list, tuple):
xref = name[0]
elif type(name) is int:
xref = name
else:
imglist = [i for i in page.get_images() if i[7] == name]
if imglist == []:
raise ValueError("bad image name")
elif len(imglist) != 1:
raise ValueError("multiple image names found")
xref = imglist[0][0]
pix = Pixmap(page.parent, xref) # make pixmap of the image to compute MD5
digest = pix.digest
del pix
infos = page.get_image_info(hashes=True)
if not transform:
bboxes = [Rect(im["bbox"]) for im in infos if im["digest"] == digest]
else:
bboxes = [
(Rect(im["bbox"]), Matrix(im["transform"]))
for im in infos
if im["digest"] == digest
]
return bboxes
def get_text(
page: Page,
option: str = "text",
clip: rect_like = None,
flags: OptInt = None,
textpage: TextPage = None,
sort: bool = False,
):
"""Extract text from a page or an annotation.
This is a unifying wrapper for various methods of the TextPage class.
Args:
option: (str) text, words, blocks, html, dict, json, rawdict, xhtml or xml.
clip: (rect-like) restrict output to this area.
flags: bit switches to e.g. exclude images or decompose ligatures.
textpage: reuse this TextPage and make no new one. If specified,
'flags' and 'clip' are ignored.
Returns:
the output of methods get_text_words / get_text_blocks or TextPage
methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT,
extractXHTML or etractXML respectively.
Default and misspelling choice is "text".
"""
formats = {
"text": 0,
"html": 1,
"json": 1,
"rawjson": 1,
"xml": 0,
"xhtml": 1,
"dict": 1,
"rawdict": 1,
"words": 0,
"blocks": 1,
}
option = option.lower()
if option not in formats:
option = "text"
if flags is None:
flags = TEXT_PRESERVE_WHITESPACE | TEXT_PRESERVE_LIGATURES
if formats[option] == 1:
flags |= TEXT_PRESERVE_IMAGES
if option == "words":
return get_text_words(
page, clip=clip, flags=flags, textpage=textpage, sort=sort
)
if option == "blocks":
return get_text_blocks(
page, clip=clip, flags=flags, textpage=textpage, sort=sort
)
CheckParent(page)
cb = None
if option in ("html", "xml", "xhtml"): # no clipping for MuPDF functions
clip = page.cropbox
if clip != None:
clip = Rect(clip)
cb = None
elif type(page) is Page:
cb = page.cropbox
# TextPage with or without images
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
if option == "json":
t = tp.extractJSON(cb=cb, sort=sort)
elif option == "rawjson":
t = tp.extractRAWJSON(cb=cb, sort=sort)
elif option == "dict":
t = tp.extractDICT(cb=cb, sort=sort)
elif option == "rawdict":
t = tp.extractRAWDICT(cb=cb, sort=sort)
elif option == "html":
t = tp.extractHTML()
elif option == "xml":
t = tp.extractXML()
elif option == "xhtml":
t = tp.extractXHTML()
else:
t = tp.extractText(sort=sort)
if textpage is None:
del tp
return t
def get_page_text(
doc: Document,
pno: int,
option: str = "text",
clip: rect_like = None,
flags: OptInt = None,
textpage: TextPage = None,
sort: bool = False,
) -> typing.Any:
"""Extract a document page's text by page number.
Notes:
Convenience function calling page.get_text().
Args:
pno: page number
option: (str) text, words, blocks, html, dict, json, rawdict, xhtml or xml.
Returns:
output from page.TextPage().
"""
return doc[pno].get_text(option, clip=clip, flags=flags, sort=sort)
def get_pixmap(page: Page, **kw) -> Pixmap:
"""Create pixmap of page.
Args:
matrix: Matrix for transformation (default: Identity).
colorspace: (str/Colorspace) cmyk, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) whether to include alpha channel
annots: (bool) whether to also render annotations
"""
CheckParent(page)
matrix = kw.get("matrix", Identity)
colorspace = kw.get("colorspace", csRGB)
clip = kw.get("clip")
alpha = bool(kw.get("alpha", False))
annots = bool(kw.get("annots", True))
if type(colorspace) is str:
if colorspace.upper() == "GRAY":
colorspace = csGRAY
elif colorspace.upper() == "CMYK":
colorspace = csCMYK
else:
colorspace = csRGB
if colorspace.n not in (1, 3, 4):
raise ValueError("unsupported colorspace")
dl = page.get_displaylist(annots=annots)
pix = dl.get_pixmap(matrix=matrix, colorspace=colorspace, alpha=alpha, clip=clip)
dl = None
return pix
def get_page_pixmap(
doc: Document,
pno: int,
matrix: matrix_like = Identity,
colorspace: Colorspace = csRGB,
clip: rect_like = None,
alpha: bool = False,
annots: bool = True,
) -> Pixmap:
"""Create pixmap of document page by page number.
Notes:
Convenience function calling page.get_pixmap.
Args:
pno: (int) page number
matrix: Matrix for transformation (default: Identity).
colorspace: (str,Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel
annots: (bool) also render annotations
"""
return doc[pno].get_pixmap(
matrix=matrix, colorspace=colorspace, clip=clip, alpha=alpha, annots=annots
)
def getLinkDict(ln) -> dict:
nl = {"kind": ln.dest.kind, "xref": 0}
try:
nl["from"] = ln.rect
except:
pass
pnt = Point(0, 0)
if ln.dest.flags & LINK_FLAG_L_VALID:
pnt.x = ln.dest.lt.x
if ln.dest.flags & LINK_FLAG_T_VALID:
pnt.y = ln.dest.lt.y
if ln.dest.kind == LINK_URI:
nl["uri"] = ln.dest.uri
elif ln.dest.kind == LINK_GOTO:
nl["page"] = ln.dest.page
nl["to"] = pnt
if ln.dest.flags & LINK_FLAG_R_IS_ZOOM:
nl["zoom"] = ln.dest.rb.x
else:
nl["zoom"] = 0.0
elif ln.dest.kind == LINK_GOTOR:
nl["file"] = ln.dest.fileSpec.replace("\\", "/")
nl["page"] = ln.dest.page
if ln.dest.page < 0:
nl["to"] = ln.dest.dest
else:
nl["to"] = pnt
if ln.dest.flags & LINK_FLAG_R_IS_ZOOM:
nl["zoom"] = ln.dest.rb.x
else:
nl["zoom"] = 0.0
elif ln.dest.kind == LINK_LAUNCH:
nl["file"] = ln.dest.fileSpec.replace("\\", "/")
elif ln.dest.kind == LINK_NAMED:
nl["name"] = ln.dest.named
else:
nl["page"] = ln.dest.page
return nl
def get_links(page: Page) -> list:
"""Create a list of all links contained in a PDF page.
Notes:
see PyMuPDF ducmentation for details.
"""
CheckParent(page)
ln = page.first_link
links = []
while ln:
nl = getLinkDict(ln)
links.append(nl)
ln = ln.next
if links != []:
linkxrefs = [x for x in page.annot_xrefs() if x[1] == PDF_ANNOT_LINK]
if len(linkxrefs) == len(links):
for i in range(len(linkxrefs)):
links[i]["xref"] = linkxrefs[i][0]
links[i]["id"] = linkxrefs[i][2]
return links
def get_toc(
doc: Document,
simple: bool = True,
) -> list:
"""Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
"""
def recurse(olItem, liste, lvl):
"""Recursively follow the outline item chain and record item information in a list."""
while olItem and olItem.this.m_internal:
if olItem.title:
title = olItem.title
else:
title = " "
if not olItem.is_external:
if olItem.uri:
if olItem.page == -1:
resolve = doc.resolve_link(olItem.uri)
page = resolve[0] + 1
else:
page = olItem.page + 1
else:
page = -1
else:
page = -1
if not simple:
link = getLinkDict(olItem)
liste.append([lvl, title, page, link])
else:
liste.append([lvl, title, page])
if olItem.down:
liste = recurse(olItem.down, liste, lvl + 1)
olItem = olItem.next
return liste
# ensure document is open
if doc.is_closed:
raise ValueError("document closed")
doc.init_doc()
olItem = doc.outline
if not olItem:
return []
lvl = 1
liste = []
toc = recurse(olItem, liste, lvl)
if doc.is_pdf and simple is False:
doc._extend_toc_items(toc)
return toc
def del_toc_item(
doc: Document,
idx: int,
) -> None:
"""Delete TOC / bookmark item by index."""
xref = doc.get_outline_xrefs()[idx]
doc._remove_toc_item(xref)
def set_toc_item(
doc: Document,
idx: int,
dest_dict: OptDict = None,
kind: OptInt = None,
pno: OptInt = None,