2 * This program is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU General Public
4 * License as published by the Free Software Foundation; either
5 * version 2 of the License, or (at your option) any later version.
7 * This software is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #define PANGO_ENABLE_BACKEND /* to access PangoFcFont.font_pattern */
23 #include <libgnomecanvas/libgnomecanvas.h>
27 #include <pango/pango.h>
28 #include <pango/pangofc-font.h>
29 #include <pango/pangoft2.h>
30 #include <fontconfig/fontconfig.h>
32 #include FT_FREETYPE_H
37 #include "ttsubset/sft.h"
40 #include "xo-support.h"
46 #define RGBA_RED(rgba) (((rgba>>24)&0xff)/255.0)
47 #define RGBA_GREEN(rgba) (((rgba>>16)&0xff)/255.0)
48 #define RGBA_BLUE(rgba) (((rgba>>8)&0xff)/255.0)
49 #define RGBA_ALPHA(rgba) (((rgba>>0)&0xff)/255.0)
50 #define RGBA_RGB(rgba) RGBA_RED(rgba), RGBA_GREEN(rgba), RGBA_BLUE(rgba)
52 /*********** Printing to PDF ************/
54 gboolean ispdfspace(char c)
56 return (c==0 || c==9 || c==10 || c==12 || c==13 || c==' ');
59 gboolean ispdfdelim(char c)
61 return (c=='(' || c==')' || c=='<' || c=='>' || c=='[' || c==']' ||
62 c=='{' || c=='}' || c=='/' || c=='%');
65 void skipspace(char **p, char *eof)
67 while (ispdfspace(**p) || **p=='%') {
68 if (**p=='%') while (*p!=eof && **p!=10 && **p!=13) (*p)++;
74 void free_pdfobj(struct PdfObj *obj)
78 if (obj==NULL) return;
79 if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
80 obj->type == PDFTYPE_STREAM) && obj->str!=NULL)
82 if ((obj->type == PDFTYPE_ARRAY || obj->type == PDFTYPE_DICT ||
83 obj->type == PDFTYPE_STREAM) && obj->num>0) {
84 for (i=0; i<obj->num; i++)
85 free_pdfobj(obj->elts[i]);
88 if ((obj->type == PDFTYPE_DICT || obj->type == PDFTYPE_STREAM) && obj->num>0) {
89 for (i=0; i<obj->num; i++)
90 g_free(obj->names[i]);
96 struct PdfObj *dup_pdfobj(struct PdfObj *obj)
101 if (obj==NULL) return NULL;
102 dup = g_memdup(obj, sizeof(struct PdfObj));
103 if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
104 obj->type == PDFTYPE_STREAM) && obj->str!=NULL) {
105 if (obj->type == PDFTYPE_NAME) obj->len = strlen(obj->str);
106 dup->str = g_memdup(obj->str, obj->len+1);
108 if ((obj->type == PDFTYPE_ARRAY || obj->type == PDFTYPE_DICT ||
109 obj->type == PDFTYPE_STREAM) && obj->num>0) {
110 dup->elts = g_malloc(obj->num*sizeof(struct PdfObj *));
111 for (i=0; i<obj->num; i++)
112 dup->elts[i] = dup_pdfobj(obj->elts[i]);
114 if ((obj->type == PDFTYPE_DICT || obj->type == PDFTYPE_STREAM) && obj->num>0) {
115 dup->names = g_malloc(obj->num*sizeof(char *));
116 for (i=0; i<obj->num; i++)
117 dup->names[i] = g_strdup(obj->names[i]);
122 void show_pdfobj(struct PdfObj *obj, GString *str)
125 if (obj==NULL) return;
128 if (obj->intval==1) g_string_append(str, "true");
129 if (obj->intval==0) g_string_append(str, "false");
130 if (obj->intval==-1) g_string_append(str, "null");
133 g_string_append_printf(str, "%d", obj->intval);
136 g_string_append_printf(str, "%f", obj->realval);
139 g_string_append_len(str, obj->str, obj->len);
142 g_string_append(str, obj->str);
145 g_string_append_c(str, '[');
146 for (i=0;i<obj->num;i++) {
147 if (i) g_string_append_c(str, ' ');
148 show_pdfobj(obj->elts[i], str);
150 g_string_append_c(str, ']');
153 g_string_append(str, "<<");
154 for (i=0;i<obj->num;i++) {
155 g_string_append_printf(str, " %s ", obj->names[i]);
156 show_pdfobj(obj->elts[i], str);
158 g_string_append(str, " >>");
161 g_string_append_printf(str, "%d %d R", obj->intval, obj->num);
166 void DEBUG_PRINTOBJ(struct PdfObj *obj)
168 GString *s = g_string_new("");
171 g_string_free(s, TRUE);
174 // parse a PDF object; returns NULL if fails
175 // THIS PARSER DOES NOT RECOGNIZE STREAMS YET
177 struct PdfObj *parse_pdf_object(char **ptr, char *eof)
179 struct PdfObj *obj, *elt;
180 char *p, *q, *r, *eltname;
183 obj = g_malloc(sizeof(struct PdfObj));
186 if (p==eof) { g_free(obj); return NULL; }
189 if (!strncmp(p, "true", 4)) {
190 obj->type = PDFTYPE_CST;
195 if (!strncmp(p, "false", 5)) {
196 obj->type = PDFTYPE_CST;
201 if (!strncmp(p, "null", 4)) {
202 obj->type = PDFTYPE_CST;
209 obj->intval = strtol(p, &q, 10);
213 obj->type = PDFTYPE_REAL;
214 obj->realval = g_ascii_strtod(p, ptr);
217 if (ispdfspace(*q)) {
218 // check for indirect reference
220 obj->num = strtol(q, &r, 10);
225 obj->type = PDFTYPE_REF;
230 obj->type = PDFTYPE_INT;
237 while (stack>0 && q!=eof) {
238 if (*q=='(') stack++;
239 if (*q==')') stack--;
243 if (q==eof) { g_free(obj); return NULL; }
244 obj->type = PDFTYPE_STRING;
246 obj->str = g_malloc(obj->len+1);
247 obj->str[obj->len] = 0;
248 g_memmove(obj->str, p, obj->len);
252 if (*p=='<' && p[1]!='<') {
254 while (*q!='>' && q!=eof) q++;
255 if (q==eof) { g_free(obj); return NULL; }
257 obj->type = PDFTYPE_STRING;
259 obj->str = g_malloc(obj->len+1);
260 obj->str[obj->len] = 0;
261 g_memmove(obj->str, p, obj->len);
269 while (!ispdfspace(*q) && !ispdfdelim(*q)) q++;
270 obj->type = PDFTYPE_NAME;
271 obj->str = g_strndup(p, q-p);
278 obj->type = PDFTYPE_ARRAY;
281 q=p+1; skipspace(&q, eof);
283 elt = parse_pdf_object(&q, eof);
284 if (elt==NULL) { free_pdfobj(obj); return NULL; }
286 obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
287 obj->elts[obj->num-1] = elt;
295 if (*p=='<' && p[1]=='<') {
296 obj->type = PDFTYPE_DICT;
300 q=p+2; skipspace(&q, eof);
301 while (*q!='>' || q[1]!='>') {
302 if (*q!='/') { free_pdfobj(obj); return NULL; }
304 while (!ispdfspace(*r) && !ispdfdelim(*r)) r++;
305 eltname = g_strndup(q, r-q);
306 q=r; skipspace(&q, eof);
307 elt = parse_pdf_object(&q, eof);
308 if (elt==NULL) { g_free(eltname); free_pdfobj(obj); return NULL; }
310 obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
311 obj->names = g_realloc(obj->names, obj->num*sizeof(char *));
312 obj->elts[obj->num-1] = elt;
313 obj->names[obj->num-1] = eltname;
320 // DOES NOT RECOGNIZE STREAMS YET (handle as subcase of dictionary)
326 struct PdfObj *get_dict_entry(struct PdfObj *dict, char *name)
330 if (dict==NULL) return NULL;
331 if (dict->type != PDFTYPE_DICT) return NULL;
332 for (i=0; i<dict->num; i++)
333 if (!strcmp(dict->names[i], name)) return dict->elts[i];
337 struct PdfObj *get_pdfobj(GString *pdfbuf, struct XrefTable *xref, struct PdfObj *obj)
342 if (obj==NULL) return NULL;
343 if (obj->type!=PDFTYPE_REF) return dup_pdfobj(obj);
344 if (obj->intval>xref->last) return NULL;
345 offs = xref->data[obj->intval];
346 if (offs<=0 || offs >= pdfbuf->len) return NULL;
348 p = pdfbuf->str + offs;
349 eof = pdfbuf->str + pdfbuf->len;
350 n = strtol(p, &p, 10);
351 if (n!=obj->intval) return NULL;
353 n = strtol(p, &p, 10);
355 if (strncmp(p, "obj", 3)) return NULL;
357 return parse_pdf_object(&p, eof);
360 // read the xref table of a PDF file in memory, and return the trailerdict
362 struct PdfObj *parse_xref_table(GString *pdfbuf, struct XrefTable *xref, int offs)
365 struct PdfObj *trailerdict, *obj;
368 if (strncmp(pdfbuf->str+offs, "xref", 4)) return NULL;
369 p = strstr(pdfbuf->str+offs, "trailer");
370 eof = pdfbuf->str + pdfbuf->len;
371 if (p==NULL) return NULL;
373 trailerdict = parse_pdf_object(&p, eof);
374 obj = get_dict_entry(trailerdict, "/Size");
375 if (obj!=NULL && obj->type == PDFTYPE_INT && obj->intval-1>xref->last)
376 make_xref(xref, obj->intval-1, 0);
377 obj = get_dict_entry(trailerdict, "/Prev");
378 if (obj!=NULL && obj->type == PDFTYPE_INT && obj->intval>0 && obj->intval!=offs) {
379 // recurse into older xref table
380 obj = parse_xref_table(pdfbuf, xref, obj->intval);
383 p = pdfbuf->str+offs+4;
385 if (*p<'0' || *p>'9') { free_pdfobj(trailerdict); return NULL; }
386 while (*p>='0' && *p<='9') {
387 start = strtol(p, &p, 10);
389 len = strtol(p, &p, 10);
391 if (len <= 0 || 20*len > eof-p) break;
392 if (start+len-1 > xref->last) make_xref(xref, start+len-1, 0);
393 for (i=start; i<start+len; i++) {
394 xref->data[i] = strtol(p, NULL, 10);
399 if (*p!='t') { free_pdfobj(trailerdict); return NULL; }
403 // parse the page tree
405 int pdf_getpageinfo(GString *pdfbuf, struct XrefTable *xref,
406 struct PdfObj *pgtree, int nmax, struct PdfPageDesc *pages)
408 struct PdfObj *obj, *kid;
411 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Type"));
412 if (obj == NULL || obj->type != PDFTYPE_NAME)
414 if (!strcmp(obj->str, "/Page")) {
416 pages->contents = dup_pdfobj(get_dict_entry(pgtree, "/Contents"));
417 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
419 free_pdfobj(pages->resources);
420 pages->resources = obj;
422 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
424 free_pdfobj(pages->mediabox);
425 pages->mediabox = obj;
427 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
428 if (obj!=NULL && obj->type == PDFTYPE_INT)
429 pages->rotate = obj->intval;
433 else if (!strcmp(obj->str, "/Pages")) {
435 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Count"));
436 if (obj!=NULL && obj->type == PDFTYPE_INT &&
437 obj->intval>0 && obj->intval<=nmax) count = obj->intval;
440 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
442 for (i=0; i<count; i++) {
443 free_pdfobj(pages[i].resources);
444 pages[i].resources = dup_pdfobj(obj);
447 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
449 for (i=0; i<count; i++) {
450 free_pdfobj(pages[i].mediabox);
451 pages[i].mediabox = dup_pdfobj(obj);
454 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
455 if (obj!=NULL && obj->type == PDFTYPE_INT)
456 for (i=0; i<count; i++)
457 pages[i].rotate = obj->intval;
459 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Kids"));
460 if (obj!=NULL && obj->type == PDFTYPE_ARRAY) {
461 for (i=0; i<obj->num; i++) {
462 kid = get_pdfobj(pdfbuf, xref, obj->elts[i]);
464 j = pdf_getpageinfo(pdfbuf, xref, kid, nmax, pages);
477 // parse a PDF file in memory
479 gboolean pdf_parse_info(GString *pdfbuf, struct PdfInfo *pdfinfo, struct XrefTable *xref)
483 struct PdfObj *obj, *pages;
485 xref->n_alloc = xref->last = 0;
487 p = pdfbuf->str + pdfbuf->len-1;
489 while (*p!='s' && p!=pdfbuf->str) p--;
490 if (strncmp(p, "startxref", 9)) return FALSE; // fail
492 while (ispdfspace(*p) && p!=pdfbuf->str+pdfbuf->len) p++;
493 offs = strtol(p, NULL, 10);
494 if (offs <= 0 || offs > pdfbuf->len) return FALSE; // fail
495 pdfinfo->startxref = offs;
497 pdfinfo->trailerdict = parse_xref_table(pdfbuf, xref, offs);
498 if (pdfinfo->trailerdict == NULL) return FALSE; // fail
500 obj = get_pdfobj(pdfbuf, xref,
501 get_dict_entry(pdfinfo->trailerdict, "/Root"));
503 { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
504 pages = get_pdfobj(pdfbuf, xref, get_dict_entry(obj, "/Pages"));
507 { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
508 obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pages, "/Count"));
509 if (obj == NULL || obj->type != PDFTYPE_INT || obj->intval<=0)
510 { free_pdfobj(pdfinfo->trailerdict); free_pdfobj(pages);
511 free_pdfobj(obj); return FALSE; }
512 pdfinfo->npages = obj->intval;
515 pdfinfo->pages = g_malloc0(pdfinfo->npages*sizeof(struct PdfPageDesc));
516 pdf_getpageinfo(pdfbuf, xref, pages, pdfinfo->npages, pdfinfo->pages);
522 // add an entry to the xref table
524 void make_xref(struct XrefTable *xref, int nobj, int offset)
526 if (xref->n_alloc <= nobj) {
527 xref->n_alloc = nobj + 10;
528 xref->data = g_realloc(xref->data, xref->n_alloc*sizeof(int));
530 if (xref->last < nobj) xref->last = nobj;
531 xref->data[nobj] = offset;
534 // a wrapper for deflate
536 GString *do_deflate(char *in, int len)
543 deflateInit(&zs, Z_DEFAULT_COMPRESSION);
544 zs.next_in = (Bytef *)in;
546 zs.avail_out = deflateBound(&zs, len);
547 out = g_string_sized_new(zs.avail_out);
548 zs.next_out = (Bytef *)out->str;
549 deflate(&zs, Z_FINISH);
550 out->len = zs.total_out;
555 // prefix to scale the original page
557 GString *make_pdfprefix(struct PdfPageDesc *pgdesc, double width, double height)
560 double v[4], t, xscl, yscl;
563 // push 3 times in case code to be annotated has unbalanced q/Q (B of A., ...)
564 str = g_string_new("q q q ");
565 if (pgdesc->rotate == 90) {
566 g_string_append_printf(str, "0 -1 1 0 0 %.2f cm ", height);
567 t = height; height = width; width = t;
569 if (pgdesc->rotate == 270) {
570 g_string_append_printf(str, "0 1 -1 0 %.2f 0 cm ", width);
571 t = height; height = width; width = t;
573 if (pgdesc->rotate == 180) {
574 g_string_append_printf(str, "-1 0 0 -1 %.2f %.2f cm ", width, height);
576 if (pgdesc->mediabox==NULL || pgdesc->mediabox->type != PDFTYPE_ARRAY ||
577 pgdesc->mediabox->num != 4) return str;
578 for (i=0; i<4; i++) {
579 if (pgdesc->mediabox->elts[i]->type == PDFTYPE_INT)
580 v[i] = pgdesc->mediabox->elts[i]->intval;
581 else if (pgdesc->mediabox->elts[i]->type == PDFTYPE_REAL)
582 v[i] = pgdesc->mediabox->elts[i]->realval;
585 if (v[0]>v[2]) { t = v[0]; v[0] = v[2]; v[2] = t; }
586 if (v[1]>v[3]) { t = v[1]; v[1] = v[3]; v[3] = t; }
587 if (v[2]-v[0] < 1. || v[3]-v[1] < 1.) return str;
588 xscl = width/(v[2]-v[0]);
589 yscl = height/(v[3]-v[1]);
590 g_string_append_printf(str, "%.4f 0 0 %.4f %.2f %.2f cm ",
591 xscl, yscl, -v[0]*xscl, -v[1]*yscl);
595 // add an entry to a subentry of a directory
597 struct PdfObj *mk_pdfname(char *name)
601 obj = g_malloc(sizeof(struct PdfObj));
602 obj->type = PDFTYPE_NAME;
603 obj->str = g_strdup(name);
607 struct PdfObj *mk_pdfref(int num)
611 obj = g_malloc(sizeof(struct PdfObj));
612 obj->type = PDFTYPE_REF;
618 gboolean iseq_obj(struct PdfObj *a, struct PdfObj *b)
620 if (a==NULL || b==NULL) return (a==b);
621 if (a->type!=b->type) return FALSE;
622 if (a->type == PDFTYPE_CST || a->type == PDFTYPE_INT)
623 return (a->intval == b->intval);
624 if (a->type == PDFTYPE_REAL)
625 return (a->realval == b->realval);
626 if (a->type == PDFTYPE_NAME)
627 return !strcmp(a->str, b->str);
628 if (a->type == PDFTYPE_REF)
629 return (a->intval == b->intval && a->num == b->num);
633 void add_dict_subentry(GString *pdfbuf, struct XrefTable *xref,
634 struct PdfObj *obj, char *section, int type, char *name, struct PdfObj *entry)
640 for (i=0; i<obj->num; i++)
641 if (!strcmp(obj->names[i], section)) subpos = i;
645 obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj*));
646 obj->names = g_realloc(obj->names, obj->num*sizeof(char *));
647 obj->names[subpos] = g_strdup(section);
648 obj->elts[subpos] = NULL;
650 if (obj->elts[subpos]!=NULL && obj->elts[subpos]->type==PDFTYPE_REF) {
651 sec = get_pdfobj(pdfbuf, xref, obj->elts[subpos]);
652 free_pdfobj(obj->elts[subpos]);
653 obj->elts[subpos] = sec;
655 if (obj->elts[subpos]!=NULL && obj->elts[subpos]->type!=type)
656 { free_pdfobj(obj->elts[subpos]); obj->elts[subpos] = NULL; }
657 if (obj->elts[subpos] == NULL) {
658 obj->elts[subpos] = sec = g_malloc(sizeof(struct PdfObj));
664 sec = obj->elts[subpos];
667 if (type==PDFTYPE_DICT) {
668 for (i=0; i<sec->num; i++)
669 if (!strcmp(sec->names[i], name)) subpos = i;
673 sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
674 sec->names = g_realloc(sec->names, sec->num*sizeof(char *));
675 sec->names[subpos] = g_strdup(name);
676 sec->elts[subpos] = NULL;
678 free_pdfobj(sec->elts[subpos]);
679 sec->elts[subpos] = entry;
681 if (type==PDFTYPE_ARRAY) {
682 for (i=0; i<sec->num; i++)
683 if (iseq_obj(sec->elts[i], entry)) subpos = i;
687 sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
688 sec->elts[subpos] = entry;
690 else free_pdfobj(entry);
694 // draw a page's background
696 void pdf_draw_solid_background(struct Page *pg, GString *str)
700 g_string_append_printf(str,
701 "%.2f %.2f %.2f rg 0 0 %.2f %.2f re f ",
702 RGBA_RGB(pg->bg->color_rgba), pg->width, pg->height);
703 if (!ui.print_ruling) return;
704 if (pg->bg->ruling == RULING_NONE) return;
705 g_string_append_printf(str,
706 "%.2f %.2f %.2f RG %.2f w ",
707 RGBA_RGB(RULING_COLOR), RULING_THICKNESS);
708 if (pg->bg->ruling == RULING_GRAPH) {
709 for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
710 g_string_append_printf(str, "%.2f 0 m %.2f %.2f l S ",
712 for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
713 g_string_append_printf(str, "0 %.2f m %.2f %.2f l S ",
717 for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
718 g_string_append_printf(str, "0 %.2f m %.2f %.2f l S ",
720 if (pg->bg->ruling == RULING_LINED)
721 g_string_append_printf(str,
722 "%.2f %.2f %.2f RG %.2f 0 m %.2f %.2f l S ",
723 RGBA_RGB(RULING_MARGIN_COLOR),
724 RULING_LEFTMARGIN, RULING_LEFTMARGIN, pg->height);
727 int pdf_draw_bitmap_background(struct Page *pg, GString *str,
728 struct XrefTable *xref, GString *pdfbuf)
733 PopplerPage *pdfpage;
735 int height, width, stride, x, y, chan;
736 double pgheight, pgwidth;
738 if (pg->bg->type == BG_PDF) {
739 if (!bgpdf.document) return -1;
740 pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
741 if (!pdfpage) return -1;
742 poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
743 width = (int) (PDFTOPPM_PRINTING_DPI * pgwidth/72.0);
744 height = (int) (PDFTOPPM_PRINTING_DPI * pgheight/72.0);
745 pix = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);
746 wrapper_poppler_page_render_to_pixbuf(
747 pdfpage, 0, 0, width, height, PDFTOPPM_PRINTING_DPI/72.0, 0, pix);
748 g_object_unref(pdfpage);
750 else pix = g_object_ref(pg->bg->pixbuf);
752 if (gdk_pixbuf_get_bits_per_sample(pix) != 8 ||
753 gdk_pixbuf_get_colorspace(pix) != GDK_COLORSPACE_RGB)
754 { g_object_unref(pix); return -1; }
756 width = gdk_pixbuf_get_width(pix);
757 height = gdk_pixbuf_get_height(pix);
758 stride = gdk_pixbuf_get_rowstride(pix);
759 chan = gdk_pixbuf_get_n_channels(pix);
760 if (chan!=3 && chan!=4) { g_object_unref(pix); return -1; }
762 g_string_append_printf(str, "q %.2f 0 0 %.2f 0 %.2f cm /ImBg Do Q ",
763 pg->width, -pg->height, pg->height);
765 p2 = buf = (char *)g_malloc(3*width*height);
766 for (y=0; y<height; y++) {
767 p1 = (char *)gdk_pixbuf_get_pixels(pix)+stride*y;
768 for (x=0; x<width; x++) {
769 *(p2++)=*(p1++); *(p2++)=*(p1++); *(p2++)=*(p1++);
773 zpix = do_deflate(buf, 3*width*height);
777 make_xref(xref, xref->last+1, pdfbuf->len);
778 g_string_append_printf(pdfbuf,
779 "%d 0 obj\n<< /Length %zu /Filter /FlateDecode /Type /Xobject "
780 "/Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB "
781 "/BitsPerComponent 8 >> stream\n",
782 xref->last, zpix->len, width, height);
783 g_string_append_len(pdfbuf, zpix->str, zpix->len);
784 g_string_free(zpix, TRUE);
785 g_string_append(pdfbuf, "endstream\nendobj\n");
790 gboolean pdf_draw_image(PdfImage *image, struct XrefTable *xref, GString *pdfbuf)
793 int height, width, stride, x, y, chan;
796 if (gdk_pixbuf_get_bits_per_sample(image->pixbuf) != 8 ||
797 gdk_pixbuf_get_colorspace(image->pixbuf) != GDK_COLORSPACE_RGB) {
801 width = gdk_pixbuf_get_width(image->pixbuf);
802 height = gdk_pixbuf_get_height(image->pixbuf);
803 stride = gdk_pixbuf_get_rowstride(image->pixbuf);
804 chan = gdk_pixbuf_get_n_channels(image->pixbuf);
805 if (!((chan==3 && !image->has_alpha) || (chan==4 && image->has_alpha))) {
809 p2 = buf = (char *)g_malloc(3*width*height);
810 for (y=0; y<height; y++) {
811 p1 = (char *)gdk_pixbuf_get_pixels(image->pixbuf)+stride*y;
812 for (x=0; x<width; x++) {
813 *(p2++)=*(p1++); *(p2++)=*(p1++); *(p2++)=*(p1++);
817 zpix = do_deflate(buf, 3*width*height);
820 xref->data[image->n_obj] = pdfbuf->len;
821 g_string_append_printf(pdfbuf,
822 "%d 0 obj\n<< /Length %d /Filter /FlateDecode /Type /Xobject "
823 "/Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB "
824 "/BitsPerComponent 8 ",
825 image->n_obj, zpix->len, width, height);
826 if (image->has_alpha) {
827 g_string_append_printf(pdfbuf,
831 g_string_append_printf(pdfbuf, " >> stream\n");
833 g_string_append_len(pdfbuf, zpix->str, zpix->len);
834 g_string_free(zpix, TRUE);
835 g_string_append(pdfbuf, "endstream\nendobj\n");
837 if (image->has_alpha) {
838 p2 = buf = (char *)g_malloc(width*height);
839 for (y=0; y<height; y++) {
840 p1 = (char *)gdk_pixbuf_get_pixels(image->pixbuf)+stride*y;
841 for (x=0; x<width; x++) {
842 p1+=3; /* skip the RGB */
843 *(p2++)=*(p1++); /* just copy the alpha */
846 zpix = do_deflate(buf, width*height);
849 xref->data[image->n_obj_smask] = pdfbuf->len;
850 g_string_append_printf(pdfbuf,
851 "%d 0 obj\n<< /Length %d /Filter /FlateDecode /Type /Xobject "
852 "/Subtype /Image /Width %d /Height %d /ColorSpace /DeviceGray "
853 "/BitsPerComponent 8 >> stream\n",
854 image->n_obj_smask, zpix->len, width, height);
856 g_string_append_len(pdfbuf, zpix->str, zpix->len);
857 g_string_free(zpix, TRUE);
858 g_string_append(pdfbuf, "endstream\nendobj\n");
865 // manipulate Pdf fonts
867 struct PdfFont *new_pdffont(struct XrefTable *xref, GList **fonts,
868 char *filename, int font_id, FT_Face face, int glyph_page)
871 struct PdfFont *font;
875 for (list = *fonts; list!=NULL; list = list->next) {
876 font = (struct PdfFont *)list->data;
877 if (!strcmp(font->filename, filename) && font->font_id == font_id
878 && font->glyph_page == glyph_page)
879 { font->used_in_this_page = TRUE; return font; }
881 font = g_malloc(sizeof(struct PdfFont));
882 *fonts = g_list_append(*fonts, font);
883 font->n_obj = xref->last+1;
884 make_xref(xref, xref->last+1, 0); // will give it a value later
885 font->filename = g_strdup(filename);
886 font->font_id = font_id;
887 font->glyph_page = glyph_page;
888 font->used_in_this_page = TRUE;
889 font->num_glyphs_used = 0;
890 for (i=0; i<256; i++) {
891 font->glyphmap[i] = -1;
892 font->advance[i] = 0;
893 font->glyphpsnames[i] = NULL;
895 font->glyphmap[0] = 0;
896 // fill in info from the FT_Face
897 font->is_truetype = FT_IS_SFNT(face);
898 font->nglyphs = face->num_glyphs;
899 font->ft2ps = 1000.0 / face->units_per_EM;
900 font->ascender = (int)(font->ft2ps*face->ascender);
901 font->descender = (int)(font->ft2ps*face->descender);
902 if (face->bbox.xMin < -100000 || face->bbox.xMin > 100000) font->xmin = 0;
903 else font->xmin = (int)(font->ft2ps*face->bbox.xMin);
904 if (face->bbox.xMax < -100000 || face->bbox.xMax > 100000) font->xmax = 0;
905 else font->xmax = (int)(font->ft2ps*face->bbox.xMax);
906 if (face->bbox.yMin < -100000 || face->bbox.yMin > 100000) font->ymin = 0;
907 else font->ymin = (int)(font->ft2ps*face->bbox.yMin);
908 if (face->bbox.yMax < -100000 || face->bbox.yMax > 100000) font->ymax = 0;
909 else font->ymax = (int)(font->ft2ps*face->bbox.yMax);
910 if (font->is_truetype) font->flags = 4; // symbolic
912 font->flags = 4; // symbolic
913 if (FT_IS_FIXED_WIDTH(face)) font->flags |= 1;
914 if (face->style_flags & FT_STYLE_FLAG_ITALIC) font->flags |= 64;
916 s = FT_Get_Postscript_Name(face);
917 if (s==NULL) s = "Noname";
918 if (glyph_page) font->fontname = g_strdup_printf("%s_%03d", s, glyph_page);
919 else font->fontname = g_strdup(s);
923 #define pfb_get_length(x) (((x)[3]<<24) + ((x)[2]<<16) + ((x)[1]<<8) + (x)[0])
924 #define T1_SEGMENT_1_END "currentfile eexec"
925 #define T1_SEGMENT_3_END "cleartomark"
927 void embed_pdffont(GString *pdfbuf, struct XrefTable *xref, struct PdfFont *font)
929 // this code inspired by libgnomeprint
930 gboolean fallback, is_binary;
931 guchar encoding[256];
941 int nobj_fontprog, nobj_descr, lastchar;
944 // embed the font file: TrueType case
945 if (font->is_truetype) {
946 glyphs[0] = encoding[0] = 0;
948 for (i=1; i<=255; i++)
949 if (font->glyphmap[i]>=0) {
950 font->glyphmap[i] = num;
951 glyphs[num] = 255*font->glyph_page+i-1;
955 font->num_glyphs_used = num-1;
956 if (OpenTTFont(font->filename, 0, &ttfnt) == SF_OK) {
957 if (CreateTTFromTTGlyphs_tomemory(ttfnt, (guint8**)&fontdata, &tt_len, glyphs, encoding, num,
958 0, NULL, TTCF_AutoName | TTCF_IncludeOS2) == SF_OK) {
959 make_xref(xref, xref->last+1, pdfbuf->len);
960 nobj_fontprog = xref->last;
961 g_string_append_printf(pdfbuf,
962 "%d 0 obj\n<< /Length %u /Length1 %u >> stream\n",
963 nobj_fontprog, tt_len, tt_len);
964 g_string_append_len(pdfbuf, fontdata, tt_len);
965 g_string_append(pdfbuf, "endstream\nendobj\n");
968 else fallback = TRUE;
971 else fallback = TRUE;
973 // embed the font file: Type1 case
974 if (g_file_get_contents(font->filename, &fontdata, &t1_len, NULL) && t1_len>=8) {
975 if (fontdata[0]==(char)0x80 && fontdata[1]==(char)0x01) {
977 len1 = pfb_get_length((unsigned char *)fontdata+2);
978 if (fontdata[len1+6]!=(char)0x80 || fontdata[len1+7]!=(char)0x02) fallback = TRUE;
980 len2 = pfb_get_length((unsigned char *)fontdata+len1+8);
981 if (fontdata[len1+len2+12]!=(char)0x80 || fontdata[len1+len2+13]!=(char)0x01)
985 else if (!strncmp(fontdata, "%!PS", 4)) {
987 p = strstr(fontdata, T1_SEGMENT_1_END) + strlen(T1_SEGMENT_1_END);
988 if (p==NULL) fallback = TRUE;
990 if (*p=='\n' || *p=='\r') p++;
991 if (*p=='\n' || *p=='\r') p++;
993 p = g_strrstr_len(fontdata, t1_len, T1_SEGMENT_3_END);
994 if (p==NULL) fallback = TRUE;
998 while (i>0 && p!=fontdata && (*p=='0' || *p=='\r' || *p=='\n')) {
1002 while (p!=fontdata && (*p=='\r' || *p=='\n')) p--;
1004 if (i>0) fallback = TRUE;
1005 else len2 = p-fontdata-len1;
1009 else fallback = TRUE;
1013 seg2 = fontdata + len1 + 12;
1016 seg2 = g_malloc(len2/2);
1019 while (p+1 < fontdata+len1+len2) {
1020 if (*p==' '||*p=='\t'||*p=='\n'||*p=='\r') { p++; continue; }
1021 if (p[0]>'9') { p[0]|=0x20; p[0]-=39; }
1022 if (p[1]>'9') { p[1]|=0x20; p[1]-=39; }
1023 seg2[j++] = ((p[0]-'0')<<4) + (p[1]-'0');
1028 make_xref(xref, xref->last+1, pdfbuf->len);
1029 nobj_fontprog = xref->last;
1030 g_string_append_printf(pdfbuf,
1031 "%d 0 obj\n<< /Length %u /Length1 %u /Length2 %u /Length3 0 >> stream\n",
1032 nobj_fontprog, len1+len2, len1, len2);
1033 g_string_append_len(pdfbuf, seg1, len1);
1034 g_string_append_len(pdfbuf, seg2, len2);
1035 g_string_append(pdfbuf, "endstream\nendobj\n");
1036 if (!is_binary) g_free(seg2);
1040 else fallback = TRUE;
1043 // next, the font descriptor
1045 make_xref(xref, xref->last+1, pdfbuf->len);
1046 nobj_descr = xref->last;
1047 g_string_append_printf(pdfbuf,
1048 "%d 0 obj\n<< /Type /FontDescriptor /FontName /%s /Flags %d "
1049 "/FontBBox [%d %d %d %d] /ItalicAngle 0 /Ascent %d "
1050 "/Descent %d /CapHeight %d /StemV 100 /%s %d 0 R >> endobj\n",
1051 nobj_descr, font->fontname, font->flags,
1052 font->xmin, font->ymin, font->xmax, font->ymax,
1053 font->ascender, -font->descender, font->ascender,
1054 font->is_truetype ? "FontFile2":"FontFile",
1058 // finally, the font itself
1059 /* Note: in Type1 case, font->glyphmap maps charcodes to glyph no's
1060 in TrueType case, encoding lists the used charcodes by index,
1061 glyphs list the used glyph no's by index
1062 font->glyphmap maps charcodes to indices */
1063 xref->data[font->n_obj] = pdfbuf->len;
1064 if (font->is_truetype) lastchar = encoding[font->num_glyphs_used];
1065 else lastchar = font->num_glyphs_used;
1067 font->is_truetype = FALSE;
1068 g_free(font->fontname);
1069 font->fontname = g_strdup("Helvetica");
1072 if (font->is_truetype) {
1073 num = font->glyph_page;
1074 for (i=0; i<6; i++) { prefix[i] = 'A'+(num%26); num/=26; }
1075 prefix[6]='+'; prefix[7]=0;
1077 g_string_append_printf(pdfbuf,
1078 "%d 0 obj\n<< /Type /Font /Subtype /%s /BaseFont /%s%s /Name /F%d ",
1079 font->n_obj, font->is_truetype?"TrueType":"Type1",
1080 prefix, font->fontname, font->n_obj);
1082 g_string_append_printf(pdfbuf,
1083 "/FontDescriptor %d 0 R /FirstChar 0 /LastChar %d /Widths [",
1084 nobj_descr, lastchar);
1085 for (i=0; i<=lastchar; i++)
1086 g_string_append_printf(pdfbuf, "%d ", font->advance[i]);
1087 g_string_append(pdfbuf, "] ");
1089 if (!font->is_truetype) { /* encoding */
1090 g_string_append(pdfbuf, "/Encoding << /Type /Encoding "
1091 "/BaseEncoding /MacRomanEncoding /Differences [1 ");
1092 for (i=1; i<=lastchar; i++) {
1093 g_string_append_printf(pdfbuf, "/%s ", font->glyphpsnames[i]);
1094 g_free(font->glyphpsnames[i]);
1096 g_string_append(pdfbuf, "] >> ");
1098 g_string_append(pdfbuf, ">> endobj\n");
1103 struct PdfImage *new_pdfimage(struct XrefTable *xref, GList **images, GdkPixbuf *pixbuf)
1106 struct PdfImage *image;
1108 image = g_malloc(sizeof(struct PdfImage));
1109 *images = g_list_append(*images, image);
1110 image->n_obj = xref->last+1;
1111 make_xref(xref, xref->last+1, 0); // will give it a value later
1112 image->has_alpha = gdk_pixbuf_get_has_alpha(pixbuf);
1113 if (image->has_alpha) {
1114 image->n_obj_smask = xref->last+1;
1115 make_xref(xref, xref->last+1, 0); // will give it a value later
1117 image->pixbuf = pixbuf;
1122 // draw a page's graphics
1124 void pdf_draw_page(struct Page *pg, GString *str, gboolean *use_hiliter,
1125 struct XrefTable *xref, GList **pdffonts, GList **pdfimages)
1127 GList *layerlist, *itemlist, *tmplist;
1130 guint old_rgba, old_text_rgba;
1131 double old_thickness;
1134 PangoFontDescription *font_desc;
1135 PangoContext *context;
1136 PangoLayout *layout;
1137 PangoLayoutIter *iter;
1138 PangoRectangle logical_rect;
1139 PangoLayoutRun *run;
1140 PangoFcFont *fcfont;
1141 PangoFontMap *fontmap;
1143 int baseline, advance;
1144 int glyph_no, glyph_page, current_page;
1149 struct PdfFont *cur_font;
1150 struct PdfImage *cur_image;
1153 old_rgba = old_text_rgba = 0x12345678; // not any values we use, so we'll reset them
1154 old_thickness = 0.0;
1155 for (tmplist = *pdffonts; tmplist!=NULL; tmplist = tmplist->next) {
1156 cur_font = (struct PdfFont *)tmplist->data;
1157 cur_font->used_in_this_page = FALSE;
1159 for (tmplist = *pdfimages; tmplist!=NULL; tmplist = tmplist->next) {
1160 cur_image = (struct PdfImage *)tmplist->data;
1161 cur_image->used_in_this_page = FALSE;
1164 for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1165 l = (struct Layer *)layerlist->data;
1166 for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1167 item = (struct Item *)itemlist->data;
1168 if (item->type == ITEM_STROKE) {
1169 if ((item->brush.color_rgba & ~0xff) != old_rgba)
1170 g_string_append_printf(str, "%.2f %.2f %.2f RG ",
1171 RGBA_RGB(item->brush.color_rgba));
1172 if (item->brush.thickness != old_thickness)
1173 g_string_append_printf(str, "%.2f w ", item->brush.thickness);
1174 if ((item->brush.color_rgba & 0xf0) != 0xf0) { // transparent
1175 g_string_append(str, "q /XoHi gs ");
1176 *use_hiliter = TRUE;
1178 old_rgba = item->brush.color_rgba & ~0xff;
1179 old_thickness = item->brush.thickness;
1180 pt = item->path->coords;
1181 if (!item->brush.variable_width) {
1182 g_string_append_printf(str, "%.2f %.2f m ", pt[0], pt[1]);
1183 for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1184 g_string_append_printf(str, "%.2f %.2f l ", pt[0], pt[1]);
1185 g_string_append_printf(str,"S\n");
1186 old_thickness = item->brush.thickness;
1188 for (i=0; i<item->path->num_points-1; i++, pt+=2)
1189 g_string_append_printf(str, "%.2f w %.2f %.2f m %.2f %.2f l S\n",
1190 item->widths[i], pt[0], pt[1], pt[2], pt[3]);
1191 old_thickness = 0.0;
1193 if ((item->brush.color_rgba & 0xf0) != 0xf0) // undo transparent
1194 g_string_append(str, "Q ");
1196 else if (item->type == ITEM_TEXT) {
1197 if ((item->brush.color_rgba & ~0xff) != old_text_rgba)
1198 g_string_append_printf(str, "%.2f %.2f %.2f rg ",
1199 RGBA_RGB(item->brush.color_rgba));
1200 old_text_rgba = item->brush.color_rgba & ~0xff;
1201 fontmap = pango_ft2_font_map_new();
1202 pango_ft2_font_map_set_resolution(PANGO_FT2_FONT_MAP (fontmap), 72, 72);
1203 context = pango_context_new();
1204 pango_context_set_font_map(context, fontmap);
1205 layout = pango_layout_new(context);
1206 g_object_unref(fontmap);
1207 g_object_unref(context);
1208 font_desc = pango_font_description_from_string(item->font_name);
1209 pango_font_description_set_absolute_size(font_desc,
1210 item->font_size*PANGO_SCALE);
1211 pango_layout_set_font_description(layout, font_desc);
1212 pango_font_description_free(font_desc);
1213 pango_layout_set_text(layout, item->text, -1);
1214 // this code inspired by the code in libgnomeprint
1215 iter = pango_layout_get_iter(layout);
1217 run = pango_layout_iter_get_run(iter);
1218 if (run==NULL) continue;
1219 pango_layout_iter_get_run_extents (iter, NULL, &logical_rect);
1220 baseline = pango_layout_iter_get_baseline (iter);
1221 if (!PANGO_IS_FC_FONT(run->item->analysis.font)) continue;
1222 fcfont = PANGO_FC_FONT(run->item->analysis.font);
1223 pattern = fcfont->font_pattern;
1224 if (FcPatternGetString(pattern, FC_FILE, 0, (unsigned char **)&filename) != FcResultMatch ||
1225 FcPatternGetInteger(pattern, FC_INDEX, 0, &font_id) != FcResultMatch)
1227 ftface = pango_fc_font_lock_face(fcfont);
1230 g_string_append_printf(str, "BT %.2f 0 0 %.2f %.2f %.2f Tm ",
1231 item->font_size, -item->font_size,
1232 item->bbox.left + (gdouble) logical_rect.x/PANGO_SCALE,
1233 item->bbox.top + (gdouble) baseline/PANGO_SCALE);
1235 for (i=0; i<run->glyphs->num_glyphs; i++) {
1236 glyph_no = run->glyphs->glyphs[i].glyph;
1237 if (FT_IS_SFNT(ftface)) glyph_page = glyph_no/255;
1238 else glyph_page = 0;
1239 if (glyph_page != current_page) {
1240 cur_font = new_pdffont(xref, pdffonts, filename, font_id,
1241 ftface, glyph_page);
1242 if (in_string) g_string_append(str, ") Tj ");
1244 g_string_append_printf(str, "/F%d 1 Tf ", cur_font->n_obj);
1246 current_page = glyph_page;
1247 FT_Load_Glyph(ftface, glyph_no, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM);
1248 advance = (int)(ftface->glyph->metrics.horiAdvance * cur_font->ft2ps + 0.5);
1249 if (!in_string) g_string_append_c(str, '(');
1251 if (cur_font->is_truetype) {
1252 if (glyph_no) glyph_no = (glyph_no%255)+1;
1253 cur_font->glyphmap[glyph_no] = glyph_no;
1256 for (j=1; j<=cur_font->num_glyphs_used; j++)
1257 if (cur_font->glyphmap[j] == glyph_no) break;
1258 if (j==256) j=0; // font is full, what do we do?
1259 if (j>cur_font->num_glyphs_used) {
1260 cur_font->glyphmap[j] = glyph_no;
1261 cur_font->num_glyphs_used++;
1262 if (FT_Get_Glyph_Name(ftface, glyph_no, tmpstr, 200) == FT_Err_Ok)
1263 cur_font->glyphpsnames[j] = g_strdup(tmpstr);
1264 else cur_font->glyphpsnames[j] = g_strdup(".notdef");
1268 cur_font->advance[glyph_no] = advance;
1269 if (glyph_no=='\\' || glyph_no == '(' || glyph_no == ')' || glyph_no == 10 || glyph_no == 13)
1270 g_string_append_c(str, '\\');
1271 if (glyph_no==10) g_string_append_c(str,'n');
1272 else if (glyph_no==13) g_string_append_c(str,'r');
1273 else g_string_append_c(str, glyph_no);
1275 if (in_string) g_string_append(str, ") Tj ");
1276 g_string_append(str, "ET ");
1277 pango_fc_font_unlock_face(fcfont);
1278 } while (pango_layout_iter_next_run(iter));
1279 pango_layout_iter_free(iter);
1280 g_object_unref(layout);
1282 else if (item->type == ITEM_IMAGE) {
1283 cur_image = new_pdfimage(xref, pdfimages, item->image);
1284 cur_image->used_in_this_page = TRUE;
1285 g_string_append_printf(str, "\nq 1 0 0 1 %.2f %.2f cm %.2f 0 0 %.2f 0 %.2f cm /Im%d Do Q ",
1286 item->bbox.left, item->bbox.top, // translation
1287 item->bbox.right-item->bbox.left, item->bbox.top-item->bbox.bottom, item->bbox.bottom-item->bbox.top, // scaling
1294 // main printing function
1296 /* we use the following object numbers, starting with n_obj_catalog:
1297 0 the document catalog
1299 2 the GS for the hiliters
1300 3 ... the page objects
1303 gboolean print_to_pdf(char *filename)
1306 GString *pdfbuf, *pgstrm, *zpgstrm, *tmpstr;
1307 int n_obj_catalog, n_obj_pages_offs, n_page, n_obj_bgpix, n_obj_prefix;
1309 struct XrefTable xref;
1312 gboolean annot, uses_pdf;
1313 gboolean use_hiliter;
1314 struct PdfInfo pdfinfo;
1316 GList *pdffonts, *pdfimages, *list;
1317 struct PdfFont *font;
1318 struct PdfImage *image;
1321 f = fopen(filename, "wb");
1322 if (f == NULL) return FALSE;
1323 setlocale(LC_NUMERIC, "C");
1329 for (pglist = journal.pages; pglist!=NULL; pglist = pglist->next) {
1330 pg = (struct Page *)pglist->data;
1331 if (pg->bg->type == BG_PDF) uses_pdf = TRUE;
1334 if (uses_pdf && bgpdf.status != STATUS_NOT_INIT &&
1335 bgpdf.file_contents!=NULL && !strncmp(bgpdf.file_contents, "%PDF-1.", 7)) {
1336 // parse the existing PDF file
1337 pdfbuf = g_string_new_len(bgpdf.file_contents, bgpdf.file_length);
1338 if (pdfbuf->str[7]<'4') pdfbuf->str[7] = '4'; // upgrade to 1.4
1339 annot = pdf_parse_info(pdfbuf, &pdfinfo, &xref);
1341 g_string_free(pdfbuf, TRUE);
1342 if (xref.data != NULL) g_free(xref.data);
1347 pdfbuf = g_string_new("%PDF-1.4\n%\370\357\365\362\n");
1348 xref.n_alloc = xref.last = 0;
1352 // catalog and page tree
1353 n_obj_catalog = xref.last+1;
1354 n_obj_pages_offs = xref.last+4;
1355 make_xref(&xref, n_obj_catalog, pdfbuf->len);
1356 g_string_append_printf(pdfbuf,
1357 "%d 0 obj\n<< /Type /Catalog /Pages %d 0 R >> endobj\n",
1358 n_obj_catalog, n_obj_catalog+1);
1359 make_xref(&xref, n_obj_catalog+1, pdfbuf->len);
1360 g_string_append_printf(pdfbuf,
1361 "%d 0 obj\n<< /Type /Pages /Kids [", n_obj_catalog+1);
1362 for (i=0;i<journal.npages;i++)
1363 g_string_append_printf(pdfbuf, "%d 0 R ", n_obj_pages_offs+i);
1364 g_string_append_printf(pdfbuf, "] /Count %d >> endobj\n", journal.npages);
1365 make_xref(&xref, n_obj_catalog+2, pdfbuf->len);
1366 g_string_append_printf(pdfbuf,
1367 "%d 0 obj\n<< /Type /ExtGState /CA %.2f >> endobj\n",
1368 n_obj_catalog+2, ui.hiliter_opacity);
1369 xref.last = n_obj_pages_offs + journal.npages-1;
1371 for (pglist = journal.pages, n_page = 0; pglist!=NULL;
1372 pglist = pglist->next, n_page++) {
1373 pg = (struct Page *)pglist->data;
1375 // draw the background and page into pgstrm
1376 pgstrm = g_string_new("");
1377 g_string_printf(pgstrm, "q 1 0 0 -1 0 %.2f cm 1 J 1 j ", pg->height);
1380 if (pg->bg->type == BG_SOLID)
1381 pdf_draw_solid_background(pg, pgstrm);
1382 else if (pg->bg->type == BG_PDF && annot &&
1383 pdfinfo.pages[pg->bg->file_page_seq-1].contents!=NULL) {
1384 make_xref(&xref, xref.last+1, pdfbuf->len);
1385 n_obj_prefix = xref.last;
1386 tmpstr = make_pdfprefix(pdfinfo.pages+(pg->bg->file_page_seq-1),
1387 pg->width, pg->height);
1388 g_string_append_printf(pdfbuf,
1389 "%d 0 obj\n<< /Length %zu >> stream\n%s\nendstream\nendobj\n",
1390 n_obj_prefix, tmpstr->len, tmpstr->str);
1391 g_string_free(tmpstr, TRUE);
1392 g_string_prepend(pgstrm, "Q Q Q ");
1394 else if (pg->bg->type == BG_PIXMAP || pg->bg->type == BG_PDF)
1395 n_obj_bgpix = pdf_draw_bitmap_background(pg, pgstrm, &xref, pdfbuf);
1396 // draw the page contents
1397 use_hiliter = FALSE;
1398 pdf_draw_page(pg, pgstrm, &use_hiliter, &xref, &pdffonts, &pdfimages);
1399 g_string_append_printf(pgstrm, "Q\n");
1401 // deflate pgstrm and write it
1402 zpgstrm = do_deflate(pgstrm->str, pgstrm->len);
1403 g_string_free(pgstrm, TRUE);
1405 make_xref(&xref, xref.last+1, pdfbuf->len);
1406 g_string_append_printf(pdfbuf,
1407 "%d 0 obj\n<< /Length %zu /Filter /FlateDecode>> stream\n",
1408 xref.last, zpgstrm->len);
1409 g_string_append_len(pdfbuf, zpgstrm->str, zpgstrm->len);
1410 g_string_free(zpgstrm, TRUE);
1411 g_string_append(pdfbuf, "endstream\nendobj\n");
1413 // write the page object
1415 make_xref(&xref, n_obj_pages_offs+n_page, pdfbuf->len);
1416 g_string_append_printf(pdfbuf,
1417 "%d 0 obj\n<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %.2f %.2f] ",
1418 n_obj_pages_offs+n_page, n_obj_catalog+1, pg->width, pg->height);
1419 if (n_obj_prefix>0) {
1420 obj = get_pdfobj(pdfbuf, &xref, pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1421 if (obj->type != PDFTYPE_ARRAY) {
1423 obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1425 g_string_append_printf(pdfbuf, "/Contents [%d 0 R ", n_obj_prefix);
1426 if (obj->type == PDFTYPE_REF)
1427 g_string_append_printf(pdfbuf, "%d %d R ", obj->intval, obj->num);
1428 if (obj->type == PDFTYPE_ARRAY) {
1429 for (i=0; i<obj->num; i++) {
1430 show_pdfobj(obj->elts[i], pdfbuf);
1431 g_string_append_c(pdfbuf, ' ');
1435 g_string_append_printf(pdfbuf, "%d 0 R] ", xref.last);
1437 else g_string_append_printf(pdfbuf, "/Contents %d 0 R ", xref.last);
1438 g_string_append(pdfbuf, "/Resources ");
1441 obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].resources);
1443 if (obj!=NULL && obj->type!=PDFTYPE_DICT)
1444 { free_pdfobj(obj); obj=NULL; }
1446 obj = g_malloc(sizeof(struct PdfObj));
1447 obj->type = PDFTYPE_DICT;
1452 add_dict_subentry(pdfbuf, &xref,
1453 obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/PDF"));
1454 if (n_obj_bgpix>0 || pdfimages!=NULL)
1455 add_dict_subentry(pdfbuf, &xref,
1456 obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/ImageC"));
1458 add_dict_subentry(pdfbuf, &xref,
1459 obj, "/ExtGState", PDFTYPE_DICT, "/XoHi", mk_pdfref(n_obj_catalog+2));
1461 add_dict_subentry(pdfbuf, &xref,
1462 obj, "/XObject", PDFTYPE_DICT, "/ImBg", mk_pdfref(n_obj_bgpix));
1463 for (list=pdffonts; list!=NULL; list = list->next) {
1464 font = (struct PdfFont *)list->data;
1465 if (font->used_in_this_page) {
1466 add_dict_subentry(pdfbuf, &xref,
1467 obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/Text"));
1468 tmpbuf = g_strdup_printf("/F%d", font->n_obj);
1469 add_dict_subentry(pdfbuf, &xref,
1470 obj, "/Font", PDFTYPE_DICT, tmpbuf, mk_pdfref(font->n_obj));
1474 for (list=pdfimages; list!=NULL; list = list->next) {
1475 image = (struct PdfImage *)list->data;
1476 if (image->used_in_this_page) {
1477 tmpbuf = g_strdup_printf("/Im%d", image->n_obj);
1478 add_dict_subentry(pdfbuf, &xref,
1479 obj, "/XObject", PDFTYPE_DICT, tmpbuf, mk_pdfref(image->n_obj));
1483 show_pdfobj(obj, pdfbuf);
1485 g_string_append(pdfbuf, " >> endobj\n");
1488 // after the pages, we insert fonts and images
1489 for (list = pdffonts; list!=NULL; list = list->next) {
1490 font = (struct PdfFont *)list->data;
1491 embed_pdffont(pdfbuf, &xref, font);
1492 g_free(font->filename);
1493 g_free(font->fontname);
1496 g_list_free(pdffonts);
1497 for (list = pdfimages; list!=NULL; list = list->next) {
1498 image = (struct PdfImage *)list->data;
1499 if (!pdf_draw_image(image, &xref, pdfbuf)) {
1504 g_list_free(pdfimages);
1507 startxref = pdfbuf->len;
1508 if (annot) g_string_append_printf(pdfbuf,
1509 "xref\n%d %d\n", n_obj_catalog, xref.last-n_obj_catalog+1);
1510 else g_string_append_printf(pdfbuf,
1511 "xref\n0 %d\n0000000000 65535 f \n", xref.last+1);
1512 for (i=n_obj_catalog; i<=xref.last; i++)
1513 g_string_append_printf(pdfbuf, "%010d 00000 n \n", xref.data[i]);
1514 g_string_append_printf(pdfbuf,
1515 "trailer\n<< /Size %d /Root %d 0 R ", xref.last+1, n_obj_catalog);
1517 g_string_append_printf(pdfbuf, "/Prev %d ", pdfinfo.startxref);
1518 // keeping encryption info somehow doesn't work.
1519 // xournal can't annotate encrypted PDFs anyway...
1521 obj = get_dict_entry(pdfinfo.trailerdict, "/Encrypt");
1523 g_string_append_printf(pdfbuf, "/Encrypt ");
1524 show_pdfobj(obj, pdfbuf);
1528 g_string_append_printf(pdfbuf,
1529 ">>\nstartxref\n%d\n%%%%EOF\n", startxref);
1533 free_pdfobj(pdfinfo.trailerdict);
1534 if (pdfinfo.pages!=NULL)
1535 for (i=0; i<pdfinfo.npages; i++) {
1536 free_pdfobj(pdfinfo.pages[i].resources);
1537 free_pdfobj(pdfinfo.pages[i].mediabox);
1538 free_pdfobj(pdfinfo.pages[i].contents);
1542 setlocale(LC_NUMERIC, "");
1543 if (fwrite(pdfbuf->str, 1, pdfbuf->len, f) < pdfbuf->len) {
1545 g_string_free(pdfbuf, TRUE);
1549 g_string_free(pdfbuf, TRUE);
1553 /*********** Printing via gtk-print **********/
1555 #if GTK_CHECK_VERSION(2, 10, 0)
1557 // does the same job as update_canvas_bg(), but to a print context
1559 void print_background(cairo_t *cr, struct Page *pg)
1564 PopplerPage *pdfpage;
1565 cairo_surface_t *cr_pixbuf;
1566 double pgwidth, pgheight;
1568 if (pg->bg->type == BG_SOLID) {
1569 cairo_set_source_rgb(cr, RGBA_RGB(pg->bg->color_rgba));
1570 cairo_rectangle(cr, 0, 0, pg->width, pg->height);
1572 if (!ui.print_ruling) return;
1573 if (pg->bg->ruling == RULING_NONE) return;
1574 cairo_set_source_rgb(cr, RGBA_RGB(RULING_COLOR));
1575 cairo_set_line_width(cr, RULING_THICKNESS);
1577 if (pg->bg->ruling == RULING_GRAPH) {
1578 for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
1579 { cairo_move_to(cr, x, 0); cairo_line_to(cr, x, pg->height); }
1580 for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
1581 { cairo_move_to(cr, 0, y); cairo_line_to(cr, pg->width, y); }
1586 for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
1587 { cairo_move_to(cr, 0, y); cairo_line_to(cr, pg->width, y); }
1589 if (pg->bg->ruling == RULING_LINED) {
1590 cairo_set_source_rgb(cr, RGBA_RGB(RULING_MARGIN_COLOR));
1591 cairo_move_to(cr, RULING_LEFTMARGIN, 0);
1592 cairo_line_to(cr, RULING_LEFTMARGIN, pg->height);
1598 if (pg->bg->type == BG_PDF) {
1599 if (!bgpdf.document) return;
1600 pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
1601 if (!pdfpage) return;
1602 poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
1604 cairo_scale(cr, pg->width/pgwidth, pg->height/pgheight);
1605 poppler_page_render(pdfpage, cr);
1607 g_object_unref(pdfpage);
1610 if (pg->bg->type == BG_PIXMAP) {
1612 cairo_scale(cr, pg->width/gdk_pixbuf_get_width(pg->bg->pixbuf),
1613 pg->height/gdk_pixbuf_get_height(pg->bg->pixbuf));
1614 gdk_cairo_set_source_pixbuf(cr, pg->bg->pixbuf, 0, 0);
1615 cairo_rectangle(cr, 0, 0, gdk_pixbuf_get_width(pg->bg->pixbuf), gdk_pixbuf_get_height(pg->bg->pixbuf));
1621 void print_job_render_page(GtkPrintOperation *print, GtkPrintContext *context, gint pageno, gpointer user_data)
1624 gdouble width, height, scale;
1627 double old_thickness;
1628 GList *layerlist, *itemlist;
1633 PangoFontDescription *font_desc;
1634 PangoLayout *layout;
1636 pg = (struct Page *)g_list_nth_data(journal.pages, pageno);
1637 cr = gtk_print_context_get_cairo_context(context);
1638 width = gtk_print_context_get_width(context);
1639 height = gtk_print_context_get_height(context);
1640 scale = MIN(width/pg->width, height/pg->height);
1642 cairo_translate(cr, (width-scale*pg->width)/2, (height-scale*pg->height)/2);
1643 cairo_scale(cr, scale, scale);
1644 cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
1645 cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
1647 print_background(cr, pg);
1649 old_rgba = predef_colors_rgba[COLOR_BLACK];
1650 cairo_set_source_rgb(cr, 0, 0, 0);
1651 old_thickness = 0.0;
1653 for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1654 l = (struct Layer *)layerlist->data;
1655 for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1656 item = (struct Item *)itemlist->data;
1657 if (item->type == ITEM_STROKE || item->type == ITEM_TEXT) {
1658 if (item->brush.color_rgba != old_rgba)
1659 cairo_set_source_rgba(cr, RGBA_RGB(item->brush.color_rgba),
1660 RGBA_ALPHA(item->brush.color_rgba));
1661 old_rgba = item->brush.color_rgba;
1663 if (item->type == ITEM_STROKE) {
1664 if (item->brush.thickness != old_thickness)
1665 cairo_set_line_width(cr, item->brush.thickness);
1666 pt = item->path->coords;
1667 if (!item->brush.variable_width) {
1668 cairo_move_to(cr, pt[0], pt[1]);
1669 for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1670 cairo_line_to(cr, pt[0], pt[1]);
1672 old_thickness = item->brush.thickness;
1674 for (i=0; i<item->path->num_points-1; i++, pt+=2) {
1675 cairo_move_to(cr, pt[0], pt[1]);
1676 cairo_set_line_width(cr, item->widths[i]);
1677 cairo_line_to(cr, pt[2], pt[3]);
1680 old_thickness = 0.0;
1683 if (item->type == ITEM_TEXT) {
1684 layout = gtk_print_context_create_pango_layout(context);
1685 font_desc = pango_font_description_from_string(item->font_name);
1686 if (item->font_size)
1687 pango_font_description_set_absolute_size(font_desc,
1688 item->font_size*PANGO_SCALE);
1689 pango_layout_set_font_description(layout, font_desc);
1690 pango_font_description_free(font_desc);
1691 pango_layout_set_text(layout, item->text, -1);
1692 cairo_move_to(cr, item->bbox.left, item->bbox.top);
1693 pango_cairo_show_layout(cr, layout);
1694 g_object_unref(layout);
1696 if (item->type == ITEM_IMAGE) {
1697 double scalex = (item->bbox.right-item->bbox.left)/gdk_pixbuf_get_width(item->image);
1698 double scaley = (item->bbox.bottom-item->bbox.top)/gdk_pixbuf_get_height(item->image);
1699 cairo_scale(cr, scalex, scaley);
1700 gdk_cairo_set_source_pixbuf(cr,item->image, item->bbox.left/scalex, item->bbox.top/scaley);
1701 cairo_scale(cr, 1/scalex, 1/scaley);
1703 old_rgba = predef_colors_rgba[COLOR_BLACK];
1704 cairo_set_source_rgb(cr, 0, 0, 0);