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 // manipulate Pdf fonts
792 struct PdfFont *new_pdffont(struct XrefTable *xref, GList **fonts,
793 char *filename, int font_id, FT_Face face, int glyph_page)
796 struct PdfFont *font;
800 for (list = *fonts; list!=NULL; list = list->next) {
801 font = (struct PdfFont *)list->data;
802 if (!strcmp(font->filename, filename) && font->font_id == font_id
803 && font->glyph_page == glyph_page)
804 { font->used_in_this_page = TRUE; return font; }
806 font = g_malloc(sizeof(struct PdfFont));
807 *fonts = g_list_append(*fonts, font);
808 font->n_obj = xref->last+1;
809 make_xref(xref, xref->last+1, 0); // will give it a value later
810 font->filename = g_strdup(filename);
811 font->font_id = font_id;
812 font->glyph_page = glyph_page;
813 font->used_in_this_page = TRUE;
814 font->num_glyphs_used = 0;
815 for (i=0; i<256; i++) {
816 font->glyphmap[i] = -1;
817 font->advance[i] = 0;
818 font->glyphpsnames[i] = NULL;
820 font->glyphmap[0] = 0;
821 // fill in info from the FT_Face
822 font->is_truetype = FT_IS_SFNT(face);
823 font->nglyphs = face->num_glyphs;
824 font->ft2ps = 1000.0 / face->units_per_EM;
825 font->ascender = (int)(font->ft2ps*face->ascender);
826 font->descender = (int)(font->ft2ps*face->descender);
827 if (face->bbox.xMin < -100000 || face->bbox.xMin > 100000) font->xmin = 0;
828 else font->xmin = (int)(font->ft2ps*face->bbox.xMin);
829 if (face->bbox.xMax < -100000 || face->bbox.xMax > 100000) font->xmax = 0;
830 else font->xmax = (int)(font->ft2ps*face->bbox.xMax);
831 if (face->bbox.yMin < -100000 || face->bbox.yMin > 100000) font->ymin = 0;
832 else font->ymin = (int)(font->ft2ps*face->bbox.yMin);
833 if (face->bbox.yMax < -100000 || face->bbox.yMax > 100000) font->ymax = 0;
834 else font->ymax = (int)(font->ft2ps*face->bbox.yMax);
835 if (font->is_truetype) font->flags = 4; // symbolic
837 font->flags = 4; // symbolic
838 if (FT_IS_FIXED_WIDTH(face)) font->flags |= 1;
839 if (face->style_flags & FT_STYLE_FLAG_ITALIC) font->flags |= 64;
841 s = FT_Get_Postscript_Name(face);
842 if (s==NULL) s = "Noname";
843 if (glyph_page) font->fontname = g_strdup_printf("%s_%03d", s, glyph_page);
844 else font->fontname = g_strdup(s);
848 #define pfb_get_length(x) (((x)[3]<<24) + ((x)[2]<<16) + ((x)[1]<<8) + (x)[0])
849 #define T1_SEGMENT_1_END "currentfile eexec"
850 #define T1_SEGMENT_3_END "cleartomark"
852 void embed_pdffont(GString *pdfbuf, struct XrefTable *xref, struct PdfFont *font)
854 // this code inspired by libgnomeprint
855 gboolean fallback, is_binary;
856 guchar encoding[256];
866 int nobj_fontprog, nobj_descr, lastchar;
869 // embed the font file: TrueType case
870 if (font->is_truetype) {
871 glyphs[0] = encoding[0] = 0;
873 for (i=1; i<=255; i++)
874 if (font->glyphmap[i]>=0) {
875 font->glyphmap[i] = num;
876 glyphs[num] = 255*font->glyph_page+i-1;
880 font->num_glyphs_used = num-1;
881 if (OpenTTFont(font->filename, 0, &ttfnt) == SF_OK) {
882 if (CreateTTFromTTGlyphs_tomemory(ttfnt, (guint8**)&fontdata, &tt_len, glyphs, encoding, num,
883 0, NULL, TTCF_AutoName | TTCF_IncludeOS2) == SF_OK) {
884 make_xref(xref, xref->last+1, pdfbuf->len);
885 nobj_fontprog = xref->last;
886 g_string_append_printf(pdfbuf,
887 "%d 0 obj\n<< /Length %u /Length1 %u >> stream\n",
888 nobj_fontprog, tt_len, tt_len);
889 g_string_append_len(pdfbuf, fontdata, tt_len);
890 g_string_append(pdfbuf, "endstream\nendobj\n");
893 else fallback = TRUE;
896 else fallback = TRUE;
898 // embed the font file: Type1 case
899 if (g_file_get_contents(font->filename, &fontdata, &t1_len, NULL) && t1_len>=8) {
900 if (fontdata[0]==(char)0x80 && fontdata[1]==(char)0x01) {
902 len1 = pfb_get_length((unsigned char *)fontdata+2);
903 if (fontdata[len1+6]!=(char)0x80 || fontdata[len1+7]!=(char)0x02) fallback = TRUE;
905 len2 = pfb_get_length((unsigned char *)fontdata+len1+8);
906 if (fontdata[len1+len2+12]!=(char)0x80 || fontdata[len1+len2+13]!=(char)0x01)
910 else if (!strncmp(fontdata, "%!PS", 4)) {
912 p = strstr(fontdata, T1_SEGMENT_1_END) + strlen(T1_SEGMENT_1_END);
913 if (p==NULL) fallback = TRUE;
915 if (*p=='\n' || *p=='\r') p++;
916 if (*p=='\n' || *p=='\r') p++;
918 p = g_strrstr_len(fontdata, t1_len, T1_SEGMENT_3_END);
919 if (p==NULL) fallback = TRUE;
923 while (i>0 && p!=fontdata && (*p=='0' || *p=='\r' || *p=='\n')) {
927 while (p!=fontdata && (*p=='\r' || *p=='\n')) p--;
929 if (i>0) fallback = TRUE;
930 else len2 = p-fontdata-len1;
934 else fallback = TRUE;
938 seg2 = fontdata + len1 + 12;
941 seg2 = g_malloc(len2/2);
944 while (p+1 < fontdata+len1+len2) {
945 if (*p==' '||*p=='\t'||*p=='\n'||*p=='\r') { p++; continue; }
946 if (p[0]>'9') { p[0]|=0x20; p[0]-=39; }
947 if (p[1]>'9') { p[1]|=0x20; p[1]-=39; }
948 seg2[j++] = ((p[0]-'0')<<4) + (p[1]-'0');
953 make_xref(xref, xref->last+1, pdfbuf->len);
954 nobj_fontprog = xref->last;
955 g_string_append_printf(pdfbuf,
956 "%d 0 obj\n<< /Length %u /Length1 %u /Length2 %u /Length3 0 >> stream\n",
957 nobj_fontprog, len1+len2, len1, len2);
958 g_string_append_len(pdfbuf, seg1, len1);
959 g_string_append_len(pdfbuf, seg2, len2);
960 g_string_append(pdfbuf, "endstream\nendobj\n");
961 if (!is_binary) g_free(seg2);
965 else fallback = TRUE;
968 // next, the font descriptor
970 make_xref(xref, xref->last+1, pdfbuf->len);
971 nobj_descr = xref->last;
972 g_string_append_printf(pdfbuf,
973 "%d 0 obj\n<< /Type /FontDescriptor /FontName /%s /Flags %d "
974 "/FontBBox [%d %d %d %d] /ItalicAngle 0 /Ascent %d "
975 "/Descent %d /CapHeight %d /StemV 100 /%s %d 0 R >> endobj\n",
976 nobj_descr, font->fontname, font->flags,
977 font->xmin, font->ymin, font->xmax, font->ymax,
978 font->ascender, -font->descender, font->ascender,
979 font->is_truetype ? "FontFile2":"FontFile",
983 // finally, the font itself
984 /* Note: in Type1 case, font->glyphmap maps charcodes to glyph no's
985 in TrueType case, encoding lists the used charcodes by index,
986 glyphs list the used glyph no's by index
987 font->glyphmap maps charcodes to indices */
988 xref->data[font->n_obj] = pdfbuf->len;
989 if (font->is_truetype) lastchar = encoding[font->num_glyphs_used];
990 else lastchar = font->num_glyphs_used;
992 font->is_truetype = FALSE;
993 g_free(font->fontname);
994 font->fontname = g_strdup("Helvetica");
997 if (font->is_truetype) {
998 num = font->glyph_page;
999 for (i=0; i<6; i++) { prefix[i] = 'A'+(num%26); num/=26; }
1000 prefix[6]='+'; prefix[7]=0;
1002 g_string_append_printf(pdfbuf,
1003 "%d 0 obj\n<< /Type /Font /Subtype /%s /BaseFont /%s%s /Name /F%d ",
1004 font->n_obj, font->is_truetype?"TrueType":"Type1",
1005 prefix, font->fontname, font->n_obj);
1007 g_string_append_printf(pdfbuf,
1008 "/FontDescriptor %d 0 R /FirstChar 0 /LastChar %d /Widths [",
1009 nobj_descr, lastchar);
1010 for (i=0; i<=lastchar; i++)
1011 g_string_append_printf(pdfbuf, "%d ", font->advance[i]);
1012 g_string_append(pdfbuf, "] ");
1014 if (!font->is_truetype) { /* encoding */
1015 g_string_append(pdfbuf, "/Encoding << /Type /Encoding "
1016 "/BaseEncoding /MacRomanEncoding /Differences [1 ");
1017 for (i=1; i<=lastchar; i++) {
1018 g_string_append_printf(pdfbuf, "/%s ", font->glyphpsnames[i]);
1019 g_free(font->glyphpsnames[i]);
1021 g_string_append(pdfbuf, "] >> ");
1023 g_string_append(pdfbuf, ">> endobj\n");
1026 // draw a page's graphics
1028 void pdf_draw_page(struct Page *pg, GString *str, gboolean *use_hiliter,
1029 struct XrefTable *xref, GList **pdffonts)
1031 GList *layerlist, *itemlist, *tmplist;
1034 guint old_rgba, old_text_rgba;
1035 double old_thickness;
1038 PangoFontDescription *font_desc;
1039 PangoContext *context;
1040 PangoLayout *layout;
1041 PangoLayoutIter *iter;
1042 PangoRectangle logical_rect;
1043 PangoLayoutRun *run;
1044 PangoFcFont *fcfont;
1045 PangoFontMap *fontmap;
1047 int baseline, advance;
1048 int glyph_no, glyph_page, current_page;
1053 struct PdfFont *cur_font;
1056 old_rgba = old_text_rgba = 0x12345678; // not any values we use, so we'll reset them
1057 old_thickness = 0.0;
1058 for (tmplist = *pdffonts; tmplist!=NULL; tmplist = tmplist->next) {
1059 cur_font = (struct PdfFont *)tmplist->data;
1060 cur_font->used_in_this_page = FALSE;
1063 for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1064 l = (struct Layer *)layerlist->data;
1065 for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1066 item = (struct Item *)itemlist->data;
1067 if (item->type == ITEM_STROKE) {
1068 if ((item->brush.color_rgba & ~0xff) != old_rgba)
1069 g_string_append_printf(str, "%.2f %.2f %.2f RG ",
1070 RGBA_RGB(item->brush.color_rgba));
1071 if (item->brush.thickness != old_thickness)
1072 g_string_append_printf(str, "%.2f w ", item->brush.thickness);
1073 if ((item->brush.color_rgba & 0xf0) != 0xf0) { // transparent
1074 g_string_append(str, "q /XoHi gs ");
1075 *use_hiliter = TRUE;
1077 old_rgba = item->brush.color_rgba & ~0xff;
1078 old_thickness = item->brush.thickness;
1079 pt = item->path->coords;
1080 if (!item->brush.variable_width) {
1081 g_string_append_printf(str, "%.2f %.2f m ", pt[0], pt[1]);
1082 for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1083 g_string_append_printf(str, "%.2f %.2f l ", pt[0], pt[1]);
1084 g_string_append_printf(str,"S\n");
1085 old_thickness = item->brush.thickness;
1087 for (i=0; i<item->path->num_points-1; i++, pt+=2)
1088 g_string_append_printf(str, "%.2f w %.2f %.2f m %.2f %.2f l S\n",
1089 item->widths[i], pt[0], pt[1], pt[2], pt[3]);
1090 old_thickness = 0.0;
1092 if ((item->brush.color_rgba & 0xf0) != 0xf0) // undo transparent
1093 g_string_append(str, "Q ");
1095 else if (item->type == ITEM_TEXT) {
1096 if ((item->brush.color_rgba & ~0xff) != old_text_rgba)
1097 g_string_append_printf(str, "%.2f %.2f %.2f rg ",
1098 RGBA_RGB(item->brush.color_rgba));
1099 old_text_rgba = item->brush.color_rgba & ~0xff;
1100 fontmap = pango_ft2_font_map_new();
1101 pango_ft2_font_map_set_resolution(PANGO_FT2_FONT_MAP (fontmap), 72, 72);
1102 context = pango_context_new();
1103 pango_context_set_font_map(context, fontmap);
1104 layout = pango_layout_new(context);
1105 g_object_unref(fontmap);
1106 g_object_unref(context);
1107 font_desc = pango_font_description_from_string(item->font_name);
1108 pango_font_description_set_absolute_size(font_desc,
1109 item->font_size*PANGO_SCALE);
1110 pango_layout_set_font_description(layout, font_desc);
1111 pango_font_description_free(font_desc);
1112 pango_layout_set_text(layout, item->text, -1);
1113 // this code inspired by the code in libgnomeprint
1114 iter = pango_layout_get_iter(layout);
1116 run = pango_layout_iter_get_run(iter);
1117 if (run==NULL) continue;
1118 pango_layout_iter_get_run_extents (iter, NULL, &logical_rect);
1119 baseline = pango_layout_iter_get_baseline (iter);
1120 if (!PANGO_IS_FC_FONT(run->item->analysis.font)) continue;
1121 fcfont = PANGO_FC_FONT(run->item->analysis.font);
1122 pattern = fcfont->font_pattern;
1123 if (FcPatternGetString(pattern, FC_FILE, 0, (unsigned char **)&filename) != FcResultMatch ||
1124 FcPatternGetInteger(pattern, FC_INDEX, 0, &font_id) != FcResultMatch)
1126 ftface = pango_fc_font_lock_face(fcfont);
1129 g_string_append_printf(str, "BT %.2f 0 0 %.2f %.2f %.2f Tm ",
1130 item->font_size, -item->font_size,
1131 item->bbox.left + (gdouble) logical_rect.x/PANGO_SCALE,
1132 item->bbox.top + (gdouble) baseline/PANGO_SCALE);
1134 for (i=0; i<run->glyphs->num_glyphs; i++) {
1135 glyph_no = run->glyphs->glyphs[i].glyph;
1136 if (FT_IS_SFNT(ftface)) glyph_page = glyph_no/255;
1137 else glyph_page = 0;
1138 if (glyph_page != current_page) {
1139 cur_font = new_pdffont(xref, pdffonts, filename, font_id,
1140 ftface, glyph_page);
1141 if (in_string) g_string_append(str, ") Tj ");
1143 g_string_append_printf(str, "/F%d 1 Tf ", cur_font->n_obj);
1145 current_page = glyph_page;
1146 FT_Load_Glyph(ftface, glyph_no, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM);
1147 advance = (int)(ftface->glyph->metrics.horiAdvance * cur_font->ft2ps + 0.5);
1148 if (!in_string) g_string_append_c(str, '(');
1150 if (cur_font->is_truetype) {
1151 if (glyph_no) glyph_no = (glyph_no%255)+1;
1152 cur_font->glyphmap[glyph_no] = glyph_no;
1155 for (j=1; j<=cur_font->num_glyphs_used; j++)
1156 if (cur_font->glyphmap[j] == glyph_no) break;
1157 if (j==256) j=0; // font is full, what do we do?
1158 if (j>cur_font->num_glyphs_used) {
1159 cur_font->glyphmap[j] = glyph_no;
1160 cur_font->num_glyphs_used++;
1161 if (FT_Get_Glyph_Name(ftface, glyph_no, tmpstr, 200) == FT_Err_Ok)
1162 cur_font->glyphpsnames[j] = g_strdup(tmpstr);
1163 else cur_font->glyphpsnames[j] = g_strdup(".notdef");
1167 cur_font->advance[glyph_no] = advance;
1168 if (glyph_no=='\\' || glyph_no == '(' || glyph_no == ')' || glyph_no == 10 || glyph_no == 13)
1169 g_string_append_c(str, '\\');
1170 if (glyph_no==10) g_string_append_c(str,'n');
1171 else if (glyph_no==13) g_string_append_c(str,'r');
1172 else g_string_append_c(str, glyph_no);
1174 if (in_string) g_string_append(str, ") Tj ");
1175 g_string_append(str, "ET ");
1176 pango_fc_font_unlock_face(fcfont);
1177 } while (pango_layout_iter_next_run(iter));
1178 pango_layout_iter_free(iter);
1179 g_object_unref(layout);
1185 // main printing function
1187 /* we use the following object numbers, starting with n_obj_catalog:
1188 0 the document catalog
1190 2 the GS for the hiliters
1191 3 ... the page objects
1194 gboolean print_to_pdf(char *filename)
1197 GString *pdfbuf, *pgstrm, *zpgstrm, *tmpstr;
1198 int n_obj_catalog, n_obj_pages_offs, n_page, n_obj_bgpix, n_obj_prefix;
1200 struct XrefTable xref;
1203 gboolean annot, uses_pdf;
1204 gboolean use_hiliter;
1205 struct PdfInfo pdfinfo;
1207 GList *pdffonts, *list;
1208 struct PdfFont *font;
1211 f = fopen(filename, "wb");
1212 if (f == NULL) return FALSE;
1213 setlocale(LC_NUMERIC, "C");
1218 for (pglist = journal.pages; pglist!=NULL; pglist = pglist->next) {
1219 pg = (struct Page *)pglist->data;
1220 if (pg->bg->type == BG_PDF) uses_pdf = TRUE;
1223 if (uses_pdf && bgpdf.status != STATUS_NOT_INIT &&
1224 bgpdf.file_contents!=NULL && !strncmp(bgpdf.file_contents, "%PDF-1.", 7)) {
1225 // parse the existing PDF file
1226 pdfbuf = g_string_new_len(bgpdf.file_contents, bgpdf.file_length);
1227 if (pdfbuf->str[7]<'4') pdfbuf->str[7] = '4'; // upgrade to 1.4
1228 annot = pdf_parse_info(pdfbuf, &pdfinfo, &xref);
1230 g_string_free(pdfbuf, TRUE);
1231 if (xref.data != NULL) g_free(xref.data);
1236 pdfbuf = g_string_new("%PDF-1.4\n%\370\357\365\362\n");
1237 xref.n_alloc = xref.last = 0;
1241 // catalog and page tree
1242 n_obj_catalog = xref.last+1;
1243 n_obj_pages_offs = xref.last+4;
1244 make_xref(&xref, n_obj_catalog, pdfbuf->len);
1245 g_string_append_printf(pdfbuf,
1246 "%d 0 obj\n<< /Type /Catalog /Pages %d 0 R >> endobj\n",
1247 n_obj_catalog, n_obj_catalog+1);
1248 make_xref(&xref, n_obj_catalog+1, pdfbuf->len);
1249 g_string_append_printf(pdfbuf,
1250 "%d 0 obj\n<< /Type /Pages /Kids [", n_obj_catalog+1);
1251 for (i=0;i<journal.npages;i++)
1252 g_string_append_printf(pdfbuf, "%d 0 R ", n_obj_pages_offs+i);
1253 g_string_append_printf(pdfbuf, "] /Count %d >> endobj\n", journal.npages);
1254 make_xref(&xref, n_obj_catalog+2, pdfbuf->len);
1255 g_string_append_printf(pdfbuf,
1256 "%d 0 obj\n<< /Type /ExtGState /CA %.2f >> endobj\n",
1257 n_obj_catalog+2, ui.hiliter_opacity);
1258 xref.last = n_obj_pages_offs + journal.npages-1;
1260 for (pglist = journal.pages, n_page = 0; pglist!=NULL;
1261 pglist = pglist->next, n_page++) {
1262 pg = (struct Page *)pglist->data;
1264 // draw the background and page into pgstrm
1265 pgstrm = g_string_new("");
1266 g_string_printf(pgstrm, "q 1 0 0 -1 0 %.2f cm 1 J 1 j ", pg->height);
1269 if (pg->bg->type == BG_SOLID)
1270 pdf_draw_solid_background(pg, pgstrm);
1271 else if (pg->bg->type == BG_PDF && annot &&
1272 pdfinfo.pages[pg->bg->file_page_seq-1].contents!=NULL) {
1273 make_xref(&xref, xref.last+1, pdfbuf->len);
1274 n_obj_prefix = xref.last;
1275 tmpstr = make_pdfprefix(pdfinfo.pages+(pg->bg->file_page_seq-1),
1276 pg->width, pg->height);
1277 g_string_append_printf(pdfbuf,
1278 "%d 0 obj\n<< /Length %zu >> stream\n%s\nendstream\nendobj\n",
1279 n_obj_prefix, tmpstr->len, tmpstr->str);
1280 g_string_free(tmpstr, TRUE);
1281 g_string_prepend(pgstrm, "Q Q Q ");
1283 else if (pg->bg->type == BG_PIXMAP || pg->bg->type == BG_PDF)
1284 n_obj_bgpix = pdf_draw_bitmap_background(pg, pgstrm, &xref, pdfbuf);
1285 // draw the page contents
1286 use_hiliter = FALSE;
1287 pdf_draw_page(pg, pgstrm, &use_hiliter, &xref, &pdffonts);
1288 g_string_append_printf(pgstrm, "Q\n");
1290 // deflate pgstrm and write it
1291 zpgstrm = do_deflate(pgstrm->str, pgstrm->len);
1292 g_string_free(pgstrm, TRUE);
1294 make_xref(&xref, xref.last+1, pdfbuf->len);
1295 g_string_append_printf(pdfbuf,
1296 "%d 0 obj\n<< /Length %zu /Filter /FlateDecode>> stream\n",
1297 xref.last, zpgstrm->len);
1298 g_string_append_len(pdfbuf, zpgstrm->str, zpgstrm->len);
1299 g_string_free(zpgstrm, TRUE);
1300 g_string_append(pdfbuf, "endstream\nendobj\n");
1302 // write the page object
1304 make_xref(&xref, n_obj_pages_offs+n_page, pdfbuf->len);
1305 g_string_append_printf(pdfbuf,
1306 "%d 0 obj\n<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %.2f %.2f] ",
1307 n_obj_pages_offs+n_page, n_obj_catalog+1, pg->width, pg->height);
1308 if (n_obj_prefix>0) {
1309 obj = get_pdfobj(pdfbuf, &xref, pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1310 if (obj->type != PDFTYPE_ARRAY) {
1312 obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1314 g_string_append_printf(pdfbuf, "/Contents [%d 0 R ", n_obj_prefix);
1315 if (obj->type == PDFTYPE_REF)
1316 g_string_append_printf(pdfbuf, "%d %d R ", obj->intval, obj->num);
1317 if (obj->type == PDFTYPE_ARRAY) {
1318 for (i=0; i<obj->num; i++) {
1319 show_pdfobj(obj->elts[i], pdfbuf);
1320 g_string_append_c(pdfbuf, ' ');
1324 g_string_append_printf(pdfbuf, "%d 0 R] ", xref.last);
1326 else g_string_append_printf(pdfbuf, "/Contents %d 0 R ", xref.last);
1327 g_string_append(pdfbuf, "/Resources ");
1330 obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].resources);
1332 if (obj!=NULL && obj->type!=PDFTYPE_DICT)
1333 { free_pdfobj(obj); obj=NULL; }
1335 obj = g_malloc(sizeof(struct PdfObj));
1336 obj->type = PDFTYPE_DICT;
1341 add_dict_subentry(pdfbuf, &xref,
1342 obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/PDF"));
1344 add_dict_subentry(pdfbuf, &xref,
1345 obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/ImageC"));
1347 add_dict_subentry(pdfbuf, &xref,
1348 obj, "/ExtGState", PDFTYPE_DICT, "/XoHi", mk_pdfref(n_obj_catalog+2));
1350 add_dict_subentry(pdfbuf, &xref,
1351 obj, "/XObject", PDFTYPE_DICT, "/ImBg", mk_pdfref(n_obj_bgpix));
1352 for (list=pdffonts; list!=NULL; list = list->next) {
1353 font = (struct PdfFont *)list->data;
1354 if (font->used_in_this_page) {
1355 add_dict_subentry(pdfbuf, &xref,
1356 obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/Text"));
1357 tmpbuf = g_strdup_printf("/F%d", font->n_obj);
1358 add_dict_subentry(pdfbuf, &xref,
1359 obj, "/Font", PDFTYPE_DICT, tmpbuf, mk_pdfref(font->n_obj));
1363 show_pdfobj(obj, pdfbuf);
1365 g_string_append(pdfbuf, " >> endobj\n");
1368 // after the pages, we insert fonts
1369 for (list = pdffonts; list!=NULL; list = list->next) {
1370 font = (struct PdfFont *)list->data;
1371 embed_pdffont(pdfbuf, &xref, font);
1372 g_free(font->filename);
1373 g_free(font->fontname);
1376 g_list_free(pdffonts);
1379 startxref = pdfbuf->len;
1380 if (annot) g_string_append_printf(pdfbuf,
1381 "xref\n%d %d\n", n_obj_catalog, xref.last-n_obj_catalog+1);
1382 else g_string_append_printf(pdfbuf,
1383 "xref\n0 %d\n0000000000 65535 f \n", xref.last+1);
1384 for (i=n_obj_catalog; i<=xref.last; i++)
1385 g_string_append_printf(pdfbuf, "%010d 00000 n \n", xref.data[i]);
1386 g_string_append_printf(pdfbuf,
1387 "trailer\n<< /Size %d /Root %d 0 R ", xref.last+1, n_obj_catalog);
1389 g_string_append_printf(pdfbuf, "/Prev %d ", pdfinfo.startxref);
1390 // keeping encryption info somehow doesn't work.
1391 // xournal can't annotate encrypted PDFs anyway...
1393 obj = get_dict_entry(pdfinfo.trailerdict, "/Encrypt");
1395 g_string_append_printf(pdfbuf, "/Encrypt ");
1396 show_pdfobj(obj, pdfbuf);
1400 g_string_append_printf(pdfbuf,
1401 ">>\nstartxref\n%d\n%%%%EOF\n", startxref);
1405 free_pdfobj(pdfinfo.trailerdict);
1406 if (pdfinfo.pages!=NULL)
1407 for (i=0; i<pdfinfo.npages; i++) {
1408 free_pdfobj(pdfinfo.pages[i].resources);
1409 free_pdfobj(pdfinfo.pages[i].mediabox);
1410 free_pdfobj(pdfinfo.pages[i].contents);
1414 setlocale(LC_NUMERIC, "");
1415 if (fwrite(pdfbuf->str, 1, pdfbuf->len, f) < pdfbuf->len) {
1417 g_string_free(pdfbuf, TRUE);
1421 g_string_free(pdfbuf, TRUE);
1425 /*********** Printing via gtk-print **********/
1427 #if GTK_CHECK_VERSION(2, 10, 0)
1429 // does the same job as update_canvas_bg(), but to a print context
1431 void print_background(cairo_t *cr, struct Page *pg)
1436 PopplerPage *pdfpage;
1437 cairo_surface_t *cr_pixbuf;
1438 double pgwidth, pgheight;
1440 if (pg->bg->type == BG_SOLID) {
1441 cairo_set_source_rgb(cr, RGBA_RGB(pg->bg->color_rgba));
1442 cairo_rectangle(cr, 0, 0, pg->width, pg->height);
1444 if (!ui.print_ruling) return;
1445 if (pg->bg->ruling == RULING_NONE) return;
1446 cairo_set_source_rgb(cr, RGBA_RGB(RULING_COLOR));
1447 cairo_set_line_width(cr, RULING_THICKNESS);
1449 if (pg->bg->ruling == RULING_GRAPH) {
1450 for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
1451 { cairo_move_to(cr, x, 0); cairo_line_to(cr, x, pg->height); }
1452 for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
1453 { cairo_move_to(cr, 0, y); cairo_line_to(cr, pg->width, y); }
1458 for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
1459 { cairo_move_to(cr, 0, y); cairo_line_to(cr, pg->width, y); }
1461 if (pg->bg->ruling == RULING_LINED) {
1462 cairo_set_source_rgb(cr, RGBA_RGB(RULING_MARGIN_COLOR));
1463 cairo_move_to(cr, RULING_LEFTMARGIN, 0);
1464 cairo_line_to(cr, RULING_LEFTMARGIN, pg->height);
1470 if (pg->bg->type == BG_PDF) {
1471 if (!bgpdf.document) return;
1472 pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
1473 if (!pdfpage) return;
1474 poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
1476 cairo_scale(cr, pg->width/pgwidth, pg->height/pgheight);
1477 poppler_page_render(pdfpage, cr);
1479 g_object_unref(pdfpage);
1482 if (pg->bg->type == BG_PIXMAP) {
1484 cairo_scale(cr, pg->width/gdk_pixbuf_get_width(pg->bg->pixbuf),
1485 pg->height/gdk_pixbuf_get_height(pg->bg->pixbuf));
1486 gdk_cairo_set_source_pixbuf(cr, pg->bg->pixbuf, 0, 0);
1487 cairo_rectangle(cr, 0, 0, gdk_pixbuf_get_width(pg->bg->pixbuf), gdk_pixbuf_get_height(pg->bg->pixbuf));
1493 void print_job_render_page(GtkPrintOperation *print, GtkPrintContext *context, gint pageno, gpointer user_data)
1496 gdouble width, height, scale;
1499 double old_thickness;
1500 GList *layerlist, *itemlist;
1505 PangoFontDescription *font_desc;
1506 PangoLayout *layout;
1508 pg = (struct Page *)g_list_nth_data(journal.pages, pageno);
1509 cr = gtk_print_context_get_cairo_context(context);
1510 width = gtk_print_context_get_width(context);
1511 height = gtk_print_context_get_height(context);
1512 scale = MIN(width/pg->width, height/pg->height);
1514 cairo_translate(cr, (width-scale*pg->width)/2, (height-scale*pg->height)/2);
1515 cairo_scale(cr, scale, scale);
1516 cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
1517 cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND);
1519 print_background(cr, pg);
1521 old_rgba = predef_colors_rgba[COLOR_BLACK];
1522 cairo_set_source_rgb(cr, 0, 0, 0);
1523 old_thickness = 0.0;
1525 for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1526 l = (struct Layer *)layerlist->data;
1527 for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1528 item = (struct Item *)itemlist->data;
1529 if (item->type == ITEM_STROKE || item->type == ITEM_TEXT) {
1530 if (item->brush.color_rgba != old_rgba)
1531 cairo_set_source_rgba(cr, RGBA_RGB(item->brush.color_rgba),
1532 RGBA_ALPHA(item->brush.color_rgba));
1533 old_rgba = item->brush.color_rgba;
1535 if (item->type == ITEM_STROKE) {
1536 if (item->brush.thickness != old_thickness)
1537 cairo_set_line_width(cr, item->brush.thickness);
1538 pt = item->path->coords;
1539 if (!item->brush.variable_width) {
1540 cairo_move_to(cr, pt[0], pt[1]);
1541 for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1542 cairo_line_to(cr, pt[0], pt[1]);
1544 old_thickness = item->brush.thickness;
1546 for (i=0; i<item->path->num_points-1; i++, pt+=2) {
1547 cairo_move_to(cr, pt[0], pt[1]);
1548 cairo_set_line_width(cr, item->widths[i]);
1549 cairo_line_to(cr, pt[2], pt[3]);
1552 old_thickness = 0.0;
1555 if (item->type == ITEM_TEXT) {
1556 layout = gtk_print_context_create_pango_layout(context);
1557 font_desc = pango_font_description_from_string(item->font_name);
1558 if (item->font_size)
1559 pango_font_description_set_absolute_size(font_desc,
1560 item->font_size*PANGO_SCALE);
1561 pango_layout_set_font_description(layout, font_desc);
1562 pango_font_description_free(font_desc);
1563 pango_layout_set_text(layout, item->text, -1);
1564 cairo_move_to(cr, item->bbox.left, item->bbox.top);
1565 pango_cairo_show_layout(cr, layout);
1566 g_object_unref(layout);