-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathfitz_cgo.go
599 lines (453 loc) · 13 KB
/
fitz_cgo.go
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
//go:build cgo && !nocgo
package fitz
/*
#include <mupdf/fitz.h>
#include <stdlib.h>
const char *fz_version = FZ_VERSION;
#if defined(_WIN32)
typedef unsigned long long store;
#else
typedef unsigned long store;
#endif
fz_document *open_document(fz_context *ctx, const char *filename) {
fz_document *doc;
fz_try(ctx) {
doc = fz_open_document(ctx, filename);
}
fz_catch(ctx) {
return NULL;
}
return doc;
}
fz_document *open_document_with_stream(fz_context *ctx, const char *magic, fz_stream *stream) {
fz_document *doc;
fz_try(ctx) {
doc = fz_open_document_with_stream(ctx, magic, stream);
}
fz_catch(ctx) {
return NULL;
}
return doc;
}
fz_page *load_page(fz_context *ctx, fz_document *doc, int number) {
fz_page *page;
fz_try(ctx) {
page = fz_load_page(ctx, doc, number);
}
fz_catch(ctx) {
return NULL;
}
return page;
}
int run_page_contents(fz_context *ctx, fz_page *page, fz_device *dev, fz_matrix transform, fz_cookie *cookie) {
fz_try(ctx) {
fz_run_page_contents(ctx, page, dev, transform, cookie);
}
fz_catch(ctx) {
return 0;
}
return 1;
}
*/
import "C"
import (
"image"
"io"
"os"
"path/filepath"
"sync"
"unsafe"
)
// Document represents fitz document.
type Document struct {
ctx *C.struct_fz_context
data []byte // binds data to the Document lifecycle avoiding premature GC
doc *C.struct_fz_document
mtx sync.Mutex
stream *C.fz_stream
}
// New returns new fitz document.
func New(filename string) (f *Document, err error) {
f = &Document{}
filename, err = filepath.Abs(filename)
if err != nil {
return
}
if _, e := os.Stat(filename); e != nil {
err = ErrNoSuchFile
return
}
f.ctx = (*C.struct_fz_context)(unsafe.Pointer(C.fz_new_context_imp(nil, nil, C.store(MaxStore), C.fz_version)))
if f.ctx == nil {
err = ErrCreateContext
return
}
C.fz_register_document_handlers(f.ctx)
cfilename := C.CString(filename)
defer C.free(unsafe.Pointer(cfilename))
f.doc = C.open_document(f.ctx, cfilename)
if f.doc == nil {
err = ErrOpenDocument
return
}
ret := C.fz_needs_password(f.ctx, f.doc)
v := int(ret) != 0
if v {
err = ErrNeedsPassword
}
return
}
// NewFromMemory returns new fitz document from byte slice.
func NewFromMemory(b []byte) (f *Document, err error) {
if len(b) == 0 {
return nil, ErrEmptyBytes
}
f = &Document{}
f.ctx = (*C.struct_fz_context)(unsafe.Pointer(C.fz_new_context_imp(nil, nil, C.store(MaxStore), C.fz_version)))
if f.ctx == nil {
err = ErrCreateContext
return
}
C.fz_register_document_handlers(f.ctx)
f.stream = C.fz_open_memory(f.ctx, (*C.uchar)(&b[0]), C.size_t(len(b)))
if f.stream == nil {
err = ErrOpenMemory
return
}
magic := contentType(b)
if magic == "" {
err = ErrOpenMemory
return
}
f.data = b
cmagic := C.CString(magic)
defer C.free(unsafe.Pointer(cmagic))
f.doc = C.open_document_with_stream(f.ctx, cmagic, f.stream)
if f.doc == nil {
err = ErrOpenDocument
}
ret := C.fz_needs_password(f.ctx, f.doc)
v := int(ret) != 0
if v {
err = ErrNeedsPassword
}
return
}
// NewFromReader returns new fitz document from io.Reader.
func NewFromReader(r io.Reader) (f *Document, err error) {
b, e := io.ReadAll(r)
if e != nil {
err = e
return
}
f, err = NewFromMemory(b)
return
}
// NumPage returns total number of pages in document.
func (f *Document) NumPage() int {
return int(C.fz_count_pages(f.ctx, f.doc))
}
// Image returns image for given page number.
func (f *Document) Image(pageNumber int) (*image.RGBA, error) {
return f.ImageDPI(pageNumber, 300.0)
}
// ImageDPI returns image for given page number and DPI.
func (f *Document) ImageDPI(pageNumber int, dpi float64) (*image.RGBA, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return nil, ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return nil, ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
var bounds C.fz_rect
bounds = C.fz_bound_page(f.ctx, page)
var ctm C.fz_matrix
ctm = C.fz_scale(C.float(dpi/72), C.float(dpi/72))
var bbox C.fz_irect
bounds = C.fz_transform_rect(bounds, ctm)
bbox = C.fz_round_rect(bounds)
pixmap := C.fz_new_pixmap_with_bbox(f.ctx, C.fz_device_rgb(f.ctx), bbox, nil, 1)
if pixmap == nil {
return nil, ErrCreatePixmap
}
C.fz_clear_pixmap_with_value(f.ctx, pixmap, C.int(0xff))
defer C.fz_drop_pixmap(f.ctx, pixmap)
device := C.fz_new_draw_device(f.ctx, ctm, pixmap)
C.fz_enable_device_hints(f.ctx, device, C.FZ_NO_CACHE)
defer C.fz_drop_device(f.ctx, device)
drawMatrix := C.fz_identity
ret := C.run_page_contents(f.ctx, page, device, drawMatrix, nil)
if ret == 0 {
return nil, ErrRunPageContents
}
C.fz_close_device(f.ctx, device)
pixels := C.fz_pixmap_samples(f.ctx, pixmap)
if pixels == nil {
return nil, ErrPixmapSamples
}
img := image.NewRGBA(image.Rect(int(bbox.x0), int(bbox.y0), int(bbox.x1), int(bbox.y1)))
copy(img.Pix, C.GoBytes(unsafe.Pointer(pixels), C.int(4*bbox.x1*bbox.y1)))
return img, nil
}
// ImagePNG returns image for given page number as PNG bytes.
func (f *Document) ImagePNG(pageNumber int, dpi float64) ([]byte, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return nil, ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return nil, ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
var bounds C.fz_rect
bounds = C.fz_bound_page(f.ctx, page)
var ctm C.fz_matrix
ctm = C.fz_scale(C.float(dpi/72), C.float(dpi/72))
var bbox C.fz_irect
bounds = C.fz_transform_rect(bounds, ctm)
bbox = C.fz_round_rect(bounds)
pixmap := C.fz_new_pixmap_with_bbox(f.ctx, C.fz_device_rgb(f.ctx), bbox, nil, 1)
if pixmap == nil {
return nil, ErrCreatePixmap
}
C.fz_clear_pixmap_with_value(f.ctx, pixmap, C.int(0xff))
defer C.fz_drop_pixmap(f.ctx, pixmap)
device := C.fz_new_draw_device(f.ctx, ctm, pixmap)
C.fz_enable_device_hints(f.ctx, device, C.FZ_NO_CACHE)
defer C.fz_drop_device(f.ctx, device)
drawMatrix := C.fz_identity
ret := C.run_page_contents(f.ctx, page, device, drawMatrix, nil)
if ret == 0 {
return nil, ErrRunPageContents
}
C.fz_close_device(f.ctx, device)
buf := C.fz_new_buffer_from_pixmap_as_png(f.ctx, pixmap, C.fz_default_color_params)
defer C.fz_drop_buffer(f.ctx, buf)
size := C.fz_buffer_storage(f.ctx, buf, nil)
str := C.GoStringN(C.fz_string_from_buffer(f.ctx, buf), C.int(size))
return []byte(str), nil
}
// Links returns slice of links for given page number.
func (f *Document) Links(pageNumber int) ([]Link, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return nil, ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return nil, ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
links := C.fz_load_links(f.ctx, page)
defer C.fz_drop_link(f.ctx, links)
linkCount := 0
for currLink := links; currLink != nil; currLink = currLink.next {
linkCount++
}
if linkCount == 0 {
return nil, nil
}
gLinks := make([]Link, linkCount)
currLink := links
for i := 0; i < linkCount; i++ {
gLinks[i] = Link{
URI: C.GoString(currLink.uri),
}
currLink = currLink.next
}
return gLinks, nil
}
// Text returns text for given page number.
func (f *Document) Text(pageNumber int) (string, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return "", ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return "", ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
var bounds C.fz_rect
bounds = C.fz_bound_page(f.ctx, page)
var ctm C.fz_matrix
ctm = C.fz_scale(C.float(72.0/72), C.float(72.0/72))
text := C.fz_new_stext_page(f.ctx, bounds)
defer C.fz_drop_stext_page(f.ctx, text)
var opts C.fz_stext_options
opts.flags = 0
device := C.fz_new_stext_device(f.ctx, text, &opts)
C.fz_enable_device_hints(f.ctx, device, C.FZ_NO_CACHE)
defer C.fz_drop_device(f.ctx, device)
var cookie C.fz_cookie
ret := C.run_page_contents(f.ctx, page, device, ctm, &cookie)
if ret == 0 {
return "", ErrRunPageContents
}
C.fz_close_device(f.ctx, device)
buf := C.fz_new_buffer_from_stext_page(f.ctx, text)
defer C.fz_drop_buffer(f.ctx, buf)
str := C.GoString(C.fz_string_from_buffer(f.ctx, buf))
return str, nil
}
// HTML returns html for given page number.
func (f *Document) HTML(pageNumber int, header bool) (string, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return "", ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return "", ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
var bounds C.fz_rect
bounds = C.fz_bound_page(f.ctx, page)
var ctm C.fz_matrix
ctm = C.fz_scale(C.float(72.0/72), C.float(72.0/72))
text := C.fz_new_stext_page(f.ctx, bounds)
defer C.fz_drop_stext_page(f.ctx, text)
var opts C.fz_stext_options
opts.flags = C.FZ_STEXT_PRESERVE_IMAGES
device := C.fz_new_stext_device(f.ctx, text, &opts)
C.fz_enable_device_hints(f.ctx, device, C.FZ_NO_CACHE)
defer C.fz_drop_device(f.ctx, device)
var cookie C.fz_cookie
ret := C.run_page_contents(f.ctx, page, device, ctm, &cookie)
if ret == 0 {
return "", ErrRunPageContents
}
C.fz_close_device(f.ctx, device)
buf := C.fz_new_buffer(f.ctx, 1024)
defer C.fz_drop_buffer(f.ctx, buf)
out := C.fz_new_output_with_buffer(f.ctx, buf)
defer C.fz_drop_output(f.ctx, out)
if header {
C.fz_print_stext_header_as_html(f.ctx, out)
}
C.fz_print_stext_page_as_html(f.ctx, out, text, C.int(pageNumber))
if header {
C.fz_print_stext_trailer_as_html(f.ctx, out)
}
C.fz_close_output(f.ctx, out)
str := C.GoString(C.fz_string_from_buffer(f.ctx, buf))
return str, nil
}
// SVG returns svg document for given page number.
func (f *Document) SVG(pageNumber int) (string, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return "", ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return "", ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
var bounds C.fz_rect
bounds = C.fz_bound_page(f.ctx, page)
var ctm C.fz_matrix
ctm = C.fz_scale(C.float(72.0/72), C.float(72.0/72))
bounds = C.fz_transform_rect(bounds, ctm)
buf := C.fz_new_buffer(f.ctx, 1024)
defer C.fz_drop_buffer(f.ctx, buf)
out := C.fz_new_output_with_buffer(f.ctx, buf)
defer C.fz_drop_output(f.ctx, out)
device := C.fz_new_svg_device(f.ctx, out, bounds.x1-bounds.x0, bounds.y1-bounds.y0, C.FZ_SVG_TEXT_AS_PATH, 1)
C.fz_enable_device_hints(f.ctx, device, C.FZ_NO_CACHE)
defer C.fz_drop_device(f.ctx, device)
var cookie C.fz_cookie
ret := C.run_page_contents(f.ctx, page, device, ctm, &cookie)
if ret == 0 {
return "", ErrRunPageContents
}
C.fz_close_device(f.ctx, device)
C.fz_close_output(f.ctx, out)
str := C.GoString(C.fz_string_from_buffer(f.ctx, buf))
return str, nil
}
// ToC returns the table of contents (also known as outline).
func (f *Document) ToC() ([]Outline, error) {
data := make([]Outline, 0)
outline := C.fz_load_outline(f.ctx, f.doc)
if outline == nil {
return nil, ErrLoadOutline
}
defer C.fz_drop_outline(f.ctx, outline)
var walk func(outline *C.fz_outline, level int)
walk = func(outline *C.fz_outline, level int) {
for outline != nil {
res := Outline{}
res.Level = level
res.Title = C.GoString(outline.title)
res.URI = C.GoString(outline.uri)
res.Page = int(outline.page.page)
res.Top = float64(outline.y)
data = append(data, res)
if outline.down != nil {
walk(outline.down, level+1)
}
outline = outline.next
}
}
walk(outline, 1)
return data, nil
}
// Metadata returns the map with standard metadata.
func (f *Document) Metadata() map[string]string {
data := make(map[string]string)
lookup := func(key string) string {
ckey := C.CString(key)
defer C.free(unsafe.Pointer(ckey))
buf := make([]byte, 256)
C.fz_lookup_metadata(f.ctx, f.doc, ckey, (*C.char)(unsafe.Pointer(&buf[0])), C.int(len(buf)))
return string(buf)
}
data["format"] = lookup("format")
data["encryption"] = lookup("encryption")
data["title"] = lookup("info:Title")
data["author"] = lookup("info:Author")
data["subject"] = lookup("info:Subject")
data["keywords"] = lookup("info:Keywords")
data["creator"] = lookup("info:Creator")
data["producer"] = lookup("info:Producer")
data["creationDate"] = lookup("info:CreationDate")
data["modDate"] = lookup("info:modDate")
return data
}
// Bound gives the Bounds of a given Page in the document.
func (f *Document) Bound(pageNumber int) (image.Rectangle, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
if pageNumber >= f.NumPage() {
return image.Rectangle{}, ErrPageMissing
}
page := C.load_page(f.ctx, f.doc, C.int(pageNumber))
if page == nil {
return image.Rectangle{}, ErrLoadPage
}
defer C.fz_drop_page(f.ctx, page)
var bounds C.fz_rect
bounds = C.fz_bound_page(f.ctx, page)
return image.Rect(int(bounds.x0), int(bounds.y0), int(bounds.x1), int(bounds.y1)), nil
}
// Close closes the underlying fitz document.
func (f *Document) Close() error {
if f.stream != nil {
C.fz_drop_stream(f.ctx, f.stream)
}
C.fz_drop_document(f.ctx, f.doc)
C.fz_drop_context(f.ctx)
f.data = nil
return nil
}