forked from ArtifexSoftware/mupdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfitz_i.py
8716 lines (8682 loc) · 333 KB
/
fitz_i.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
import jlib
from mupdf import *
from fitz_wrap_c import *
#------------------------------------------------------------------------
# SWIG macro: check that a document is not closed / encrypted
#------------------------------------------------------------------------
def CLOSECHECK(meth, doc):
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
def CLOSECHECK0(meth, doc):
if self.is_closed:
raise ValueError("document closed")
#------------------------------------------------------------------------
# SWIG macro: check if object has a valid parent
#------------------------------------------------------------------------
def PARENTCHECK(meth, doc):
CheckParent(self)
FLT_EPSILON = 1e-5
#define SWIG_FILE_WITH_INIT
#define SWIG_PYTHON_2_UNICODE
# memory allocation macros
JM_MEMORY = 1
EMPTY_STRING = ""
def EXISTS(x):
return True if x else False
def THROWMSG(gctx, msg):
raise Exception(msg)
def ASSERT_PDF(cond):
if not cond:
raise Exception("not a PDF")
def INRANGE(v, low, high):
return low <= v and v <= high
def JM_StrAsChar(x):
if isinstance(x, bytes):
return x.decode('utf-8')
elif isinstance(x, str):
return x
else:
assert 0
def JM_BinFromChar(x):
return x.encode('utf-8')
def JM_BinFromCharSize(x, y):
return JM_BinFromChar(x[:y])
#------------------------------------------------------------------------
# global context
#------------------------------------------------------------------------
mfz_register_document_handlers()
#------------------------------------------------------------------------
# START redirect stdout/stderr
#------------------------------------------------------------------------
JM_mupdf_warnings_store = []
JM_mupdf_show_errors = 1
JM_mupdf_show_warnings = 0
user = "PyMuPDF";
#mfz_set_warning_callback(gctx, JM_mupdf_warning, &user);
#fz_set_error_callback(gctx, JM_mupdf_error, &user);
#------------------------------------------------------------------------
# STOP redirect stdout/stderr
#------------------------------------------------------------------------
# init global constants
#------------------------------------------------------------------------
def PyUnicode_InternFromString(s):
return s
dictkey_align = PyUnicode_InternFromString("align");
dictkey_align = PyUnicode_InternFromString("ascender");
dictkey_bbox = PyUnicode_InternFromString("bbox");
dictkey_blocks = PyUnicode_InternFromString("blocks");
dictkey_bpc = PyUnicode_InternFromString("bpc");
dictkey_c = PyUnicode_InternFromString("c");
dictkey_chars = PyUnicode_InternFromString("chars");
dictkey_color = PyUnicode_InternFromString("color");
dictkey_colorspace = PyUnicode_InternFromString("colorspace");
dictkey_content = PyUnicode_InternFromString("content");
dictkey_creationDate = PyUnicode_InternFromString("creationDate");
dictkey_cs_name = PyUnicode_InternFromString("cs-name");
dictkey_da = PyUnicode_InternFromString("da");
dictkey_dashes = PyUnicode_InternFromString("dashes");
dictkey_desc = PyUnicode_InternFromString("desc");
dictkey_desc = PyUnicode_InternFromString("descender");
dictkey_dir = PyUnicode_InternFromString("dir");
dictkey_effect = PyUnicode_InternFromString("effect");
dictkey_ext = PyUnicode_InternFromString("ext");
dictkey_filename = PyUnicode_InternFromString("filename");
dictkey_fill = PyUnicode_InternFromString("fill");
dictkey_flags = PyUnicode_InternFromString("flags");
dictkey_font = PyUnicode_InternFromString("font");
dictkey_height = PyUnicode_InternFromString("height");
dictkey_id = PyUnicode_InternFromString("id");
dictkey_image = PyUnicode_InternFromString("image");
dictkey_items = PyUnicode_InternFromString("items");
dictkey_length = PyUnicode_InternFromString("length");
dictkey_lines = PyUnicode_InternFromString("lines");
dictkey_matrix = PyUnicode_InternFromString("transform");
dictkey_modDate = PyUnicode_InternFromString("modDate");
dictkey_name = PyUnicode_InternFromString("name");
dictkey_number = PyUnicode_InternFromString("number");
dictkey_origin = PyUnicode_InternFromString("origin");
dictkey_rect = PyUnicode_InternFromString("rect");
dictkey_size = PyUnicode_InternFromString("size");
dictkey_smask = PyUnicode_InternFromString("smask");
dictkey_spans = PyUnicode_InternFromString("spans");
dictkey_stroke = PyUnicode_InternFromString("stroke");
dictkey_style = PyUnicode_InternFromString("style");
dictkey_subject = PyUnicode_InternFromString("subject");
dictkey_text = PyUnicode_InternFromString("text");
dictkey_title = PyUnicode_InternFromString("title");
dictkey_type = PyUnicode_InternFromString("type");
dictkey_ufilename = PyUnicode_InternFromString("ufilename");
dictkey_width = PyUnicode_InternFromString("width");
dictkey_wmode = PyUnicode_InternFromString("wmode");
dictkey_xref = PyUnicode_InternFromString("xref");
dictkey_xres = PyUnicode_InternFromString("xres");
dictkey_yres = PyUnicode_InternFromString("yres");
JM_UNIQUE_ID = 0;
class DeviceWrapper:
#fz_device *device;
#fz_display_list *list;
pass
#------------------------------------------------------------------------
# include version information and several other helpers
#------------------------------------------------------------------------
import io
import math
import os
import weakref
import hashlib
import typing
import binascii
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]
#try:
# from pymupdf_fonts import fontdescriptors
#
# fitz_fontdescriptors = fontdescriptors.copy()
# del fontdescriptors
#except ImportError:
# fitz_fontdescriptors = {}
#%}
#%include version.i
#%include helper-defines.i
#%include helper-geo-c.i
#%include helper-other.i
#%include helper-pixmap.i
#%include helper-geo-py.i
#%include helper-annot.i
#%include helper-stext.i
#%include helper-fields.i
#%include helper-python.i
#%include helper-portfolio.i
#%include helper-select.i
#%include helper-xobject.i
#%include helper-pdfinfo.i
#%include helper-convert.i
#%include helper-fileobj.i
#%include helper-devices.i
def PySequence_Check(s):
return isinstance(s, (list, tuple))
#------------------------------------------------------------------------
# fz_document
#------------------------------------------------------------------------
def new_Document(filename, stream, filetype, rect, width, height, fontsize):
#doc = NULL;
#char *c = NULL;
#len = 0;
#fz_stream *data = NULL
w = width
h = height
r = JM_rect_from_py(rect)
jlib.log('{rect=} {r=}')
if not mfz_is_infinite_rect(r):
w = r.x1 - r.x0
h = r.y1 - r.y0
try:
if stream is not None: # stream given, **MUST** be bytes!
c = PyBytes_AS_STRING(stream); # just a pointer, no new obj
len_ = len(stream);
data = mfz_open_memory(c, len_);
magic = filename;
if not magic:
magic = filetype
doc = mfz_open_document_with_stream(magic, data)
else:
if filename:
if not filetype or len(filetype) == 0:
doc = mfz_open_document(filename);
else:
handler = mfz_recognize_document(filetype)
if handler and handler.open:
doc = handler.open(filename)
else:
THROWMSG("unrecognized file type")
else:
pdf = mpdf_create_document()
pdf.dirty = 1
doc = pdf
except Exception as e:
jlib.log('{e=}')
return
if w > 0 and h > 0:
mfz_layout_document(doc, w, h, fontsize)
elif mfz_is_document_reflowable(doc):
mfz_layout_document(doc, 400, 600, 11)
return doc
def Document_loadPage(self, page_id):
doc = self.this
try:
if PySequence_Check(page_id):
chapter = JM_INT_ITEM(page_id, 0)
pno = JM_INT_ITEM(page_id, 1)
page = mfz_load_chapter_page(doc, chapter, pno)
else:
pno = int(page_id)
page = mfz_load_page(doc, pno)
except Exception:
return
return Page(page)
#
#
# FITZEXCEPTION(set_layer, !result)
# %pythonprepend set_layer
#%{"""Set the PDF keys /ON, /OFF, /RBGroups of an OC layer."""
#if self.is_closed:
# raise ValueError("document closed")
#ocgs = set(self.get_ocgs().keys())
#if ocgs == set():
# raise ValueError("document has no optional content")
#
#if on:
# if type(on) not in (list, tuple):
# raise ValueError("bad type: 'on'")
# s = set(on).difference(ocgs)
# if s != set():
# raise ValueError("bad OCGs in 'on': %s" % s)
#
#if off:
# if type(off) not in (list, tuple):
# raise ValueError("bad type: 'off'")
# s = set(off).difference(ocgs)
# if s != set():
# raise ValueError("bad OCGs in 'off': %s" % s)
#
#if rbgroups:
# if type(rbgroups) not in (list, tuple):
# raise ValueError("bad type: 'rbgroups'")
# for x in rbgroups:
# if not type(x) in (list, tuple):
# raise ValueError("bad RBGroup '%s'" % x)
# s = set(x).difference(ocgs)
# if f != set():
# raise ValueError("bad OCGs in RBGroup: %s" % s)
#
#if basestate:
# basestate = str(basestate).upper()
# if basestate == "UNCHANGED":
# basestate = "Unchanged"
# if basestate not in ("ON", "OFF", "Unchanged"):
# raise ValueError("bad 'basestate'")
#%}
# PyObject *
# set_layer(int config, const char *basestate=NULL, PyObject *on=NULL,
# PyObject *off=NULL, PyObject *rbgroups=NULL)
# {
# pdf_obj *obj = NULL;
# fz_try(gctx) {
# pdf_document *pdf = pdf_specifics(gctx, (fz_document *) self);
# ASSERT_PDF(pdf);
# pdf_obj *ocp = pdf_dict_getl(gctx, pdf_trailer(gctx, pdf),
# PDF_NAME(Root), PDF_NAME(OCProperties), NULL);
# if (!ocp) {
# goto finished;
# }
# if (config == -1) {
# obj = pdf_dict_get(gctx, ocp, PDF_NAME(D));
# } else {
# obj = pdf_array_get(gctx, pdf_dict_get(gctx, ocp, PDF_NAME(Configs)), config);
# }
# if (!obj) THROWMSG(gctx, "bad config number");
# JM_set_ocg_arrays(gctx, obj, basestate, on, off, rbgroups);
# pdf_read_ocg(gctx, pdf);
# finished:;
# }
# fz_catch(gctx) {
# return NULL;
# }
# Py_RETURN_NONE;
# }
#
#
# FITZEXCEPTION(add_layer, !result)
# CLOSECHECK0(add_layer, """Add a new OC layer.""")
# PyObject *add_layer(char *name, char *creator=NULL, PyObject *on=NULL)
# {
# fz_try(gctx) {
# pdf_document *pdf = pdf_specifics(gctx, (fz_document *) self);
# ASSERT_PDF(pdf);
# JM_add_layer_config(gctx, pdf, name, creator, on);
# pdf_read_ocg(gctx, pdf);
# }
# fz_catch(gctx) {
# return NULL;
# }
# Py_RETURN_NONE;
# }
#
#
# FITZEXCEPTION(layer_ui_configs, !result)
# CLOSECHECK0(layer_ui_configs, """Show OC visibility status modifyable by user.""")
# PyObject *layer_ui_configs()
# {
# typedef struct
# {
# const char *text;
# int depth;
# pdf_layer_config_ui_type type;
# int selected;
# int locked;
# } pdf_layer_config_ui;
# PyObject *rc = NULL;
#
# fz_try(gctx) {
# pdf_document *pdf = pdf_specifics(gctx, (fz_document *) self);
# ASSERT_PDF(pdf);
# pdf_layer_config_ui info;
# int i, n = pdf_count_layer_config_ui(gctx, pdf);
# rc = PyTuple_New(n);
# char *type = NULL;
# for (i = 0; i < n; i++) {
# pdf_layer_config_ui_info(gctx, pdf, i, (void *) &info);
# switch (info.type)
# {
# case (1): type = "checkbox"; break;
# case (2): type = "radiobox"; break;
# default: type = "label"; break;
# }
# PyObject *item = Py_BuildValue("{s:i,s:s,s:i,s:s,s:O,s:O}",
# "number", i,
# "text", info.text,
# "depth", info.depth,
# "type", type,
# "on", JM_BOOL(info.selected),
# "locked", JM_BOOL(info.locked));
# PyTuple_SET_ITEM(rc, i, item);
# }
# }
# fz_catch(gctx) {
# Py_CLEAR(rc);
# return NULL;
# }
# return rc;
# }
#
#
# FITZEXCEPTION(set_layer_ui_config, !result)
# CLOSECHECK0(set_layer_ui_config, """Set / unset OC intent configuration.""")
# PyObject *set_layer_ui_config(int number, int action=0)
# {
# fz_try(gctx) {
# pdf_document *pdf = pdf_specifics(gctx, (fz_document *) self);
# ASSERT_PDF(pdf);
# switch (action)
# {
# case (1):
# pdf_toggle_layer_config_ui(gctx, pdf, number);
# break;
# case (2):
# pdf_deselect_layer_config_ui(gctx, pdf, number);
# break;
# default:
# pdf_select_layer_config_ui(gctx, pdf, number);
# break;
# }
# }
# fz_catch(gctx) {
# return NULL;
# }
# Py_RETURN_NONE;
# }
#
#
# FITZEXCEPTION(get_ocgs, !result)
# CLOSECHECK0(get_ocgs, """Show existing optional content groups.""")
# PyObject *
# get_ocgs()
# {
# PyObject *rc = NULL;
# pdf_obj *ci = pdf_new_name(gctx, "CreatorInfo");
# fz_try(gctx) {
# pdf_document *pdf = pdf_specifics(gctx, (fz_document *) self);
# ASSERT_PDF(pdf);
# pdf_obj *ocgs = pdf_dict_getl(gctx,
# pdf_dict_get(gctx,
# pdf_trailer(gctx, pdf), PDF_NAME(Root)),
# PDF_NAME(OCProperties), PDF_NAME(OCGs), NULL);
# rc = PyDict_New();
# if (!pdf_is_array(gctx, ocgs)) goto fertig;
# int i, n = pdf_array_len(gctx, ocgs);
# for (i = 0; i < n; i++) {
# pdf_obj *ocg = pdf_array_get(gctx, ocgs, i);
# int xref = pdf_to_num(gctx, ocg);
# const char *name = pdf_to_text_string(gctx, pdf_dict_get(gctx, ocg, PDF_NAME(Name)));
# pdf_obj *obj = pdf_dict_getl(gctx, ocg, PDF_NAME(Usage), ci, PDF_NAME(Subtype), NULL);
# const char *usage = NULL;
# if (obj) usage = pdf_to_name(gctx, obj);
# PyObject *intents = PyList_New(0);
# pdf_obj *intent = pdf_dict_get(gctx, ocg, PDF_NAME(Intent));
# if (intent) {
# if (pdf_is_name(gctx, intent)) {
# LIST_APPEND_DROP(intents, Py_BuildValue("s", pdf_to_name(gctx, intent)));
# } else if (pdf_is_array(gctx, intent)) {
# int j, m = pdf_array_len(gctx, intent);
# for (j = 0; j < m; j++) {
# pdf_obj *o = pdf_array_get(gctx, intent, j);
# if (pdf_is_name(gctx, o))
# LIST_APPEND_DROP(intents, Py_BuildValue("s", pdf_to_name(gctx, o)));
# }
# }
# }
# pdf_ocg_descriptor *desc = pdf->ocg;
# int hidden = pdf_is_hidden_ocg(gctx, desc, NULL, usage, ocg);
# PyObject *item = Py_BuildValue("{s:s,s:O,s:O,s:s}",
# "name", name,
# "intent", intents,
# "on", JM_BOOL(!hidden),
# "usage", usage);
# Py_DECREF(intents);
# PyObject *temp = Py_BuildValue("i", xref);
# DICT_SETITEM_DROP(rc, temp, item);
# Py_DECREF(temp);
# }
# fertig:;
# }
# fz_always(gctx) {
# pdf_drop_obj(gctx, ci);
# }
# fz_catch(gctx) {
# Py_CLEAR(rc);
# return NULL;
# }
# return rc;
# }
#
#
# FITZEXCEPTION(add_ocg, !result)
# CLOSECHECK0(add_ocg, """Add new optional content group.""")
# PyObject *
# add_ocg(char *name, int config=-1, int on=1, PyObject *intent=NULL, const char *usage=NULL)
# {
# int xref = 0;
# pdf_obj *obj = NULL, *cfg = NULL;
# pdf_obj *indocg = NULL;
# fz_try(gctx) {
# pdf_document *pdf = pdf_specifics(gctx, (fz_document *) self);
# ASSERT_PDF(pdf);
#
# // ------------------------------
# // make the OCG
# // ------------------------------
# pdf_obj *ocg = pdf_add_new_dict(gctx, pdf, 3);
# pdf_dict_put(gctx, ocg, PDF_NAME(Type), PDF_NAME(OCG));
# pdf_dict_put_text_string(gctx, ocg, PDF_NAME(Name), name);
# pdf_obj *intents = pdf_dict_put_array(gctx, ocg, PDF_NAME(Intent), 2);
# if (!EXISTS(intent)) {
# pdf_array_push(gctx, intents, PDF_NAME(View));
# } else if (!PyUnicode_Check(intent)) {
# int i, n = PySequence_Size(intent);
# for (i = 0; i < n; i++) {
# PyObject *item = PySequence_ITEM(intent, i);
# char *c = JM_StrAsChar(item);
# if (c) {
# pdf_array_push(gctx, intents, pdf_new_name(gctx, c));
# }
# Py_DECREF(item);
# }
# } else {
# char *c = JM_StrAsChar(intent);
# if (c) {
# pdf_array_push(gctx, intents, pdf_new_name(gctx, c));
# }
# }
# pdf_obj *use_for = pdf_dict_put_dict(gctx, ocg, PDF_NAME(Usage), 3);
# pdf_obj *ci_name = pdf_new_name(gctx, "CreatorInfo");
# pdf_obj *cre_info = pdf_dict_put_dict(gctx, use_for, ci_name, 2);
# pdf_dict_put_text_string(gctx, cre_info, PDF_NAME(Creator), "PyMuPDF");
# if (usage) {
# pdf_dict_put_name(gctx, cre_info, PDF_NAME(Subtype), usage);
# } else {
# pdf_dict_put_name(gctx, cre_info, PDF_NAME(Subtype), "Artwork");
# }
# indocg = pdf_add_object(gctx, pdf, ocg);
#
# // ------------------------------
# // Insert OCG in the right config
# // ------------------------------
# pdf_obj *ocp = JM_ensure_ocproperties(gctx, pdf);
# obj = pdf_dict_get(gctx, ocp, PDF_NAME(OCGs));
# pdf_array_push(gctx, obj, indocg);
#
# if (config > -1) {
# obj = pdf_dict_get(gctx, ocp, PDF_NAME(Configs));
# if (!pdf_is_array(gctx, obj)) {
# THROWMSG(gctx, "bad config number");
# }
# cfg = pdf_array_get(gctx, obj, config);
# if (!cfg) {
# THROWMSG(gctx, "bad config number");
# }
# } else {
# cfg = pdf_dict_get(gctx, ocp, PDF_NAME(D));
# }
#
# obj = pdf_dict_get(gctx, cfg, PDF_NAME(Order));
# if (!obj) {
# obj = pdf_dict_put_array(gctx, cfg, PDF_NAME(Order), 1);
# }
# pdf_array_push(gctx, obj, indocg);
# if (on) {
# obj = pdf_dict_get(gctx, cfg, PDF_NAME(ON));
# if (!obj) {
# obj = pdf_dict_put_array(gctx, cfg, PDF_NAME(ON), 1);
# }
# } else {
# obj = pdf_dict_get(gctx, cfg, PDF_NAME(OFF));
# if (!obj) {
# obj = pdf_dict_put_array(gctx, cfg, PDF_NAME(OFF), 1);
# }
# }
# pdf_array_push(gctx, obj, indocg);
#
# // let MuPDF take note: re-read OCProperties
# pdf_read_ocg(gctx, pdf);
#
# xref = pdf_to_num(gctx, indocg);
# }
# fz_always(gctx) {
# pdf_drop_obj(gctx, indocg);
# }
# fz_catch(gctx) {
# return NULL;
# }
# return Py_BuildValue("i", xref);
# }
#
#
# //------------------------------------------------------------------
# // Initialize document: set outline and metadata properties
# //------------------------------------------------------------------
# %pythoncode %{
# def init_doc(self):
# if self.is_encrypted:
# raise ValueError("cannot initialize - document still encrypted")
# self._outline = self._loadOutline()
# self.metadata = dict([(k,self._getMetadata(v)) for k,v in {'format':'format', 'title':'info:Title', #'author':'info:Author','subject':'info:Subject', 'keywords':'info:Keywords','creator':'info:Creator', #'producer':'info:Producer', 'creationDate':'info:CreationDate', 'modDate':'info:ModDate', #'trapped':'info:Trapped'}.items()])
# self.metadata['encryption'] = None if self._getMetadata('encryption')=='None' else #self._getMetadata('encryption')
#
# outline = property(lambda self: self._outline)
#
#
# def get_page_fonts(self, pno: int, full: bool =False) -> list:
# """Retrieve a list of fonts used on a page.
# """
# if self.is_closed or self.is_encrypted:
# raise ValueError("document closed or encrypted")
# if not self.is_pdf:
# return ()
# if type(pno) is not int:
# try:
# pno = pno.number
# except:
# raise ValueError("need a Page or page number")
# val = self._getPageInfo(pno, 1)
# if full is False:
# return [v[:-1] for v in val]
# return val
#
#
# def get_page_images(self, pno: int, full: bool =False) -> list:
# """Retrieve a list of images used on a page.
# """
# if self.is_closed or self.is_encrypted:
# raise ValueError("document closed or encrypted")
# if not self.is_pdf:
# return ()
# if type(pno) is not int:
# try:
# pno = pno.number
# except:
# raise ValueError("need a Page or page number")
# val = self._getPageInfo(pno, 2)
# if full is False:
# return [v[:-1] for v in val]
# return val
#
#
# def get_page_xobjects(self, pno: int) -> list:
# """Retrieve a list of XObjects used on a page.
# """
# if self.is_closed or self.is_encrypted:
# raise ValueError("document closed or encrypted")
# if not self.is_pdf:
# return ()
# if type(pno) is not int:
# try:
# pno = pno.number
# except:
# raise ValueError("need a Page or page number")
# val = self._getPageInfo(pno, 3)
# rc = [(v[0], v[1], v[2], Rect(v[3])) for v in val]
# return rc
#
#
# def xref_is_image(self, xref):
# """Check if xref is an image object."""
# if self.is_closed or self.is_encrypted:
# raise ValueError("document closed or encrypted")
# if self.xref_get_key(xref, "Subtype")[1] == "/Image":
# return True
# return False
#
# def xref_is_font(self, xref):
# """Check if xref is a font object."""
# if self.is_closed or self.is_encrypted:
# raise ValueError("document closed or encrypted")
# if self.xref_get_key(xref, "Type")[1] == "/Font":
# return True
# return False
#
# def xref_is_xobject(self, xref):
# """Check if xref is a form xobject."""
# if self.is_closed or self.is_encrypted:
# raise ValueError("document closed or encrypted")
# if self.xref_get_key(xref, "Subtype")[1] == "/Form":
# return True
# return False
#
# def copy_page(self, pno: int, to: int =-1):
# """Copy a page within a PDF document.
#
# This will only create another reference of the same page object.
# Args:
# pno: source page number
# to: put before this page, '-1' means after last page.
# """
# if self.is_closed:
# raise ValueError("document closed")
#
# page_count = len(self)
# if (
# pno not in range(page_count) or
# to not in range(-1, page_count)
# ):
# raise ValueError("bad page number(s)")
# before = 1
# copy = 1
# if to == -1:
# to = page_count - 1
# before = 0
#
# return self._move_copy_page(pno, to, before, copy)
#
# def move_page(self, pno: int, to: int =-1):
# """Move a page within a PDF document.
#
# Args:
# pno: source page number.
# to: put before this page, '-1' means after last page.
# """
# if self.is_closed:
# raise ValueError("document closed")
#
# page_count = len(self)
# if (
# pno not in range(page_count) or
# to not in range(-1, page_count)
# ):
# raise ValueError("bad page number(s)")
# before = 1
# copy = 0
# if to == -1:
# to = page_count - 1
# before = 0
#
# return self._move_copy_page(pno, to, before, copy)
#
# def delete_page(self, pno: int =-1):
# """ Delete one page from a PDF.
# """
# if not self.is_pdf:
# raise ValueError("not a PDF")
# if self.is_closed:
# raise ValueError("document closed")
#
# page_count = self.page_count
# while pno < 0:
# pno += page_count
#
# if pno >= page_count:
# raise ValueError("bad page number(s)")
#
# # remove TOC bookmarks pointing to deleted page
# toc = self.get_toc()
# ol_xrefs = self.get_outline_xrefs()
# for i, item in enumerate(toc):
# if item[2] == pno + 1:
# self._remove_toc_item(ol_xrefs[i])
#
# self._remove_links_to(frozenset((pno,)))
# self._delete_page(pno)
# self._reset_page_refs()
#
#
# def delete_pages(self, *args, **kw):
# """Delete pages from a PDF.
#
# Args:
# Either keywords 'from_page'/'to_page', or two integers to
# specify the first/last page to delete.
# Or a list/tuple/range object, which can contain arbitrary
# page numbers.
# """
# if not self.is_pdf:
# raise ValueError("not a PDF")
# if self.is_closed:
# raise ValueError("document closed")
#
# page_count = self.page_count # page count of document
# f = t = -1
# if kw: # check if keywords were used
# if args != []: # then no positional args are allowed
# raise ValueError("cannot mix keyword and positional argument")
# f = kw.get("from_page", -1) # first page to delete
# t = kw.get("to_page", -1) # last page to delete
# while f < 0:
# f += page_count
# while t < 0:
# t += page_count
# if not f <= t < page_count:
# raise ValueError("bad page number(s)")
# numbers = tuple(range(f, t + 1))
# else:
# if len(args) > 2 or args == []:
# raise ValueError("need 1 or 2 positional arguments")
# if len(args) == 2:
# f, t = args
# if not (type(f) is int and type(t) is int):
# raise ValueError("both arguments must be int")
# if f > t:
# f, t = t, f
# if not f <= t < page_count:
# raise ValueError("bad page number(s)")
# numbers = tuple(range(f, t + 1))
# else:
# r = args[0]
# if type(r) not in (int, range, list, tuple):
# raise ValueError("need int or sequence if one argument")
# numbers = tuple(r)
#
# numbers = list(map(int, set(numbers))) # ensure unique integers
# if numbers == []:
# print("nothing to delete")
# return
# numbers.sort()
# if numbers[0] < 0 or numbers[-1] >= page_count:
# raise ValueError("bad page number(s)")
# frozen_numbers = frozenset(numbers)
# toc = self.get_toc()
# for i, xref in enumerate(self.get_outline_xrefs()):
# if toc[i][2] - 1 in frozen_numbers:
# self._remove_toc_item(xref) # remove target in PDF object
#
# self._remove_links_to(frozen_numbers)
#
# for i in reversed(numbers): # delete pages, last to first
# self._delete_page(i)
#
# self._reset_page_refs()
#
#
# def saveIncr(self):
# """ Save PDF incrementally"""
# return self.save(self.name, incremental=True, encryption=PDF_ENCRYPT_KEEP)
#
#
# def ez_save(self, filename, garbage=3, clean=False,
# deflate=True, deflate_images=True, deflate_fonts=True,
# incremental=False, ascii=False, expand=False, linear=False,
# pretty=False, encryption=1, permissions=4095,
# owner_pw=None, user_pw=None):
# """ Save PDF using some different defaults"""
# return self.save(filename, garbage=garbage,
# clean=clean,
# deflate=deflate,
# deflate_images=deflate_images,
# deflate_fonts=deflate_fonts,
# incremental=incremental,
# ascii=ascii,
# expand=expand,
# linear=linear,
# pretty=pretty,
# encryption=encryption,
# permissions=permissions,
# owner_pw=owner_pw,
# user_pw=user_pw)
#
#
# def reload_page(self, page: "struct Page *") -> "struct Page *":
# """Make a fresh copy of a page."""
# old_annots = {} # copy annot references to here
# pno = page.number # save the page number
# for k, v in page._annot_refs.items(): # save the annot dictionary
# old_annots[k] = v
# page._erase() # remove the page
# page = None
# page = self.load_page(pno) # reload the page
#
# # copy annot refs over to the new dictionary
# page_proxy = weakref.proxy(page)
# for k, v in old_annots.items():
# annot = old_annots[k]
# annot.parent = page_proxy # refresh parent to new page
# page._annot_refs[k] = annot
# return page
#
#
# def __repr__(self) -> str:
# m = "closed " if self.is_closed else ""
# if self.stream is None:
# if self.name == "":
# return m + "Document(<new PDF, doc# %i>)" % self._graft_id
# return m + "Document('%s')" % (self.name,)
# return m + "Document('%s', <memory, doc# %i>)" % (self.name, self._graft_id)
#
#
# def __contains__(self, loc) -> bool:
# if type(loc) is int:
# if loc < self.page_count:
# return True
# return False
# if type(loc) not in (tuple, list) or len(loc) != 2:
# return False
#
# chapter, pno = loc
# if (type(chapter) != int or
# chapter < 0 or
# chapter >= self.chapter_count
# ):
# return False
# if (type(pno) != int or
# pno < 0 or
# pno >= self.chapter_page_count(chapter)
# ):
# return False
#
# return True
#
#
# def __getitem__(self, i: int =0)->"Page":
# if i not in self:
# raise IndexError("page not in document")
# return self.load_page(i)
#
#
# def __delitem__(self, i: AnyType)->None:
# if not self.is_pdf:
# raise ValueError("not a PDF")
# if type(i) is int:
# return self.delete_page(i)
# if type(i) in (list, tuple, range):
# return self.delete_pages(i)
# if type(i) is not slice:
# raise ValueError("bad argument type")
# pc = self.page_count
# start = i.start if i.start else 0
# stop = i.stop if i.stop else pc
# step = i.step if i.step else 1
# while start < 0:
# start += pc
# if start >= pc:
# raise ValueError("bad page number(s)")
# while stop < 0:
# stop += pc
# if stop > pc:
# raise ValueError("bad page number(s)")
# return self.delete_pages(range(start, stop, step))
#
#
# def pages(self, start: OptInt =None, stop: OptInt =None, step: OptInt =None):
# """Return a generator iterator over a page range.
#
# Arguments have the same meaning as for the range() built-in.
# """
# # set the start value
# start = start or 0
# while start < 0:
# start += self.page_count
# if start not in range(self.page_count):
# raise ValueError("bad start page number")
#
# # set the stop value
# stop = stop if stop is not None and stop <= self.page_count else self.page_count
#
# # set the step value
# if step == 0:
# raise ValueError("arg 3 must not be zero")
# if step is None:
# if start > stop:
# step = -1
# else:
# step = 1
#
# for pno in range(start, stop, step):
# yield (self.load_page(pno))
#
#
# def __len__(self) -> int:
# return self.page_count
#
# def _forget_page(self, page: "struct Page *"):
# """Remove a page from document page dict."""
# pid = id(page)
# if pid in self._page_refs:
# self._page_refs[pid] = None
#
# def _reset_page_refs(self):
# """Invalidate all pages in document dictionary."""
# if self.is_closed:
# return
# for page in self._page_refs.values():
# if page:
# page._erase()
# page = None
# self._page_refs.clear()
#
# def __del__(self):
# if hasattr(self, "_reset_page_refs"):
# self._reset_page_refs()
# if hasattr(self, "Graftmaps"):
# for k in self.Graftmaps.keys():
# self.Graftmaps[k] = None
# if hasattr(self, "this") and self.thisown:
# try:
# self.__swig_destroy__(self)
# except:
# pass
# self.thisown = False
#
# self.Graftmaps = {}
# self.ShownPages = {}
# self.InsertedImages = {}
# self.stream = None
# self._reset_page_refs = DUMMY
# self.__swig_destroy__ = DUMMY
# self.is_closed = True
#
# def __enter__(self):
# return self
#
# def __exit__(self, *args):
# if hasattr(self, "_reset_page_refs"):