backport to mupdf-0.7
[fbpdf.git] / mupdf.c
blob71cdc73908e7a823e4b7406469f5238da57de02f
1 #include <stdlib.h>
2 #include <string.h>
3 #include "fitz.h"
4 #include "mupdf.h"
5 #include "draw.h"
6 #include "doc.h"
8 #define MIN_(a, b) ((a) < (b) ? (a) : (b))
10 struct doc {
11 fz_glyphcache *glyphcache;
12 pdf_xref *xref;
15 int doc_draw(struct doc *doc, int p, int zoom, int rotate,
16 fbval_t *bitmap, int *rows, int *cols)
18 fz_matrix ctm;
19 fz_bbox bbox;
20 fz_pixmap *pix;
21 fz_device *dev;
22 fz_obj *pageobj;
23 fz_displaylist *list;
24 pdf_page *page;
25 int h, w;
26 int x, y;
28 pageobj = pdf_getpageobject(doc->xref, p);
29 if (pdf_loadpage(&page, doc->xref, pageobj))
30 return 1;
31 list = fz_newdisplaylist();
32 dev = fz_newlistdevice(list);
33 if (pdf_runpage(doc->xref, page, dev, fz_identity))
34 return 1;
35 fz_freedevice(dev);
37 ctm = fz_translate(0, -page->mediabox.y1);
38 ctm = fz_concat(ctm, fz_scale((float) zoom / 10, (float) -zoom / 10));
39 if (rotate)
40 ctm = fz_concat(ctm, fz_rotate(rotate));
41 bbox = fz_roundrect(fz_transformrect(ctm, page->mediabox));
43 pix = fz_newpixmapwithrect(fz_devicergb, bbox);
44 fz_clearpixmap(pix, 0xff);
46 dev = fz_newdrawdevice(doc->glyphcache, pix);
47 fz_executedisplaylist(list, dev, ctm);
48 fz_freedevice(dev);
50 w = MIN_(pix->w, *cols);
51 h = MIN_(pix->h, *rows);
53 for (y = 0; y < h; y++) {
54 int xs = y * *cols + (*cols - w) / 2;
55 for (x = 0; x < w; x++) {
56 unsigned char *s = pix->samples + y * pix->w * 4 + x * 4;
57 bitmap[xs + x] = FB_VAL(s[0], s[1], s[2]);
60 fz_droppixmap(pix);
61 fz_freedisplaylist(list);
62 pdf_freepage(page);
63 pdf_agestore(doc->xref->store, 3);
64 *cols = w;
65 *rows = h;
66 return 0;
69 int doc_pages(struct doc *doc)
71 return pdf_getpagecount(doc->xref);
74 struct doc *doc_open(char *path)
76 struct doc *doc = malloc(sizeof(*doc));
77 fz_accelerate();
78 doc->glyphcache = fz_newglyphcache();
79 if (pdf_openxref(&doc->xref, path, NULL)) {
80 free(doc);
81 return NULL;
83 if (pdf_loadpagetree(doc->xref)) {
84 free(doc);
85 return NULL;
87 return doc;
90 void doc_close(struct doc *doc)
92 pdf_freexref(doc->xref);
93 fz_freeglyphcache(doc->glyphcache);
94 free(doc);