-
Notifications
You must be signed in to change notification settings - Fork 585
/
Copy pathfitz_old.i
15210 lines (13920 loc) · 570 KB
/
fitz_old.i
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
%module fitz
%pythonbegin %{
%}
//------------------------------------------------------------------------
// SWIG macros: handle fitz exceptions
//------------------------------------------------------------------------
%define FITZEXCEPTION(meth, cond)
%exception meth
{
$action
if (cond) {
return JM_ReturnException(gctx);
}
}
%enddef
%define FITZEXCEPTION2(meth, cond)
%exception meth
{
$action
if (cond) {
const char *msg = fz_caught_message(gctx);
if (strcmp(msg, MSG_BAD_FILETYPE) == 0) {
PyErr_SetString(PyExc_ValueError, msg);
} else {
PyErr_SetString(JM_Exc_FileDataError, MSG_BAD_DOCUMENT);
}
return NULL;
}
}
%enddef
//------------------------------------------------------------------------
// SWIG macro: check that a document is not closed / encrypted
//------------------------------------------------------------------------
%define CLOSECHECK(meth, doc)
%pythonprepend meth %{doc
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")%}
%enddef
%define CLOSECHECK0(meth, doc)
%pythonprepend meth%{doc
if self.is_closed:
raise ValueError("document closed")%}
%enddef
//------------------------------------------------------------------------
// SWIG macro: check if object has a valid parent
//------------------------------------------------------------------------
%define PARENTCHECK(meth, doc)
%pythonprepend meth %{doc
CheckParent(self)%}
%enddef
//------------------------------------------------------------------------
// SWIG macro: ensure object still exists
//------------------------------------------------------------------------
%define ENSURE_OWNERSHIP(meth, doc)
%pythonprepend meth %{doc
EnsureOwnership(self)%}
%enddef
%include "mupdf/fitz/version.h"
%{
#define MEMDEBUG 0
#if MEMDEBUG == 1
#define DEBUGMSG1(x) PySys_WriteStderr("[DEBUG] free %s ", x)
#define DEBUGMSG2 PySys_WriteStderr("... done!\n")
#else
#define DEBUGMSG1(x)
#define DEBUGMSG2
#endif
#ifndef FLT_EPSILON
#define FLT_EPSILON 1e-5
#endif
#define SWIG_FILE_WITH_INIT
// JM_MEMORY controls what allocators we tell MuPDF to use when we call
// fz_new_context():
//
// JM_MEMORY=0: MuPDF uses malloc()/free().
// JM_MEMORY=1: MuPDF uses PyMem_Malloc()/PyMem_Free().
//
// There are also a small number of places where we call malloc() or
// PyMem_Malloc() ourselves, depending on JM_MEMORY.
//
#define JM_MEMORY 0
#if JM_MEMORY == 1
#define JM_Alloc(type, len) PyMem_New(type, len)
#define JM_Free(x) PyMem_Del(x)
#else
#define JM_Alloc(type, len) (type *) malloc(sizeof(type)*len)
#define JM_Free(x) free(x)
#endif
#define EMPTY_STRING PyUnicode_FromString("")
#define EXISTS(x) (x != NULL && PyObject_IsTrue(x)==1)
#define RAISEPY(context, msg, exc) {JM_Exc_CurrentException=exc; fz_throw(context, FZ_ERROR_GENERIC, msg);}
#define ASSERT_PDF(cond) if (cond == NULL) RAISEPY(gctx, MSG_IS_NO_PDF, PyExc_RuntimeError)
#define ENSURE_OPERATION(ctx, pdf) if (!JM_have_operation(ctx, pdf)) RAISEPY(ctx, "No journalling operation started", PyExc_RuntimeError)
#define INRANGE(v, low, high) ((low) <= v && v <= (high))
#define JM_BOOL(x) PyBool_FromLong((long) (x))
#define JM_PyErr_Clear if (PyErr_Occurred()) PyErr_Clear()
#define JM_StrAsChar(x) (char *)PyUnicode_AsUTF8(x)
#define JM_BinFromChar(x) PyBytes_FromString(x)
#define JM_BinFromCharSize(x, y) PyBytes_FromStringAndSize(x, (Py_ssize_t) y)
#include <mupdf/fitz.h>
#include <mupdf/pdf.h>
#include <time.h>
// freetype includes >> --------------------------------------------------
#include <ft2build.h>
#include FT_FREETYPE_H
#ifdef FT_FONT_FORMATS_H
#include FT_FONT_FORMATS_H
#else
#include FT_XFREE86_H
#endif
#include FT_TRUETYPE_TABLES_H
#ifndef FT_SFNT_HEAD
#define FT_SFNT_HEAD ft_sfnt_head
#endif
// << freetype includes --------------------------------------------------
void JM_delete_widget(fz_context *ctx, pdf_page *page, pdf_annot *annot);
static void JM_get_page_labels(fz_context *ctx, PyObject *liste, pdf_obj *nums);
static int DICT_SETITEMSTR_DROP(PyObject *dict, const char *key, PyObject *value);
static int LIST_APPEND_DROP(PyObject *list, PyObject *item);
static int LIST_APPEND_DROP(PyObject *list, PyObject *item);
static fz_irect JM_irect_from_py(PyObject *r);
static fz_matrix JM_matrix_from_py(PyObject *m);
static fz_point JM_normalize_vector(float x, float y);
static fz_point JM_point_from_py(PyObject *p);
static fz_quad JM_quad_from_py(PyObject *r);
static fz_rect JM_rect_from_py(PyObject *r);
static int JM_FLOAT_ITEM(PyObject *obj, Py_ssize_t idx, double *result);
static int JM_INT_ITEM(PyObject *obj, Py_ssize_t idx, int *result);
static PyObject *JM_py_from_irect(fz_irect r);
static PyObject *JM_py_from_matrix(fz_matrix m);
static PyObject *JM_py_from_point(fz_point p);
static PyObject *JM_py_from_quad(fz_quad q);
static PyObject *JM_py_from_rect(fz_rect r);
static void show(const char* prefix, PyObject* obj);
// additional headers ----------------------------------------------
#if FZ_VERSION_MAJOR == 1 && FZ_VERSION_MINOR == 23 && FZ_VERSION_PATCH < 8
pdf_obj *pdf_lookup_page_loc(fz_context *ctx, pdf_document *doc, int needle, pdf_obj **parentp, int *indexp);
fz_pixmap *fz_scale_pixmap(fz_context *ctx, fz_pixmap *src, float x, float y, float w, float h, const fz_irect *clip);
int fz_pixmap_size(fz_context *ctx, fz_pixmap *src);
void fz_subsample_pixmap(fz_context *ctx, fz_pixmap *tile, int factor);
void fz_copy_pixmap_rect(fz_context *ctx, fz_pixmap *dest, fz_pixmap *src, fz_irect b, const fz_default_colorspaces *default_cs);
void fz_write_pixmap_as_jpeg(fz_context *ctx, fz_output *out, fz_pixmap *pix, int jpg_quality);
#endif
static const float JM_font_ascender(fz_context *ctx, fz_font *font);
static const float JM_font_descender(fz_context *ctx, fz_font *font);
// end of additional headers --------------------------------------------
static PyObject *JM_mupdf_warnings_store;
static int JM_mupdf_show_errors;
static int JM_mupdf_show_warnings;
static PyObject *JM_Exc_FileDataError;
static PyObject *JM_Exc_CurrentException;
%}
//------------------------------------------------------------------------
// global context
//------------------------------------------------------------------------
%init %{
#if FZ_VERSION_MAJOR == 1 && FZ_VERSION_MINOR >= 22
/* Stop Memento backtraces if we reach the Python interpreter.
`cfunction_call()` isn't the only way that Python calls C though, so we
might need extra calls to Memento_addBacktraceLimitFnname().
We put this inside `#ifdef MEMENTO` because memento.h's disabling macro
causes "warning: statement with no effect" from cc. */
#ifdef MEMENTO
Memento_addBacktraceLimitFnname("cfunction_call");
#endif
#endif
/*
We end up with Memento leaks from fz_new_context()'s allocs even when our
atexit handler calls fz_drop_context(), so remove these from Memento's
accounting.
*/
Memento_startLeaking();
#if JM_MEMORY == 1
gctx = fz_new_context(&JM_Alloc_Context, NULL, FZ_STORE_DEFAULT);
#else
gctx = fz_new_context(NULL, NULL, FZ_STORE_DEFAULT);
#endif
Memento_stopLeaking();
if(!gctx)
{
PyErr_SetString(PyExc_RuntimeError, "Fatal error: cannot create global context.");
return NULL;
}
fz_register_document_handlers(gctx);
//------------------------------------------------------------------------
// START redirect stdout/stderr
//------------------------------------------------------------------------
JM_mupdf_warnings_store = PyList_New(0);
JM_mupdf_show_errors = 1;
JM_mupdf_show_warnings = 0;
char user[] = "PyMuPDF";
fz_set_warning_callback(gctx, JM_mupdf_warning, &user);
fz_set_error_callback(gctx, JM_mupdf_error, &user);
JM_Exc_FileDataError = NULL;
JM_Exc_CurrentException = PyExc_RuntimeError;
//------------------------------------------------------------------------
// STOP redirect stdout/stderr
//------------------------------------------------------------------------
// init global constants
//------------------------------------------------------------------------
dictkey_align = PyUnicode_InternFromString("align");
dictkey_ascender = 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_descender = 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_glyph = PyUnicode_InternFromString("glyph");
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");
atexit( cleanup);
%}
%header %{
fz_context *gctx;
static void cleanup()
{
fz_drop_context( gctx);
}
static int JM_UNIQUE_ID = 0;
struct DeviceWrapper {
fz_device *device;
fz_display_list *list;
};
%}
//------------------------------------------------------------------------
// include version information and several other helpers
//------------------------------------------------------------------------
%pythoncode %{
import sys
import io
import math
import os
import weakref
import hashlib
import typing
import binascii
import re
import tarfile
import zipfile
import pathlib
import string
# PDF names must not contain these characters:
INVALID_NAME_CHARS = set(string.whitespace + "()<>[]{}/%" + chr(0))
TESSDATA_PREFIX = os.getenv("TESSDATA_PREFIX")
point_like = "point_like"
rect_like = "rect_like"
matrix_like = "matrix_like"
quad_like = "quad_like"
# ByteString is gone from typing in 3.14.
# collections.abc.Buffer available from 3.12 only
try:
ByteString = typing.ByteString
except AttributeError:
ByteString = bytes | bytearray | memoryview
AnyType = typing.Any
OptInt = typing.Union[int, None]
OptFloat = typing.Optional[float]
OptStr = typing.Optional[str]
OptDict = typing.Optional[dict]
OptBytes = typing.Optional[ByteString]
OptSeq = typing.Optional[typing.Sequence]
try:
from pymupdf_fonts import fontdescriptors, fontbuffers
fitz_fontdescriptors = fontdescriptors.copy()
for k in fitz_fontdescriptors.keys():
fitz_fontdescriptors[k]["loader"] = fontbuffers[k]
del fontdescriptors, fontbuffers
except ImportError:
fitz_fontdescriptors = {}
%}
%include version.i
%include helper-git-versions.i
%include helper-defines.i
%include helper-globals.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-fields.i
%include helper-python.i
%include helper-portfolio.i
%include helper-select.i
%include helper-stext.i
%include helper-xobject.i
%include helper-pdfinfo.i
%include helper-convert.i
%include helper-fileobj.i
%include helper-devices.i
%{
// Declaring these structs here prevents gcc from generating warnings like:
//
// warning: 'struct Document' declared inside parameter list will not be visible outside of this definition or declaration
//
struct Colorspace;
struct Document;
struct Font;
struct Graftmap;
struct TextPage;
struct TextWriter;
struct DocumentWriter;
struct Xml;
struct Archive;
struct Story;
%}
//------------------------------------------------------------------------
// fz_document
//------------------------------------------------------------------------
struct Document
{
%extend
{
~Document()
{
DEBUGMSG1("Document");
fz_document *this_doc = (fz_document *) $self;
fz_drop_document(gctx, this_doc);
DEBUGMSG2;
}
FITZEXCEPTION2(Document, !result)
%pythonprepend Document %{
"""Creates a document. Use 'open' as a synonym.
Notes:
Basic usages:
open() - new PDF document
open(filename) - string, pathlib.Path, or file object.
open(filename, fileype=type) - overwrite filename extension.
open(type, buffer) - type: extension, buffer: bytes object.
open(stream=buffer, filetype=type) - keyword version of previous.
Parameters rect, width, height, fontsize: layout reflowable
document on open (e.g. EPUB). Ignored if n/a.
"""
self.is_closed = False
self.is_encrypted = False
self.isEncrypted = False
self.metadata = None
self.FontInfos = []
self.Graftmaps = {}
self.ShownPages = {}
self.InsertedImages = {}
self._page_refs = weakref.WeakValueDictionary()
if not filename or type(filename) is str:
pass
elif hasattr(filename, "absolute"):
filename = str(filename)
elif hasattr(filename, "name"):
filename = filename.name
else:
msg = "bad filename"
raise TypeError(msg)
if stream != None:
if type(stream) is bytes:
self.stream = stream
elif type(stream) is bytearray:
self.stream = bytes(stream)
elif type(stream) is io.BytesIO:
self.stream = stream.getvalue()
else:
msg = "bad type: 'stream'"
raise TypeError(msg)
stream = self.stream
if not (filename or filetype):
filename = "pdf"
else:
self.stream = None
if filename and self.stream == None:
self.name = filename
from_file = True
else:
from_file = False
self.name = ""
if from_file:
if not os.path.exists(filename):
msg = f"no such file: '{filename}'"
raise FileNotFoundError(msg)
elif not os.path.isfile(filename):
msg = f"'{filename}' is no file"
raise FileDataError(msg)
if from_file and os.path.getsize(filename) == 0 or type(self.stream) is bytes and len(self.stream) == 0:
msg = "cannot open empty document"
raise EmptyFileError(msg)
%}
%pythonappend Document %{
if self.thisown:
self._graft_id = TOOLS.gen_id()
if self.needs_pass is True:
self.is_encrypted = True
self.isEncrypted = True
else: # we won't init until doc is decrypted
self.init_doc()
# the following hack detects invalid/empty SVG files, which else may lead
# to interpreter crashes
if filename and filename.lower().endswith("svg") or filetype and "svg" in filetype.lower():
try:
_ = self.convert_to_pdf() # this seems to always work
except:
raise FileDataError("cannot open broken document") from None
%}
Document(const char *filename=NULL, PyObject *stream=NULL,
const char *filetype=NULL, PyObject *rect=NULL,
float width=0, float height=0,
float fontsize=11)
{
int old_msg_option = JM_mupdf_show_errors;
JM_mupdf_show_errors = 0;
fz_document *doc = NULL;
const fz_document_handler *handler;
char *c = NULL;
char *magic = NULL;
size_t len = 0;
fz_stream *data = NULL;
float w = width, h = height;
fz_rect r = JM_rect_from_py(rect);
if (!fz_is_infinite_rect(r)) {
w = r.x1 - r.x0;
h = r.y1 - r.y0;
}
fz_try(gctx) {
if (stream != Py_None) { // stream given, **MUST** be bytes!
c = PyBytes_AS_STRING(stream); // just a pointer, no new obj
len = (size_t) PyBytes_Size(stream);
data = fz_open_memory(gctx, (const unsigned char *) c, len);
magic = (char *)filename;
if (!magic) magic = (char *)filetype;
handler = fz_recognize_document(gctx, magic);
if (!handler) {
RAISEPY(gctx, MSG_BAD_FILETYPE, PyExc_ValueError);
}
doc = fz_open_document_with_stream(gctx, magic, data);
} else {
if (filename && strlen(filename)) {
if (!filetype || strlen(filetype) == 0) {
doc = fz_open_document(gctx, filename);
} else {
handler = fz_recognize_document(gctx, filetype);
if (!handler) {
RAISEPY(gctx, MSG_BAD_FILETYPE, PyExc_ValueError);
}
#if FZ_VERSION_MINOR >= 24
if (handler->open)
{
fz_stream* filename_stream = fz_open_file(gctx, filename);
fz_try(gctx)
{
doc = handler->open(gctx, filename_stream, NULL, NULL);
}
fz_always(gctx)
{
fz_drop_stream(gctx, filename_stream);
}
fz_catch(gctx)
{
fz_rethrow(gctx);
}
}
#else
if (handler->open) {
doc = handler->open(gctx, filename);
} else if (handler->open_with_stream) {
data = fz_open_file(gctx, filename);
doc = handler->open_with_stream(gctx, data);
}
#endif
}
} else {
pdf_document *pdf = pdf_create_document(gctx);
doc = (fz_document *) pdf;
}
}
}
fz_always(gctx) {
fz_drop_stream(gctx, data);
}
fz_catch(gctx) {
JM_mupdf_show_errors = old_msg_option;
return NULL;
}
if (w > 0 && h > 0) {
fz_layout_document(gctx, doc, w, h, fontsize);
} else if (fz_is_document_reflowable(gctx, doc)) {
fz_layout_document(gctx, doc, 400, 600, 11);
}
return (struct Document *) doc;
}
FITZEXCEPTION(load_page, !result)
%pythonprepend load_page %{
"""Load a page.
'page_id' is either a 0-based page number or a tuple (chapter, pno),
with chapter number and page number within that chapter.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if page_id is None:
page_id = 0
if page_id not in self:
raise ValueError("page not in document")
if type(page_id) is int and page_id < 0:
np = self.page_count
while page_id < 0:
page_id += np
%}
%pythonappend load_page %{
val.thisown = True
val.parent = weakref.proxy(self)
self._page_refs[id(val)] = val
val._annot_refs = weakref.WeakValueDictionary()
val.number = page_id
%}
struct Page *
load_page(PyObject *page_id)
{
fz_page *page = NULL;
fz_document *doc = (fz_document *) $self;
int pno = 0, chapter = 0;
fz_try(gctx) {
if (PySequence_Check(page_id)) {
if (JM_INT_ITEM(page_id, 0, &chapter) == 1) {
RAISEPY(gctx, MSG_BAD_PAGEID, PyExc_ValueError);
}
if (JM_INT_ITEM(page_id, 1, &pno) == 1) {
RAISEPY(gctx, MSG_BAD_PAGEID, PyExc_ValueError);
}
page = fz_load_chapter_page(gctx, doc, chapter, pno);
} else {
pno = (int) PyLong_AsLong(page_id);
if (PyErr_Occurred()) {
RAISEPY(gctx, MSG_BAD_PAGEID, PyExc_ValueError);
}
page = fz_load_page(gctx, doc, pno);
}
}
fz_catch(gctx) {
PyErr_Clear();
return NULL;
}
PyErr_Clear();
return (struct Page *) page;
}
FITZEXCEPTION(_remove_links_to, !result)
PyObject *_remove_links_to(PyObject *numbers)
{
fz_try(gctx) {
pdf_document *pdf = pdf_specifics(gctx, (fz_document *) $self);
remove_dest_range(gctx, pdf, numbers);
}
fz_catch(gctx) {
return NULL;
}
Py_RETURN_NONE;
}
CLOSECHECK0(_loadOutline, """Load first outline.""")
struct Outline *_loadOutline()
{
fz_outline *ol = NULL;
fz_document *doc = (fz_document *) $self;
fz_try(gctx) {
ol = fz_load_outline(gctx, doc);
}
fz_catch(gctx) {
return NULL;
}
return (struct Outline *) ol;
}
void _dropOutline(struct Outline *ol) {
DEBUGMSG1("Outline");
fz_outline *this_ol = (fz_outline *) ol;
fz_drop_outline(gctx, this_ol);
DEBUGMSG2;
}
FITZEXCEPTION(_insert_font, !result)
CLOSECHECK0(_insert_font, """Utility: insert font from file or binary.""")
PyObject *
_insert_font(char *fontfile=NULL, PyObject *fontbuffer=NULL)
{
PyObject *value=NULL;
pdf_document *pdf = pdf_specifics(gctx, (fz_document *)$self);
fz_try(gctx) {
ASSERT_PDF(pdf);
if (!fontfile && !EXISTS(fontbuffer)) {
RAISEPY(gctx, MSG_FILE_OR_BUFFER, PyExc_ValueError);
}
value = JM_insert_font(gctx, pdf, NULL, fontfile, fontbuffer,
0, 0, 0, 0, 0, -1);
}
fz_catch(gctx) {
return NULL;
}
return value;
}
FITZEXCEPTION(get_outline_xrefs, !result)
CLOSECHECK0(get_outline_xrefs, """Get list of outline xref numbers.""")
PyObject *
get_outline_xrefs()
{
PyObject *xrefs = PyList_New(0);
pdf_document *pdf = pdf_specifics(gctx, (fz_document *)$self);
if (!pdf) {
return xrefs;
}
fz_try(gctx) {
pdf_obj *root = pdf_dict_get(gctx, pdf_trailer(gctx, pdf), PDF_NAME(Root));
if (!root) goto finished;
pdf_obj *olroot = pdf_dict_get(gctx, root, PDF_NAME(Outlines));
if (!olroot) goto finished;
pdf_obj *first = pdf_dict_get(gctx, olroot, PDF_NAME(First));
if (!first) goto finished;
xrefs = JM_outline_xrefs(gctx, first, xrefs);
finished:;
}
fz_catch(gctx) {
Py_DECREF(xrefs);
return NULL;
}
return xrefs;
}
FITZEXCEPTION(xref_get_keys, !result)
CLOSECHECK0(xref_get_keys, """Get the keys of PDF dict object at 'xref'. Use -1 for the PDF trailer.""")
PyObject *
xref_get_keys(int xref)
{
pdf_document *pdf = pdf_specifics(gctx, (fz_document *)$self);
pdf_obj *obj=NULL;
PyObject *rc = NULL;
int i, n;
fz_try(gctx) {
ASSERT_PDF(pdf);
int xreflen = pdf_xref_len(gctx, pdf);
if (!INRANGE(xref, 1, xreflen-1) && xref != -1) {
RAISEPY(gctx, MSG_BAD_XREF, PyExc_ValueError);
}
if (xref > 0) {
obj = pdf_load_object(gctx, pdf, xref);
} else {
obj = pdf_trailer(gctx, pdf);
}
n = pdf_dict_len(gctx, obj);
rc = PyTuple_New(n);
if (!n) goto finished;
for (i = 0; i < n; i++) {
const char *key = pdf_to_name(gctx, pdf_dict_get_key(gctx, obj, i));
PyTuple_SET_ITEM(rc, i, Py_BuildValue("s", key));
}
finished:;
}
fz_always(gctx) {
if (xref > 0) {
pdf_drop_obj(gctx, obj);
}
}
fz_catch(gctx) {
return NULL;
}
return rc;
}
FITZEXCEPTION(xref_get_key, !result)
CLOSECHECK0(xref_get_key, """Get PDF dict key value of object at 'xref'.""")
PyObject *
xref_get_key(int xref, const char *key)
{
pdf_document *pdf = pdf_specifics(gctx, (fz_document *)$self);
pdf_obj *obj=NULL, *subobj=NULL;
PyObject *rc = NULL;
fz_buffer *res = NULL;
PyObject *text = NULL;
fz_try(gctx) {
ASSERT_PDF(pdf);
int xreflen = pdf_xref_len(gctx, pdf);
if (!INRANGE(xref, 1, xreflen-1) && xref != -1) {
RAISEPY(gctx, MSG_BAD_XREF, PyExc_ValueError);
}
if (xref > 0) {
obj = pdf_load_object(gctx, pdf, xref);
} else {
obj = pdf_trailer(gctx, pdf);
}
if (!obj) {
goto not_found;
}
subobj = pdf_dict_getp(gctx, obj, key);
if (!subobj) {
goto not_found;
}
char *type;
if (pdf_is_indirect(gctx, subobj)) {
type = "xref";
text = PyUnicode_FromFormat("%i 0 R", pdf_to_num(gctx, subobj));
} else if (pdf_is_array(gctx, subobj)) {
type = "array";
} else if (pdf_is_dict(gctx, subobj)) {
type = "dict";
} else if (pdf_is_int(gctx, subobj)) {
type = "int";
text = PyUnicode_FromFormat("%i", pdf_to_int(gctx, subobj));
} else if (pdf_is_real(gctx, subobj)) {
type = "float";
} else if (pdf_is_null(gctx, subobj)) {
type = "null";
text = PyUnicode_FromString("null");
} else if (pdf_is_bool(gctx, subobj)) {
type = "bool";
if (pdf_to_bool(gctx, subobj)) {
text = PyUnicode_FromString("true");
} else {
text = PyUnicode_FromString("false");
}
} else if (pdf_is_name(gctx, subobj)) {
type = "name";
text = PyUnicode_FromFormat("/%s", pdf_to_name(gctx, subobj));
} else if (pdf_is_string(gctx, subobj)) {
type = "string";
text = JM_UnicodeFromStr(pdf_to_text_string(gctx, subobj));
} else {
type = "unknown";
}
if (!text) {
res = JM_object_to_buffer(gctx, subobj, 1, 0);
text = JM_UnicodeFromBuffer(gctx, res);
}
rc = Py_BuildValue("sO", type, text);
Py_DECREF(text);
goto finished;
not_found:;
rc = Py_BuildValue("ss", "null", "null");
finished:;
}
fz_always(gctx) {
if (xref > 0) {
pdf_drop_obj(gctx, obj);
}
fz_drop_buffer(gctx, res);
}
fz_catch(gctx) {
return NULL;
}
return rc;
}
FITZEXCEPTION(xref_set_key, !result)
%pythonprepend xref_set_key %{
"""Set the value of a PDF dictionary key."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not key or not isinstance(key, str) or INVALID_NAME_CHARS.intersection(key) not in (set(), {"/"}):
raise ValueError("bad 'key'")
if not isinstance(value, str) or not value or value[0] == "/" and INVALID_NAME_CHARS.intersection(value[1:]) != set():
raise ValueError("bad 'value'")
%}
PyObject *
xref_set_key(int xref, const char *key, char *value)
{
pdf_document *pdf = pdf_specifics(gctx, (fz_document *)$self);
pdf_obj *obj = NULL, *new_obj = NULL;
int i, n;
fz_try(gctx) {
ASSERT_PDF(pdf);
if (!key || strlen(key) == 0) {
RAISEPY(gctx, "bad 'key'", PyExc_ValueError);
}
if (!value || strlen(value) == 0) {
RAISEPY(gctx, "bad 'value'", PyExc_ValueError);
}
int xreflen = pdf_xref_len(gctx, pdf);
if (!INRANGE(xref, 1, xreflen-1) && xref != -1) {
RAISEPY(gctx, MSG_BAD_XREF, PyExc_ValueError);
}
if (xref != -1) {
obj = pdf_load_object(gctx, pdf, xref);
} else {
obj = pdf_trailer(gctx, pdf);
}
// if val=="null" and no path hierarchy, delete "key" from object
// chr(47) = "/"
if (strcmp(value, "null") == 0 && strchr(key, 47) == NULL) {
pdf_dict_dels(gctx, obj, key);
goto finished;
}
new_obj = JM_set_object_value(gctx, obj, key, value);
if (!new_obj) {
goto finished; // did not work: skip update
}
if (xref != -1) {
pdf_drop_obj(gctx, obj);
obj = NULL;
pdf_update_object(gctx, pdf, xref, new_obj);
} else {
n = pdf_dict_len(gctx, new_obj);
for (i = 0; i < n; i++) {
pdf_dict_put(gctx, obj, pdf_dict_get_key(gctx, new_obj, i), pdf_dict_get_val(gctx, new_obj, i));
}
}
finished:;
}
fz_always(gctx) {
if (xref != -1) {
pdf_drop_obj(gctx, obj);
}
pdf_drop_obj(gctx, new_obj);
PyErr_Clear();
}
fz_catch(gctx) {
return NULL;
}
Py_RETURN_NONE;
}
FITZEXCEPTION(_extend_toc_items, !result)
CLOSECHECK0(_extend_toc_items, """Add color info to all items of an extended TOC list.""")
PyObject *
_extend_toc_items(PyObject *items)
{
pdf_document *pdf = pdf_specifics(gctx, (fz_document *)$self);
pdf_obj *bm, *col, *obj;
int count, flags;
PyObject *item=NULL, *itemdict=NULL, *xrefs, *bold, *italic, *collapse, *zoom;
zoom = PyUnicode_FromString("zoom");
bold = PyUnicode_FromString("bold");
italic = PyUnicode_FromString("italic");
collapse = PyUnicode_FromString("collapse");
fz_try(gctx) {
pdf_obj *root = pdf_dict_get(gctx, pdf_trailer(gctx, pdf), PDF_NAME(Root));
if (!root) goto finished;
pdf_obj *olroot = pdf_dict_get(gctx, root, PDF_NAME(Outlines));
if (!olroot) goto finished;
pdf_obj *first = pdf_dict_get(gctx, olroot, PDF_NAME(First));
if (!first) goto finished;
xrefs = PyList_New(0); // pre-allocate an empty list
xrefs = JM_outline_xrefs(gctx, first, xrefs);
Py_ssize_t i, n = PySequence_Size(xrefs), m = PySequence_Size(items);
if (!n) goto finished;
if (n != m) {
RAISEPY(gctx, "internal error finding outline xrefs", PyExc_IndexError);
}
int xref;
// update all TOC item dictionaries
for (i = 0; i < n; i++) {
JM_INT_ITEM(xrefs, i, &xref);
item = PySequence_ITEM(items, i);
itemdict = PySequence_ITEM(item, 3);
if (!itemdict || !PyDict_Check(itemdict)) {
RAISEPY(gctx, "need non-simple TOC format", PyExc_ValueError);
}
PyDict_SetItem(itemdict, dictkey_xref, PySequence_ITEM(xrefs, i));
bm = pdf_load_object(gctx, pdf, xref);
flags = pdf_to_int(gctx, (pdf_dict_get(gctx, bm, PDF_NAME(F))));
if (flags == 1) {
PyDict_SetItem(itemdict, italic, Py_True);
} else if (flags == 2) {
PyDict_SetItem(itemdict, bold, Py_True);
} else if (flags == 3) {
PyDict_SetItem(itemdict, italic, Py_True);
PyDict_SetItem(itemdict, bold, Py_True);
}
count = pdf_to_int(gctx, (pdf_dict_get(gctx, bm, PDF_NAME(Count))));
if (count < 0) {
PyDict_SetItem(itemdict, collapse, Py_True);
} else if (count > 0) {
PyDict_SetItem(itemdict, collapse, Py_False);
}
col = pdf_dict_get(gctx, bm, PDF_NAME(C));
if (pdf_is_array(gctx, col) && pdf_array_len(gctx, col) == 3) {
PyObject *color = PyTuple_New(3);
PyTuple_SET_ITEM(color, 0, Py_BuildValue("f", pdf_to_real(gctx, pdf_array_get(gctx, col, 0))));
PyTuple_SET_ITEM(color, 1, Py_BuildValue("f", pdf_to_real(gctx, pdf_array_get(gctx, col, 1))));
PyTuple_SET_ITEM(color, 2, Py_BuildValue("f", pdf_to_real(gctx, pdf_array_get(gctx, col, 2))));
DICT_SETITEM_DROP(itemdict, dictkey_color, color);
}
float z=0;
obj = pdf_dict_get(gctx, bm, PDF_NAME(Dest));
if (!obj || !pdf_is_array(gctx, obj)) {
obj = pdf_dict_getl(gctx, bm, PDF_NAME(A), PDF_NAME(D), NULL);
}
if (pdf_is_array(gctx, obj) && pdf_array_len(gctx, obj) == 5) {
z = pdf_to_real(gctx, pdf_array_get(gctx, obj, 4));
}
DICT_SETITEM_DROP(itemdict, zoom, Py_BuildValue("f", z));
PyList_SetItem(item, 3, itemdict);
PyList_SetItem(items, i, item);
pdf_drop_obj(gctx, bm);
bm = NULL;
}
finished:;
}
fz_always(gctx) {
Py_CLEAR(xrefs);
Py_CLEAR(bold);
Py_CLEAR(italic);
Py_CLEAR(collapse);
Py_CLEAR(zoom);
pdf_drop_obj(gctx, bm);
PyErr_Clear();