]> git.donarmstrong.com Git - xournal.git/blob - src/xo-print.c
Image patch
[xournal.git] / src / xo-print.c
1 /*
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.
6  *
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.
11  *
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/>.
14  */
15
16 #ifdef HAVE_CONFIG_H
17 #  include <config.h>
18 #endif
19
20 #define PANGO_ENABLE_BACKEND /* to access PangoFcFont.font_pattern */
21
22 #include <gtk/gtk.h>
23 #include <libgnomecanvas/libgnomecanvas.h>
24 #include <zlib.h>
25 #include <string.h>
26 #include <locale.h>
27 #include <pango/pango.h>
28 #include <pango/pangofc-font.h>
29 #include <pango/pangoft2.h>
30 #include <fontconfig/fontconfig.h>
31 #include <ft2build.h>
32 #include FT_FREETYPE_H
33
34 #define NO_MAPPERS
35 #define NO_TYPE3
36 #define NO_TYPE42
37 #include "ttsubset/sft.h"
38
39 #include "xournal.h"
40 #include "xo-support.h"
41 #include "xo-misc.h"
42 #include "xo-paint.h"
43 #include "xo-print.h"
44 #include "xo-file.h"
45
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)
51
52 /*********** Printing to PDF ************/
53
54 gboolean ispdfspace(char c)
55 {
56   return (c==0 || c==9 || c==10 || c==12 || c==13 || c==' ');
57 }
58
59 gboolean ispdfdelim(char c)
60 {
61   return (c=='(' || c==')' || c=='<' || c=='>' || c=='[' || c==']' ||
62           c=='{' || c=='}' || c=='/' || c=='%');
63 }
64
65 void skipspace(char **p, char *eof)
66 {
67   while (ispdfspace(**p) || **p=='%') {
68     if (**p=='%') while (*p!=eof && **p!=10 && **p!=13) (*p)++;
69     if (*p==eof) return;
70     (*p)++;
71   }
72 }
73
74 void free_pdfobj(struct PdfObj *obj)
75 {
76   int i;
77   
78   if (obj==NULL) return;
79   if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
80       obj->type == PDFTYPE_STREAM) && obj->str!=NULL)
81     g_free(obj->str);
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]);
86     g_free(obj->elts);
87   }
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]);
91     g_free(obj->names);
92   }
93   g_free(obj);
94 }
95
96 struct PdfObj *dup_pdfobj(struct PdfObj *obj)
97 {
98   struct PdfObj *dup;
99   int i;
100   
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);
107   }
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]);
113   }
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]);
118   }
119   return dup;
120 }
121
122 void show_pdfobj(struct PdfObj *obj, GString *str)
123 {
124   int i;
125   if (obj==NULL) return;
126   switch(obj->type) {
127     case PDFTYPE_CST:
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");
131       break;
132     case PDFTYPE_INT:
133       g_string_append_printf(str, "%d", obj->intval);
134       break;
135     case PDFTYPE_REAL:
136       g_string_append_printf(str, "%f", obj->realval);
137       break;
138     case PDFTYPE_STRING:
139       g_string_append_len(str, obj->str, obj->len);
140       break;
141     case PDFTYPE_NAME:
142       g_string_append(str, obj->str);
143       break;
144     case PDFTYPE_ARRAY:
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);
149       }
150       g_string_append_c(str, ']');
151       break;
152     case PDFTYPE_DICT:
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);
157       }
158       g_string_append(str, " >>");
159       break;
160     case PDFTYPE_REF:
161       g_string_append_printf(str, "%d %d R", obj->intval, obj->num);
162       break;
163   }
164 }
165
166 void DEBUG_PRINTOBJ(struct PdfObj *obj)
167 {
168   GString *s = g_string_new("");
169   show_pdfobj(obj, s);
170   puts(s->str);
171   g_string_free(s, TRUE);
172 }
173
174 // parse a PDF object; returns NULL if fails
175 // THIS PARSER DOES NOT RECOGNIZE STREAMS YET
176
177 struct PdfObj *parse_pdf_object(char **ptr, char *eof)
178 {
179   struct PdfObj *obj, *elt;
180   char *p, *q, *r, *eltname;
181   int stack;
182
183   obj = g_malloc(sizeof(struct PdfObj));
184   p = *ptr;
185   skipspace(&p, eof);
186   if (p==eof) { g_free(obj); return NULL; }
187   
188   // maybe a constant
189   if (!strncmp(p, "true", 4)) {
190     obj->type = PDFTYPE_CST;
191     obj->intval = 1;
192     *ptr = p+4;
193     return obj;
194   }
195   if (!strncmp(p, "false", 5)) {
196     obj->type = PDFTYPE_CST;
197     obj->intval = 0;
198     *ptr = p+5;
199     return obj;
200   }
201   if (!strncmp(p, "null", 4)) {
202     obj->type = PDFTYPE_CST;
203     obj->intval = -1;
204     *ptr = p+4;
205     return obj;
206   }
207
208   // or a number ?
209   obj->intval = strtol(p, &q, 10);
210   *ptr = q;
211   if (q!=p) {
212     if (*q == '.') {
213       obj->type = PDFTYPE_REAL;
214       obj->realval = g_ascii_strtod(p, ptr);
215       return obj;
216     }
217     if (ispdfspace(*q)) {
218       // check for indirect reference
219       skipspace(&q, eof);
220       obj->num = strtol(q, &r, 10);
221       if (r!=q) {
222         skipspace(&r, eof);
223         if (*r=='R') {
224           *ptr = r+1;
225           obj->type = PDFTYPE_REF;
226           return obj;
227         }
228       }
229     }
230     obj->type = PDFTYPE_INT;
231     return obj;
232   }
233
234   // a string ?
235   if (*p=='(') {
236     q=p+1; stack=1;
237     while (stack>0 && q!=eof) {
238       if (*q=='(') stack++;
239       if (*q==')') stack--;
240       if (*q=='\\') q++;
241       if (q!=eof) q++;
242     }
243     if (q==eof) { g_free(obj); return NULL; }
244     obj->type = PDFTYPE_STRING;
245     obj->len = q-p;
246     obj->str = g_malloc(obj->len+1);
247     obj->str[obj->len] = 0;
248     g_memmove(obj->str, p, obj->len);
249     *ptr = q;
250     return obj;
251   }  
252   if (*p=='<' && p[1]!='<') {
253     q=p+1;
254     while (*q!='>' && q!=eof) q++;
255     if (q==eof) { g_free(obj); return NULL; }
256     q++;
257     obj->type = PDFTYPE_STRING;
258     obj->len = q-p;
259     obj->str = g_malloc(obj->len+1);
260     obj->str[obj->len] = 0;
261     g_memmove(obj->str, p, obj->len);
262     *ptr = q;
263     return obj;
264   }
265   
266   // a name ?
267   if (*p=='/') {
268     q=p+1;
269     while (!ispdfspace(*q) && !ispdfdelim(*q)) q++;
270     obj->type = PDFTYPE_NAME;
271     obj->str = g_strndup(p, q-p);
272     *ptr = q;
273     return obj;
274   }
275
276   // an array ?
277   if (*p=='[') {
278     obj->type = PDFTYPE_ARRAY;
279     obj->num = 0;
280     obj->elts = NULL;
281     q=p+1; skipspace(&q, eof);
282     while (*q!=']') {
283       elt = parse_pdf_object(&q, eof);
284       if (elt==NULL) { free_pdfobj(obj); return NULL; }
285       obj->num++;
286       obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
287       obj->elts[obj->num-1] = elt;
288       skipspace(&q, eof);
289     }
290     *ptr = q+1;
291     return obj;
292   }
293
294   // a dictionary ?
295   if (*p=='<' && p[1]=='<') {
296     obj->type = PDFTYPE_DICT;
297     obj->num = 0;
298     obj->elts = NULL;
299     obj->names = NULL;
300     q=p+2; skipspace(&q, eof);
301     while (*q!='>' || q[1]!='>') {
302       if (*q!='/') { free_pdfobj(obj); return NULL; }
303       r=q+1;
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; }
309       obj->num++;
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;
314       skipspace(&q, eof);
315     }
316     *ptr = q+2;
317     return obj;
318   }
319
320   // DOES NOT RECOGNIZE STREAMS YET (handle as subcase of dictionary)
321   
322   g_free(obj);
323   return NULL;
324 }
325
326 struct PdfObj *get_dict_entry(struct PdfObj *dict, char *name)
327 {
328   int i;
329   
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];
334   return NULL;
335 }
336
337 struct PdfObj *get_pdfobj(GString *pdfbuf, struct XrefTable *xref, struct PdfObj *obj)
338 {
339   char *p, *eof;
340   int offs, n;
341
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;
347
348   p = pdfbuf->str + offs;
349   eof = pdfbuf->str + pdfbuf->len;
350   n = strtol(p, &p, 10);
351   if (n!=obj->intval) return NULL;
352   skipspace(&p, eof);
353   n = strtol(p, &p, 10);
354   skipspace(&p, eof);
355   if (strncmp(p, "obj", 3)) return NULL;
356   p+=3;
357   return parse_pdf_object(&p, eof);
358 }
359
360 // read the xref table of a PDF file in memory, and return the trailerdict
361
362 struct PdfObj *parse_xref_table(GString *pdfbuf, struct XrefTable *xref, int offs)
363 {
364   char *p, *eof;
365   struct PdfObj *trailerdict, *obj;
366   int start, len, i;
367   
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;
372   p+=8;
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);
381     free_pdfobj(obj);
382   }
383   p = pdfbuf->str+offs+4;
384   skipspace(&p, eof);
385   if (*p<'0' || *p>'9') { free_pdfobj(trailerdict); return NULL; }
386   while (*p>='0' && *p<='9') {
387     start = strtol(p, &p, 10);
388     skipspace(&p, eof);
389     len = strtol(p, &p, 10);
390     skipspace(&p, eof);
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);
395       p+=20;
396     }
397     skipspace(&p, eof);
398   }
399   if (*p!='t') { free_pdfobj(trailerdict); return NULL; }
400   return trailerdict;
401 }
402
403 // parse the page tree
404
405 int pdf_getpageinfo(GString *pdfbuf, struct XrefTable *xref, 
406                 struct PdfObj *pgtree, int nmax, struct PdfPageDesc *pages)
407 {
408   struct PdfObj *obj, *kid;
409   int i, count, j;
410   
411   obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Type"));
412   if (obj == NULL || obj->type != PDFTYPE_NAME)
413     return 0;
414   if (!strcmp(obj->str, "/Page")) {
415     free_pdfobj(obj);
416     pages->contents = dup_pdfobj(get_dict_entry(pgtree, "/Contents"));
417     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
418     if (obj!=NULL) {
419       free_pdfobj(pages->resources);
420       pages->resources = obj;
421     }
422     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
423     if (obj!=NULL) {
424       free_pdfobj(pages->mediabox);
425       pages->mediabox = obj;
426     }
427     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
428     if (obj!=NULL && obj->type == PDFTYPE_INT)
429       pages->rotate = obj->intval;
430     free_pdfobj(obj);
431     return 1;
432   }
433   else if (!strcmp(obj->str, "/Pages")) {
434     free_pdfobj(obj);
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;
438     else count = 0;
439     free_pdfobj(obj);
440     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
441     if (obj!=NULL)
442       for (i=0; i<count; i++) {
443         free_pdfobj(pages[i].resources);
444         pages[i].resources = dup_pdfobj(obj);
445       }
446     free_pdfobj(obj);
447     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
448     if (obj!=NULL)
449       for (i=0; i<count; i++) {
450         free_pdfobj(pages[i].mediabox);
451         pages[i].mediabox = dup_pdfobj(obj);
452       }
453     free_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;
458     free_pdfobj(obj);
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]);
463         if (kid!=NULL) {
464           j = pdf_getpageinfo(pdfbuf, xref, kid, nmax, pages);
465           nmax -= j;
466           pages += j;
467           free_pdfobj(kid);
468         }
469       }
470     }
471     free_pdfobj(obj);
472     return count;
473   }
474   return 0;
475 }
476
477 // parse a PDF file in memory
478
479 gboolean pdf_parse_info(GString *pdfbuf, struct PdfInfo *pdfinfo, struct XrefTable *xref)
480 {
481   char *p;
482   int offs;
483   struct PdfObj *obj, *pages;
484
485   xref->n_alloc = xref->last = 0;
486   xref->data = NULL;
487   p = pdfbuf->str + pdfbuf->len-1;
488   
489   while (*p!='s' && p!=pdfbuf->str) p--;
490   if (strncmp(p, "startxref", 9)) return FALSE; // fail
491   p+=9;
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;
496   
497   pdfinfo->trailerdict = parse_xref_table(pdfbuf, xref, offs);
498   if (pdfinfo->trailerdict == NULL) return FALSE; // fail
499   
500   obj = get_pdfobj(pdfbuf, xref,
501      get_dict_entry(pdfinfo->trailerdict, "/Root"));
502   if (obj == NULL)
503     { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
504   pages = get_pdfobj(pdfbuf, xref, get_dict_entry(obj, "/Pages"));
505   free_pdfobj(obj);
506   if (pages == NULL)
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;
513   free_pdfobj(obj);
514   
515   pdfinfo->pages = g_malloc0(pdfinfo->npages*sizeof(struct PdfPageDesc));
516   pdf_getpageinfo(pdfbuf, xref, pages, pdfinfo->npages, pdfinfo->pages);
517   free_pdfobj(pages);
518   
519   return TRUE;
520 }
521
522 // add an entry to the xref table
523
524 void make_xref(struct XrefTable *xref, int nobj, int offset)
525 {
526   if (xref->n_alloc <= nobj) {
527     xref->n_alloc = nobj + 10;
528     xref->data = g_realloc(xref->data, xref->n_alloc*sizeof(int));
529   }
530   if (xref->last < nobj) xref->last = nobj;
531   xref->data[nobj] = offset;
532 }
533
534 // a wrapper for deflate
535
536 GString *do_deflate(char *in, int len)
537 {
538   GString *out;
539   z_stream zs;
540   
541   zs.zalloc = Z_NULL;
542   zs.zfree = Z_NULL;
543   deflateInit(&zs, Z_DEFAULT_COMPRESSION);
544   zs.next_in = (Bytef *)in;
545   zs.avail_in = len;
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;
551   deflateEnd(&zs);
552   return out;
553 }
554
555 // prefix to scale the original page
556
557 GString *make_pdfprefix(struct PdfPageDesc *pgdesc, double width, double height)
558 {
559   GString *str;
560   double v[4], t, xscl, yscl;
561   int i;
562
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;
568   }
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;
572   }
573   if (pgdesc->rotate == 180) {
574     g_string_append_printf(str, "-1 0 0 -1 %.2f %.2f cm ", width, height);
575   }
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;
583     else return str;
584   }
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);
592   return str;
593 }
594
595 // add an entry to a subentry of a directory
596
597 struct PdfObj *mk_pdfname(char *name)
598 {
599   struct PdfObj *obj;
600   
601   obj = g_malloc(sizeof(struct PdfObj));
602   obj->type = PDFTYPE_NAME;
603   obj->str = g_strdup(name);
604   return obj;
605 }
606
607 struct PdfObj *mk_pdfref(int num)
608 {
609   struct PdfObj *obj;
610   
611   obj = g_malloc(sizeof(struct PdfObj));
612   obj->type = PDFTYPE_REF;
613   obj->intval = num;
614   obj->num = 0;
615   return obj;
616 }
617
618 gboolean iseq_obj(struct PdfObj *a, struct PdfObj *b)
619 {
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);
630   return FALSE;
631 }
632
633 void add_dict_subentry(GString *pdfbuf, struct XrefTable *xref,
634    struct PdfObj *obj, char *section, int type, char *name, struct PdfObj *entry)
635 {
636   struct PdfObj *sec;
637   int i, subpos;
638   
639   subpos = -1;
640   for (i=0; i<obj->num; i++) 
641     if (!strcmp(obj->names[i], section)) subpos = i;
642   if (subpos == -1) {
643     subpos = obj->num;
644     obj->num++;
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;
649   }
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;
654   }
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));
659     sec->type = type;
660     sec->num = 0;
661     sec->elts = NULL;
662     sec->names = NULL;
663   }
664   sec = obj->elts[subpos];
665
666   subpos = -1;
667   if (type==PDFTYPE_DICT) {
668     for (i=0; i<sec->num; i++) 
669       if (!strcmp(sec->names[i], name)) subpos = i;
670     if (subpos == -1) {
671       subpos = sec->num;
672       sec->num++;
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;
677     }
678     free_pdfobj(sec->elts[subpos]);
679     sec->elts[subpos] = entry;
680   } 
681   if (type==PDFTYPE_ARRAY) {
682     for (i=0; i<sec->num; i++)
683       if (iseq_obj(sec->elts[i], entry)) subpos = i;
684     if (subpos == -1) {
685       subpos = sec->num;
686       sec->num++;
687       sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
688       sec->elts[subpos] = entry;
689     }
690     else free_pdfobj(entry);
691   }
692 }
693
694 // draw a page's background
695
696 void pdf_draw_solid_background(struct Page *pg, GString *str)
697 {
698   double x, y;
699
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 ",
711         x, x, pg->height);
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 ",
714         y, pg->width, y);
715     return;
716   }
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 ",
719       y, pg->width, y);
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);
725 }
726
727 int pdf_draw_bitmap_background(struct Page *pg, GString *str, 
728                                 struct XrefTable *xref, GString *pdfbuf)
729 {
730   BgPdfPage *pgpdf;
731   GdkPixbuf *pix;
732   GString *zpix;
733   PopplerPage *pdfpage;
734   char *buf, *p1, *p2;
735   int height, width, stride, x, y, chan;
736   double pgheight, pgwidth;
737   
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);
749   }
750   else pix = g_object_ref(pg->bg->pixbuf);
751   
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; }
755                     
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; }
761
762   g_string_append_printf(str, "q %.2f 0 0 %.2f 0 %.2f cm /ImBg Do Q ",
763     pg->width, -pg->height, pg->height);
764   
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++);
770       if (chan==4) p1++;
771     }
772   }
773   zpix = do_deflate(buf, 3*width*height);
774   g_free(buf);
775   g_object_unref(pix);
776
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");
786  
787   return xref->last;
788 }
789
790 gboolean pdf_draw_image(PdfImage *image, struct XrefTable *xref, GString *pdfbuf)
791 {
792   char *buf, *p1, *p2;
793   int height, width, stride, x, y, chan;
794   GString *zpix;
795
796   if (gdk_pixbuf_get_bits_per_sample(image->pixbuf) != 8 ||
797       gdk_pixbuf_get_colorspace(image->pixbuf) != GDK_COLORSPACE_RGB) {
798     return FALSE;
799   }
800
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))) {
806     return FALSE;
807   }
808
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++);
814       if (chan==4) p1++;
815     }
816   }
817   zpix = do_deflate(buf, 3*width*height);
818   g_free(buf);
819
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, 
828       "/SMask %d 0 R ",
829       image->n_obj_smask);
830   }
831   g_string_append_printf(pdfbuf, " >> stream\n");
832
833   g_string_append_len(pdfbuf, zpix->str, zpix->len);
834   g_string_free(zpix, TRUE);
835   g_string_append(pdfbuf, "endstream\nendobj\n");
836
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 */
844       }
845     }
846     zpix = do_deflate(buf, width*height);
847     g_free(buf);
848     
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);
855
856     g_string_append_len(pdfbuf, zpix->str, zpix->len);
857     g_string_free(zpix, TRUE);
858     g_string_append(pdfbuf, "endstream\nendobj\n");
859   }
860
861   return TRUE;
862 }
863
864
865 // manipulate Pdf fonts
866
867 struct PdfFont *new_pdffont(struct XrefTable *xref, GList **fonts,
868    char *filename, int font_id, FT_Face face, int glyph_page)
869 {
870   GList *list;
871   struct PdfFont *font;
872   int i;
873   const char *s;
874   
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; }
880   }
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;
894   }
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
911   else {
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;
915   }
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);
920   return font;
921 }
922
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"
926
927 void embed_pdffont(GString *pdfbuf, struct XrefTable *xref, struct PdfFont *font)
928 {
929   // this code inspired by libgnomeprint
930   gboolean fallback, is_binary;
931   guchar encoding[256];
932   gushort glyphs[256];
933   int i, j, num;
934   guint32 len1, len2;
935   guint32 tt_len;
936   gsize t1_len;
937   TrueTypeFont *ttfnt;
938   char *seg1, *seg2;
939   char *fontdata, *p;
940   char prefix[8];
941   int nobj_fontprog, nobj_descr, lastchar;
942   
943   fallback = FALSE;
944   // embed the font file: TrueType case
945   if (font->is_truetype) {
946     glyphs[0] = encoding[0] = 0;
947     num = 1;
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;
952         encoding[num] = i;
953         num++;
954       }
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");
966         g_free(fontdata);
967       }
968       else fallback = TRUE;
969       CloseTTFont(ttfnt);
970     } 
971     else fallback = TRUE;
972   } else {
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) {
976         is_binary = TRUE;
977         len1 = pfb_get_length((unsigned char *)fontdata+2);
978         if (fontdata[len1+6]!=(char)0x80 || fontdata[len1+7]!=(char)0x02) fallback = TRUE;
979         else {
980           len2 = pfb_get_length((unsigned char *)fontdata+len1+8);
981           if (fontdata[len1+len2+12]!=(char)0x80 || fontdata[len1+len2+13]!=(char)0x01)
982             fallback = TRUE;
983         }
984       }
985       else if (!strncmp(fontdata, "%!PS", 4)) {
986         is_binary = FALSE;
987         p = strstr(fontdata, T1_SEGMENT_1_END) + strlen(T1_SEGMENT_1_END);
988         if (p==NULL) fallback = TRUE;
989         else {
990           if (*p=='\n' || *p=='\r') p++;
991           if (*p=='\n' || *p=='\r') p++;
992           len1 = p-fontdata;
993           p = g_strrstr_len(fontdata, t1_len, T1_SEGMENT_3_END);
994           if (p==NULL) fallback = TRUE;
995           else {
996             // rewind 512 zeros
997             i = 512; p--;
998             while (i>0 && p!=fontdata && (*p=='0' || *p=='\r' || *p=='\n')) {
999               if (*p=='0') i--;
1000               p--;
1001             }
1002             while (p!=fontdata && (*p=='\r' || *p=='\n')) p--;
1003             p++;
1004             if (i>0) fallback = TRUE;
1005             else len2 = p-fontdata-len1;
1006           }
1007         }
1008       }
1009       else fallback = TRUE;
1010       if (!fallback) {
1011         if (is_binary) {
1012           seg1 = fontdata+6;
1013           seg2 = fontdata + len1 + 12;
1014         } else {
1015           seg1 = fontdata;
1016           seg2 = g_malloc(len2/2);
1017           j=0;
1018           p = fontdata+len1;
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');
1024             p+=2;
1025           }
1026           len2 = j;
1027         }
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);
1037       }
1038       g_free(fontdata);
1039     }
1040     else fallback = TRUE;
1041   }
1042   
1043   // next, the font descriptor
1044   if (!fallback) {
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",
1055       nobj_fontprog);
1056   }
1057   
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;
1066   if (fallback) {
1067     font->is_truetype = FALSE;
1068     g_free(font->fontname);
1069     font->fontname = g_strdup("Helvetica");
1070   }
1071   prefix[0]=0;
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;
1076   }
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);
1081   if (!fallback) {
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, "] ");
1088   }
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]);
1095     }
1096     g_string_append(pdfbuf, "] >> ");
1097   }
1098   g_string_append(pdfbuf, ">> endobj\n");
1099 }
1100
1101 // Pdf images
1102
1103 struct PdfImage *new_pdfimage(struct XrefTable *xref, GList **images, GdkPixbuf *pixbuf)
1104 {
1105   GList *list;
1106   struct PdfImage *image;
1107   
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
1116   }
1117   image->pixbuf = pixbuf;
1118
1119   return image;
1120 }
1121
1122 // draw a page's graphics
1123
1124 void pdf_draw_page(struct Page *pg, GString *str, gboolean *use_hiliter, 
1125                    struct XrefTable *xref, GList **pdffonts, GList **pdfimages)
1126 {
1127   GList *layerlist, *itemlist, *tmplist;
1128   struct Layer *l;
1129   struct Item *item;
1130   guint old_rgba, old_text_rgba;
1131   double old_thickness;
1132   double *pt;
1133   int i, j;
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;
1142   FcPattern *pattern;
1143   int baseline, advance;
1144   int glyph_no, glyph_page, current_page;
1145   char *filename;
1146   char tmpstr[200];
1147   int font_id;
1148   FT_Face ftface;
1149   struct PdfFont *cur_font;
1150   struct PdfImage *cur_image;
1151   gboolean in_string;
1152   
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;
1158   }
1159   for (tmplist = *pdfimages; tmplist!=NULL; tmplist = tmplist->next) {
1160     cur_image = (struct PdfImage *)tmplist->data;
1161     cur_image->used_in_this_page = FALSE;
1162   }
1163
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;
1177         }
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;
1187         } else {
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;
1192         }
1193         if ((item->brush.color_rgba & 0xf0) != 0xf0) // undo transparent
1194           g_string_append(str, "Q ");
1195       }
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);
1216         do {
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)
1226                 continue;
1227           ftface = pango_fc_font_lock_face(fcfont);
1228           current_page = -1;
1229           cur_font = NULL;
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);
1234           in_string = FALSE;
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 ");
1243               in_string = FALSE;
1244               g_string_append_printf(str, "/F%d 1 Tf ", cur_font->n_obj);
1245             }
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, '(');
1250             in_string = TRUE;
1251             if (cur_font->is_truetype) {
1252               if (glyph_no) glyph_no = (glyph_no%255)+1;
1253               cur_font->glyphmap[glyph_no] = glyph_no;
1254             }
1255             else {
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");
1265               }
1266               glyph_no = j;
1267             }
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);
1274           }
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);
1281       }
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
1288            cur_image->n_obj);
1289       }
1290     }
1291   }
1292 }
1293
1294 // main printing function
1295
1296 /* we use the following object numbers, starting with n_obj_catalog:
1297     0 the document catalog
1298     1 the page tree
1299     2 the GS for the hiliters
1300     3 ... the page objects
1301 */
1302
1303 gboolean print_to_pdf(char *filename)
1304 {
1305   FILE *f;
1306   GString *pdfbuf, *pgstrm, *zpgstrm, *tmpstr;
1307   int n_obj_catalog, n_obj_pages_offs, n_page, n_obj_bgpix, n_obj_prefix;
1308   int i, startxref;
1309   struct XrefTable xref;
1310   GList *pglist;
1311   struct Page *pg;
1312   gboolean annot, uses_pdf;
1313   gboolean use_hiliter;
1314   struct PdfInfo pdfinfo;
1315   struct PdfObj *obj;
1316   GList *pdffonts, *pdfimages, *list;
1317   struct PdfFont *font;
1318   struct PdfImage *image;
1319   char *tmpbuf;
1320   
1321   f = fopen(filename, "wb");
1322   if (f == NULL) return FALSE;
1323   setlocale(LC_NUMERIC, "C");
1324   annot = FALSE;
1325   xref.data = NULL;
1326   uses_pdf = FALSE;
1327   pdffonts = NULL;
1328   pdfimages = NULL;
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;
1332   }
1333   
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);
1340     if (!annot) {
1341       g_string_free(pdfbuf, TRUE);
1342       if (xref.data != NULL) g_free(xref.data);
1343     }
1344   }
1345
1346   if (!annot) {
1347     pdfbuf = g_string_new("%PDF-1.4\n%\370\357\365\362\n");
1348     xref.n_alloc = xref.last = 0;
1349     xref.data = NULL;
1350   }
1351     
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;
1370   
1371   for (pglist = journal.pages, n_page = 0; pglist!=NULL;
1372        pglist = pglist->next, n_page++) {
1373     pg = (struct Page *)pglist->data;
1374     
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);
1378     n_obj_bgpix = -1;
1379     n_obj_prefix = -1;
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 ");
1393     }
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");
1400     
1401     // deflate pgstrm and write it
1402     zpgstrm = do_deflate(pgstrm->str, pgstrm->len);
1403     g_string_free(pgstrm, TRUE);
1404     
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");
1412     
1413     // write the page object
1414     
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) {
1422         free_pdfobj(obj);
1423         obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1424       }
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, ' ');
1432         }
1433       }
1434       free_pdfobj(obj);
1435       g_string_append_printf(pdfbuf, "%d 0 R] ", xref.last);
1436     }
1437     else g_string_append_printf(pdfbuf, "/Contents %d 0 R ", xref.last);
1438     g_string_append(pdfbuf, "/Resources ");
1439
1440     if (n_obj_prefix>0)
1441       obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].resources);
1442     else obj = NULL;
1443     if (obj!=NULL && obj->type!=PDFTYPE_DICT)
1444       { free_pdfobj(obj); obj=NULL; }
1445     if (obj==NULL) {
1446       obj = g_malloc(sizeof(struct PdfObj));
1447       obj->type = PDFTYPE_DICT;
1448       obj->num = 0;
1449       obj->elts = NULL;
1450       obj->names = NULL;
1451     }
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"));
1457     if (use_hiliter)
1458       add_dict_subentry(pdfbuf, &xref,
1459         obj, "/ExtGState", PDFTYPE_DICT, "/XoHi", mk_pdfref(n_obj_catalog+2));
1460     if (n_obj_bgpix>0)
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));
1471         g_free(tmpbuf);
1472       }
1473     }
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));
1480         g_free(tmpbuf);
1481       }
1482     }
1483     show_pdfobj(obj, pdfbuf);
1484     free_pdfobj(obj);
1485     g_string_append(pdfbuf, " >> endobj\n");
1486   }
1487   
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);
1494     g_free(font);
1495   }
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)) {
1500       return FALSE;
1501     }
1502     g_free(image);
1503   }
1504   g_list_free(pdfimages);
1505   
1506   // PDF trailer
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);
1516   if (annot) {
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...
1520 /*    
1521     obj = get_dict_entry(pdfinfo.trailerdict, "/Encrypt");
1522     if (obj!=NULL) {
1523       g_string_append_printf(pdfbuf, "/Encrypt ");
1524       show_pdfobj(obj, pdfbuf);
1525     } 
1526 */
1527   }
1528   g_string_append_printf(pdfbuf, 
1529     ">>\nstartxref\n%d\n%%%%EOF\n", startxref);
1530   
1531   g_free(xref.data);
1532   if (annot) {
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);
1539       }
1540   }
1541   
1542   setlocale(LC_NUMERIC, "");
1543   if (fwrite(pdfbuf->str, 1, pdfbuf->len, f) < pdfbuf->len) {
1544     fclose(f);
1545     g_string_free(pdfbuf, TRUE);
1546     return FALSE;
1547   }
1548   fclose(f);
1549   g_string_free(pdfbuf, TRUE);
1550   return TRUE;
1551 }
1552
1553 /*********** Printing via gtk-print **********/
1554
1555 #if GTK_CHECK_VERSION(2, 10, 0)
1556
1557 // does the same job as update_canvas_bg(), but to a print context
1558
1559 void print_background(cairo_t *cr, struct Page *pg)
1560 {
1561   double x, y;
1562   GdkPixbuf *pix;
1563   BgPdfPage *pgpdf;
1564   PopplerPage *pdfpage;
1565   cairo_surface_t *cr_pixbuf;
1566   double pgwidth, pgheight;
1567
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);
1571     cairo_fill(cr);
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);
1576
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); }
1582       cairo_stroke(cr);
1583       return;
1584     }
1585     
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); }
1588     cairo_stroke(cr);
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);
1593       cairo_stroke(cr);
1594     }
1595     return;
1596   }
1597   else
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);
1603     cairo_save(cr);
1604     cairo_scale(cr, pg->width/pgwidth, pg->height/pgheight);
1605     poppler_page_render(pdfpage, cr);
1606     cairo_restore(cr);
1607     g_object_unref(pdfpage);
1608   }
1609   else 
1610   if (pg->bg->type == BG_PIXMAP) {
1611     cairo_save(cr);
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));
1616     cairo_fill(cr);
1617     cairo_restore(cr);
1618   }
1619 }
1620
1621 void print_job_render_page(GtkPrintOperation *print, GtkPrintContext *context, gint pageno, gpointer user_data)
1622 {
1623   cairo_t *cr;
1624   gdouble width, height, scale;
1625   struct Page *pg;
1626   guint old_rgba;
1627   double old_thickness;
1628   GList *layerlist, *itemlist;
1629   struct Layer *l;
1630   struct Item *item;
1631   int i;
1632   double *pt;
1633   PangoFontDescription *font_desc;
1634   PangoLayout *layout;
1635         
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);
1641   
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);
1646   
1647   print_background(cr, pg);
1648
1649   old_rgba = predef_colors_rgba[COLOR_BLACK];
1650   cairo_set_source_rgb(cr, 0, 0, 0);
1651   old_thickness = 0.0;
1652
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;
1662       }
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]);
1671           cairo_stroke(cr);
1672           old_thickness = item->brush.thickness;
1673         } else {
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]);
1678             cairo_stroke(cr);
1679           }
1680           old_thickness = 0.0;
1681         }
1682       }
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);
1695       }
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);
1702         cairo_paint(cr);
1703         old_rgba = predef_colors_rgba[COLOR_BLACK];
1704         cairo_set_source_rgb(cr, 0, 0, 0);
1705       }
1706     }
1707   }
1708 }
1709
1710 #endif