forked from gen2brain/go-fitz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fitz.go
484 lines (367 loc) · 11.3 KB
/
fitz.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
//go:build !compat
// +build !compat
// Package fitz provides wrapper for the [MuPDF](http://mupdf.com/) fitz library
// that can extract pages from PDF and EPUB documents as images, text, html or svg.
package fitz
/*
#include <mupdf/fitz.h>
#include <stdlib.h>
const char *fz_version = FZ_VERSION;
*/
import "C"
import (
"errors"
"image"
"io"
"io/ioutil"
"os"
"path/filepath"
"sync"
"unsafe"
)
// Errors.
var (
ErrNoSuchFile = errors.New("fitz: no such file")
ErrCreateContext = errors.New("fitz: cannot create context")
ErrOpenDocument = errors.New("fitz: cannot open document")
ErrOpenMemory = errors.New("fitz: cannot open memory")
ErrPageMissing = errors.New("fitz: page missing")
ErrCreatePixmap = errors.New("fitz: cannot create pixmap")
ErrPixmapSamples = errors.New("fitz: cannot get pixmap samples")
ErrNeedsPassword = errors.New("fitz: document needs password")
ErrLoadOutline = errors.New("fitz: cannot load outline")
)
// Document represents fitz document.
type Document struct {
ctx *C.struct_fz_context
doc *C.struct_fz_document
mtx sync.Mutex
stream *C.fz_stream
}
// Outline type.
type Outline struct {
// Hierarchy level of the entry (starting from 1).
Level int
// Title of outline item.
Title string
// Destination in the document to be displayed when this outline item is activated.
URI string
// The page number of an internal link.
Page int
// Top.
Top float64
}
// 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
}
b, e := ioutil.ReadFile(filename)
if e != nil {
err = ErrOpenDocument
return
}
magic := contentType(b)
if magic == "" {
err = ErrOpenDocument
return
}
f.ctx = (*C.struct_fz_context)(unsafe.Pointer(C.fz_new_context_imp(nil, nil, C.FZ_STORE_UNLIMITED, 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.fz_open_document(f.ctx, cfilename)
if f.doc == nil {
err = ErrOpenDocument
return
}
ret := C.fz_needs_password(f.ctx, f.doc)
v := bool(int(ret) != 0)
if v {
err = ErrNeedsPassword
}
return
}
// NewFromMemory returns new fitz document from byte slice.
func NewFromMemory(b []byte) (f *Document, err error) {
f = &Document{}
f.ctx = (*C.struct_fz_context)(unsafe.Pointer(C.fz_new_context_imp(nil, nil, C.FZ_STORE_UNLIMITED, C.fz_version)))
if f.ctx == nil {
err = ErrCreateContext
return
}
C.fz_register_document_handlers(f.ctx)
stream := C.fz_open_memory(f.ctx, (*C.uchar)(&b[0]), C.size_t(len(b)))
f.stream = C.fz_keep_stream(f.ctx, stream)
if f.stream == nil {
err = ErrOpenMemory
return
}
magic := contentType(b)
if magic == "" {
err = ErrOpenMemory
return
}
cmagic := C.CString(magic)
defer C.free(unsafe.Pointer(cmagic))
f.doc = C.fz_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 := bool(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 := ioutil.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.Image, 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.Image, error) {
f.mtx.Lock()
defer f.mtx.Unlock()
img := image.RGBA{}
if pageNumber >= f.NumPage() {
return nil, ErrPageMissing
}
page := C.fz_load_page(f.ctx, f.doc, C.int(pageNumber))
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
C.fz_run_page(f.ctx, page, device, drawMatrix, nil)
C.fz_close_device(f.ctx, device)
pixels := C.fz_pixmap_samples(f.ctx, pixmap)
if pixels == nil {
return nil, ErrPixmapSamples
}
img.Pix = C.GoBytes(unsafe.Pointer(pixels), C.int(4*bbox.x1*bbox.y1))
img.Rect = image.Rect(int(bbox.x0), int(bbox.y0), int(bbox.x1), int(bbox.y1))
img.Stride = 4 * img.Rect.Max.X
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.fz_load_page(f.ctx, f.doc, C.int(pageNumber))
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
C.fz_run_page(f.ctx, page, device, drawMatrix, nil)
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
}
// 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.fz_load_page(f.ctx, f.doc, C.int(pageNumber))
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
C.fz_run_page(f.ctx, page, device, ctm, &cookie)
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.fz_load_page(f.ctx, f.doc, C.int(pageNumber))
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
C.fz_run_page(f.ctx, page, device, ctm, &cookie)
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)
}
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.fz_load_page(f.ctx, f.doc, C.int(pageNumber))
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
C.fz_run_page(f.ctx, page, device, ctm, &cookie)
C.fz_close_device(f.ctx, device)
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)
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
}
// 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)
return nil
}