forked from gen2brain/go-fitz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fitz.go
92 lines (73 loc) · 2.04 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
package fitz
// #include <mupdf/fitz.h>
// #cgo LDFLAGS: -lmupdf -lmupdfthird
// const char *fz_version = FZ_VERSION;
import "C"
import (
"errors"
"image"
"os"
"path/filepath"
"unsafe"
)
// Fitz document
type Document struct {
ctx *C.struct_fz_context_s
doc *C.struct_fz_document_s
}
// NewDocument returns new fitz document
func NewDocument(filename string) (f *Document, err error) {
f = &Document{}
filename, err = filepath.Abs(filename)
if err != nil {
return
}
if _, e := os.Stat(filename); os.IsNotExist(e) {
err = errors.New("fitz: no such file")
return
}
f.ctx = (*C.struct_fz_context_s)(unsafe.Pointer(
C.fz_new_context_imp(nil, nil, C.FZ_STORE_UNLIMITED, C.fz_version)))
if f.ctx == nil {
err = errors.New("fitz: cannot create context")
return
}
C.fz_register_document_handlers(f.ctx)
f.doc = C.fz_open_document(f.ctx, C.CString(filename))
if f.doc == nil {
err = errors.New("fitz: cannot open document")
return
}
return
}
// Pages returns total number of pages in document
func (f *Document) Pages() int {
return int(C.fz_count_pages(f.ctx, f.doc))
}
// Image returns image for given page number
func (f *Document) Image(page int) (image.Image, error) {
var ctm C.fz_matrix
C.fz_scale(&ctm, C.float(4.0), C.float(4.0))
cs := C.fz_device_rgb(f.ctx)
defer C.fz_drop_colorspace(f.ctx, cs)
pixmap := C.fz_new_pixmap_from_page_number(f.ctx, f.doc, C.int(page), &ctm, cs)
if pixmap == nil {
return nil, errors.New("fitz: cannot create pixmap")
}
defer C.fz_drop_pixmap(f.ctx, pixmap)
var bbox C.fz_irect
C.fz_pixmap_bbox(f.ctx, pixmap, &bbox)
pixels := C.fz_pixmap_samples(f.ctx, pixmap)
if pixels == nil {
return nil, errors.New("fitz: cannot get pixmap samples")
}
rect := image.Rect(int(bbox.x0), int(bbox.y0), int(bbox.x1), int(bbox.y1))
bytes := C.GoBytes(unsafe.Pointer(pixels), 4*bbox.x1*bbox.y1)
img := &image.RGBA{bytes, 4 * rect.Max.X, rect}
return img, nil
}
// Close closes the underlying fitz document
func (f *Document) Close() {
C.fz_drop_document(f.ctx, f.doc)
C.fz_drop_context(f.ctx)
}