]> git.donarmstrong.com Git - xournal.git/blob - src/xo-print.c
cb480b1936d0192b7097337fb4a774f0932547e0
[xournal.git] / src / xo-print.c
1 #ifdef HAVE_CONFIG_H
2 #  include <config.h>
3 #endif
4
5 #define PANGO_ENABLE_BACKEND /* to access PangoFcFont.font_pattern */
6
7 #include <gtk/gtk.h>
8 #include <libgnomecanvas/libgnomecanvas.h>
9 #include <libgnomeprint/gnome-print-job.h>
10 #include <libgnomeprint/gnome-print-pango.h>
11 #include <zlib.h>
12 #include <string.h>
13 #include <locale.h>
14 #include <pango/pango.h>
15 #include <pango/pangofc-font.h>
16 #include <fontconfig/fontconfig.h>
17 #include <ft2build.h>
18 #include FT_FREETYPE_H
19 #include "sft.h" /* Sun Font Tools, embedded in libgnomeprint */
20
21 #include "xournal.h"
22 #include "xo-misc.h"
23 #include "xo-paint.h"
24 #include "xo-print.h"
25 #include "xo-file.h"
26
27 #define RGBA_RED(rgba) (((rgba>>24)&0xff)/255.0)
28 #define RGBA_GREEN(rgba) (((rgba>>16)&0xff)/255.0)
29 #define RGBA_BLUE(rgba) (((rgba>>8)&0xff)/255.0)
30 #define RGBA_ALPHA(rgba) (((rgba>>0)&0xff)/255.0)
31 #define RGBA_RGB(rgba) RGBA_RED(rgba), RGBA_GREEN(rgba), RGBA_BLUE(rgba)
32
33 /*********** Printing to PDF ************/
34
35 gboolean ispdfspace(char c)
36 {
37   return (c==0 || c==9 || c==10 || c==12 || c==13 || c==' ');
38 }
39
40 gboolean ispdfdelim(char c)
41 {
42   return (c=='(' || c==')' || c=='<' || c=='>' || c=='[' || c==']' ||
43           c=='{' || c=='}' || c=='/' || c=='%');
44 }
45
46 void skipspace(char **p, char *eof)
47 {
48   while (ispdfspace(**p) || **p=='%') {
49     if (**p=='%') while (*p!=eof && **p!=10 && **p!=13) (*p)++;
50     if (*p==eof) return;
51     (*p)++;
52   }
53 }
54
55 void free_pdfobj(struct PdfObj *obj)
56 {
57   int i;
58   
59   if (obj==NULL) return;
60   if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
61       obj->type == PDFTYPE_STREAM) && obj->str!=NULL)
62     g_free(obj->str);
63   if ((obj->type == PDFTYPE_ARRAY || obj->type == PDFTYPE_DICT ||
64       obj->type == PDFTYPE_STREAM) && obj->num>0) {
65     for (i=0; i<obj->num; i++)
66       free_pdfobj(obj->elts[i]);
67     g_free(obj->elts);
68   }
69   if ((obj->type == PDFTYPE_DICT || obj->type == PDFTYPE_STREAM) && obj->num>0) {
70     for (i=0; i<obj->num; i++)
71       g_free(obj->names[i]);
72     g_free(obj->names);
73   }
74   g_free(obj);
75 }
76
77 struct PdfObj *dup_pdfobj(struct PdfObj *obj)
78 {
79   struct PdfObj *dup;
80   int i;
81   
82   if (obj==NULL) return NULL;
83   dup = g_memdup(obj, sizeof(struct PdfObj));
84   if ((obj->type == PDFTYPE_STRING || obj->type == PDFTYPE_NAME ||
85       obj->type == PDFTYPE_STREAM) && obj->str!=NULL) {
86     if (obj->type == PDFTYPE_NAME) obj->len = strlen(obj->str);
87     dup->str = g_memdup(obj->str, obj->len+1);
88   }
89   if ((obj->type == PDFTYPE_ARRAY || obj->type == PDFTYPE_DICT ||
90       obj->type == PDFTYPE_STREAM) && obj->num>0) {
91     dup->elts = g_malloc(obj->num*sizeof(struct PdfObj *));
92     for (i=0; i<obj->num; i++)
93       dup->elts[i] = dup_pdfobj(obj->elts[i]);
94   }
95   if ((obj->type == PDFTYPE_DICT || obj->type == PDFTYPE_STREAM) && obj->num>0) {
96     dup->names = g_malloc(obj->num*sizeof(char *));
97     for (i=0; i<obj->num; i++)
98       dup->names[i] = g_strdup(obj->names[i]);
99   }
100   return dup;
101 }
102
103 void show_pdfobj(struct PdfObj *obj, GString *str)
104 {
105   int i;
106   if (obj==NULL) return;
107   switch(obj->type) {
108     case PDFTYPE_CST:
109       if (obj->intval==1) g_string_append(str, "true");
110       if (obj->intval==0) g_string_append(str, "false");
111       if (obj->intval==-1) g_string_append(str, "null");
112       break;
113     case PDFTYPE_INT:
114       g_string_append_printf(str, "%d", obj->intval);
115       break;
116     case PDFTYPE_REAL:
117       g_string_append_printf(str, "%f", obj->realval);
118       break;
119     case PDFTYPE_STRING:
120       g_string_append_len(str, obj->str, obj->len);
121       break;
122     case PDFTYPE_NAME:
123       g_string_append(str, obj->str);
124       break;
125     case PDFTYPE_ARRAY:
126       g_string_append_c(str, '[');
127       for (i=0;i<obj->num;i++) {
128         if (i) g_string_append_c(str, ' ');
129         show_pdfobj(obj->elts[i], str);
130       }
131       g_string_append_c(str, ']');
132       break;
133     case PDFTYPE_DICT:
134       g_string_append(str, "<<");
135       for (i=0;i<obj->num;i++) {
136         g_string_append_printf(str, " %s ", obj->names[i]); 
137         show_pdfobj(obj->elts[i], str);
138       }
139       g_string_append(str, " >>");
140       break;
141     case PDFTYPE_REF:
142       g_string_append_printf(str, "%d %d R", obj->intval, obj->num);
143       break;
144   }
145 }
146
147 void DEBUG_PRINTOBJ(struct PdfObj *obj)
148 {
149   GString *s = g_string_new("");
150   show_pdfobj(obj, s);
151   puts(s->str);
152   g_string_free(s, TRUE);
153 }
154
155 // parse a PDF object; returns NULL if fails
156 // THIS PARSER DOES NOT RECOGNIZE STREAMS YET
157
158 struct PdfObj *parse_pdf_object(char **ptr, char *eof)
159 {
160   struct PdfObj *obj, *elt;
161   char *p, *q, *r, *eltname;
162   int stack;
163
164   obj = g_malloc(sizeof(struct PdfObj));
165   p = *ptr;
166   skipspace(&p, eof);
167   if (p==eof) { g_free(obj); return NULL; }
168   
169   // maybe a constant
170   if (!strncmp(p, "true", 4)) {
171     obj->type = PDFTYPE_CST;
172     obj->intval = 1;
173     *ptr = p+4;
174     return obj;
175   }
176   if (!strncmp(p, "false", 5)) {
177     obj->type = PDFTYPE_CST;
178     obj->intval = 0;
179     *ptr = p+5;
180     return obj;
181   }
182   if (!strncmp(p, "null", 4)) {
183     obj->type = PDFTYPE_CST;
184     obj->intval = -1;
185     *ptr = p+4;
186     return obj;
187   }
188
189   // or a number ?
190   obj->intval = strtol(p, &q, 10);
191   *ptr = q;
192   if (q!=p) {
193     if (*q == '.') {
194       obj->type = PDFTYPE_REAL;
195       obj->realval = g_ascii_strtod(p, ptr);
196       return obj;
197     }
198     if (ispdfspace(*q)) {
199       // check for indirect reference
200       skipspace(&q, eof);
201       obj->num = strtol(q, &r, 10);
202       if (r!=q) {
203         skipspace(&r, eof);
204         if (*r=='R') {
205           *ptr = r+1;
206           obj->type = PDFTYPE_REF;
207           return obj;
208         }
209       }
210     }
211     obj->type = PDFTYPE_INT;
212     return obj;
213   }
214
215   // a string ?
216   if (*p=='(') {
217     q=p+1; stack=1;
218     while (stack>0 && q!=eof) {
219       if (*q=='(') stack++;
220       if (*q==')') stack--;
221       if (*q=='\\') q++;
222       if (q!=eof) q++;
223     }
224     if (q==eof) { g_free(obj); return NULL; }
225     obj->type = PDFTYPE_STRING;
226     obj->len = q-p;
227     obj->str = g_malloc(obj->len+1);
228     obj->str[obj->len] = 0;
229     g_memmove(obj->str, p, obj->len);
230     *ptr = q;
231     return obj;
232   }  
233   if (*p=='<' && p[1]!='<') {
234     q=p+1;
235     while (*q!='>' && q!=eof) q++;
236     if (q==eof) { g_free(obj); return NULL; }
237     q++;
238     obj->type = PDFTYPE_STRING;
239     obj->len = q-p;
240     obj->str = g_malloc(obj->len+1);
241     obj->str[obj->len] = 0;
242     g_memmove(obj->str, p, obj->len);
243     *ptr = q;
244     return obj;
245   }
246   
247   // a name ?
248   if (*p=='/') {
249     q=p+1;
250     while (!ispdfspace(*q) && !ispdfdelim(*q)) q++;
251     obj->type = PDFTYPE_NAME;
252     obj->str = g_strndup(p, q-p);
253     *ptr = q;
254     return obj;
255   }
256
257   // an array ?
258   if (*p=='[') {
259     obj->type = PDFTYPE_ARRAY;
260     obj->num = 0;
261     obj->elts = NULL;
262     q=p+1; skipspace(&q, eof);
263     while (*q!=']') {
264       elt = parse_pdf_object(&q, eof);
265       if (elt==NULL) { free_pdfobj(obj); return NULL; }
266       obj->num++;
267       obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
268       obj->elts[obj->num-1] = elt;
269       skipspace(&q, eof);
270     }
271     *ptr = q+1;
272     return obj;
273   }
274
275   // a dictionary ?
276   if (*p=='<' && p[1]=='<') {
277     obj->type = PDFTYPE_DICT;
278     obj->num = 0;
279     obj->elts = NULL;
280     obj->names = NULL;
281     q=p+2; skipspace(&q, eof);
282     while (*q!='>' || q[1]!='>') {
283       if (*q!='/') { free_pdfobj(obj); return NULL; }
284       r=q+1;
285       while (!ispdfspace(*r) && !ispdfdelim(*r)) r++;
286       eltname = g_strndup(q, r-q);
287       q=r; skipspace(&q, eof);
288       elt = parse_pdf_object(&q, eof);
289       if (elt==NULL) { g_free(eltname); free_pdfobj(obj); return NULL; }
290       obj->num++;
291       obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj *));
292       obj->names = g_realloc(obj->names, obj->num*sizeof(char *));
293       obj->elts[obj->num-1] = elt;
294       obj->names[obj->num-1] = eltname;
295       skipspace(&q, eof);
296     }
297     *ptr = q+2;
298     return obj;
299   }
300
301   // DOES NOT RECOGNIZE STREAMS YET (handle as subcase of dictionary)
302   
303   g_free(obj);
304   return NULL;
305 }
306
307 struct PdfObj *get_dict_entry(struct PdfObj *dict, char *name)
308 {
309   int i;
310   
311   if (dict==NULL) return NULL;
312   if (dict->type != PDFTYPE_DICT) return NULL;
313   for (i=0; i<dict->num; i++) 
314     if (!strcmp(dict->names[i], name)) return dict->elts[i];
315   return NULL;
316 }
317
318 struct PdfObj *get_pdfobj(GString *pdfbuf, struct XrefTable *xref, struct PdfObj *obj)
319 {
320   char *p, *eof;
321   int offs, n;
322
323   if (obj==NULL) return NULL;
324   if (obj->type!=PDFTYPE_REF) return dup_pdfobj(obj);
325   if (obj->intval>xref->last) return NULL;
326   offs = xref->data[obj->intval];
327   if (offs<=0 || offs >= pdfbuf->len) return NULL;
328
329   p = pdfbuf->str + offs;
330   eof = pdfbuf->str + pdfbuf->len;
331   n = strtol(p, &p, 10);
332   if (n!=obj->intval) return NULL;
333   skipspace(&p, eof);
334   n = strtol(p, &p, 10);
335   skipspace(&p, eof);
336   if (strncmp(p, "obj", 3)) return NULL;
337   p+=3;
338   return parse_pdf_object(&p, eof);
339 }
340
341 // read the xref table of a PDF file in memory, and return the trailerdict
342
343 struct PdfObj *parse_xref_table(GString *pdfbuf, struct XrefTable *xref, int offs)
344 {
345   char *p, *eof;
346   struct PdfObj *trailerdict, *obj;
347   int start, len, i;
348   
349   if (strncmp(pdfbuf->str+offs, "xref", 4)) return NULL;
350   p = strstr(pdfbuf->str+offs, "trailer");
351   eof = pdfbuf->str + pdfbuf->len;
352   if (p==NULL) return NULL;
353   p+=8;
354   trailerdict = parse_pdf_object(&p, eof);
355   obj = get_dict_entry(trailerdict, "/Size");
356   if (obj!=NULL && obj->type == PDFTYPE_INT && obj->intval-1>xref->last)
357     make_xref(xref, obj->intval-1, 0);
358   obj = get_dict_entry(trailerdict, "/Prev");
359   if (obj!=NULL && obj->type == PDFTYPE_INT && obj->intval>0 && obj->intval!=offs) {
360     // recurse into older xref table
361     obj = parse_xref_table(pdfbuf, xref, obj->intval);
362     free_pdfobj(obj);
363   }
364   p = pdfbuf->str+offs+4;
365   skipspace(&p, eof);
366   if (*p<'0' || *p>'9') { free_pdfobj(trailerdict); return NULL; }
367   while (*p>='0' && *p<='9') {
368     start = strtol(p, &p, 10);
369     skipspace(&p, eof);
370     len = strtol(p, &p, 10);
371     skipspace(&p, eof);
372     if (len <= 0 || 20*len > eof-p) break;
373     if (start+len-1 > xref->last) make_xref(xref, start+len-1, 0);
374     for (i=start; i<start+len; i++) {
375       xref->data[i] = strtol(p, NULL, 10);
376       p+=20;
377     }
378     skipspace(&p, eof);
379   }
380   if (*p!='t') { free_pdfobj(trailerdict); return NULL; }
381   return trailerdict;
382 }
383
384 // parse the page tree
385
386 int pdf_getpageinfo(GString *pdfbuf, struct XrefTable *xref, 
387                 struct PdfObj *pgtree, int nmax, struct PdfPageDesc *pages)
388 {
389   struct PdfObj *obj, *kid;
390   int i, count, j;
391   
392   obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Type"));
393   if (obj == NULL || obj->type != PDFTYPE_NAME)
394     return 0;
395   if (!strcmp(obj->str, "/Page")) {
396     free_pdfobj(obj);
397     pages->contents = dup_pdfobj(get_dict_entry(pgtree, "/Contents"));
398     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
399     if (obj!=NULL) {
400       free_pdfobj(pages->resources);
401       pages->resources = obj;
402     }
403     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
404     if (obj!=NULL) {
405       free_pdfobj(pages->mediabox);
406       pages->mediabox = obj;
407     }
408     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
409     if (obj!=NULL && obj->type == PDFTYPE_INT)
410       pages->rotate = obj->intval;
411     free_pdfobj(obj);
412     return 1;
413   }
414   else if (!strcmp(obj->str, "/Pages")) {
415     free_pdfobj(obj);
416     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Count"));
417     if (obj!=NULL && obj->type == PDFTYPE_INT && 
418         obj->intval>0 && obj->intval<=nmax) count = obj->intval;
419     else count = 0;
420     free_pdfobj(obj);
421     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Resources"));
422     if (obj!=NULL)
423       for (i=0; i<count; i++) {
424         free_pdfobj(pages[i].resources);
425         pages[i].resources = dup_pdfobj(obj);
426       }
427     free_pdfobj(obj);
428     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/MediaBox"));
429     if (obj!=NULL)
430       for (i=0; i<count; i++) {
431         free_pdfobj(pages[i].mediabox);
432         pages[i].mediabox = dup_pdfobj(obj);
433       }
434     free_pdfobj(obj);
435     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Rotate"));
436     if (obj!=NULL && obj->type == PDFTYPE_INT)
437       for (i=0; i<count; i++)
438         pages[i].rotate = obj->intval;
439     free_pdfobj(obj);
440     obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pgtree, "/Kids"));
441     if (obj!=NULL && obj->type == PDFTYPE_ARRAY) {
442       for (i=0; i<obj->num; i++) {
443         kid = get_pdfobj(pdfbuf, xref, obj->elts[i]);
444         if (kid!=NULL) {
445           j = pdf_getpageinfo(pdfbuf, xref, kid, nmax, pages);
446           nmax -= j;
447           pages += j;
448           free_pdfobj(kid);
449         }
450       }
451     }
452     free_pdfobj(obj);
453     return count;
454   }
455   return 0;
456 }
457
458 // parse a PDF file in memory
459
460 gboolean pdf_parse_info(GString *pdfbuf, struct PdfInfo *pdfinfo, struct XrefTable *xref)
461 {
462   char *p;
463   int offs;
464   struct PdfObj *obj, *pages;
465
466   xref->n_alloc = xref->last = 0;
467   xref->data = NULL;
468   p = pdfbuf->str + pdfbuf->len-1;
469   
470   while (*p!='s' && p!=pdfbuf->str) p--;
471   if (strncmp(p, "startxref", 9)) return FALSE; // fail
472   p+=9;
473   while (ispdfspace(*p) && p!=pdfbuf->str+pdfbuf->len) p++;
474   offs = strtol(p, NULL, 10);
475   if (offs <= 0 || offs > pdfbuf->len) return FALSE; // fail
476   pdfinfo->startxref = offs;
477   
478   pdfinfo->trailerdict = parse_xref_table(pdfbuf, xref, offs);
479   if (pdfinfo->trailerdict == NULL) return FALSE; // fail
480   
481   obj = get_pdfobj(pdfbuf, xref,
482      get_dict_entry(pdfinfo->trailerdict, "/Root"));
483   if (obj == NULL)
484     { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
485   pages = get_pdfobj(pdfbuf, xref, get_dict_entry(obj, "/Pages"));
486   free_pdfobj(obj);
487   if (pages == NULL)
488     { free_pdfobj(pdfinfo->trailerdict); return FALSE; }
489   obj = get_pdfobj(pdfbuf, xref, get_dict_entry(pages, "/Count"));
490   if (obj == NULL || obj->type != PDFTYPE_INT || obj->intval<=0) 
491     { free_pdfobj(pdfinfo->trailerdict); free_pdfobj(pages); 
492       free_pdfobj(obj); return FALSE; }
493   pdfinfo->npages = obj->intval;
494   free_pdfobj(obj);
495   
496   pdfinfo->pages = g_malloc0(pdfinfo->npages*sizeof(struct PdfPageDesc));
497   pdf_getpageinfo(pdfbuf, xref, pages, pdfinfo->npages, pdfinfo->pages);
498   free_pdfobj(pages);
499   
500   return TRUE;
501 }
502
503 // add an entry to the xref table
504
505 void make_xref(struct XrefTable *xref, int nobj, int offset)
506 {
507   if (xref->n_alloc <= nobj) {
508     xref->n_alloc = nobj + 10;
509     xref->data = g_realloc(xref->data, xref->n_alloc*sizeof(int));
510   }
511   if (xref->last < nobj) xref->last = nobj;
512   xref->data[nobj] = offset;
513 }
514
515 // a wrapper for deflate
516
517 GString *do_deflate(char *in, int len)
518 {
519   GString *out;
520   z_stream zs;
521   
522   zs.zalloc = Z_NULL;
523   zs.zfree = Z_NULL;
524   deflateInit(&zs, Z_DEFAULT_COMPRESSION);
525   zs.next_in = (Bytef *)in;
526   zs.avail_in = len;
527   zs.avail_out = deflateBound(&zs, len);
528   out = g_string_sized_new(zs.avail_out);
529   zs.next_out = (Bytef *)out->str;
530   deflate(&zs, Z_FINISH);
531   out->len = zs.total_out;
532   deflateEnd(&zs);
533   return out;
534 }
535
536 // prefix to scale the original page
537
538 GString *make_pdfprefix(struct PdfPageDesc *pgdesc, double width, double height)
539 {
540   GString *str;
541   double v[4], t, xscl, yscl;
542   int i;
543
544   // push 3 times in case code to be annotated has unbalanced q/Q (B of A., ...)
545   str = g_string_new("q q q "); 
546   if (pgdesc->rotate == 90) {
547     g_string_append_printf(str, "0 -1 1 0 0 %.2f cm ", height);
548     t = height; height = width; width = t;
549   }
550   if (pgdesc->rotate == 270) {
551     g_string_append_printf(str, "0 1 -1 0 %.2f 0 cm ", width);
552     t = height; height = width; width = t;
553   }
554   if (pgdesc->rotate == 180) {
555     g_string_append_printf(str, "-1 0 0 -1 %.2f %.2f cm ", width, height);
556   }
557   if (pgdesc->mediabox==NULL || pgdesc->mediabox->type != PDFTYPE_ARRAY ||
558       pgdesc->mediabox->num != 4) return str;
559   for (i=0; i<4; i++) {
560     if (pgdesc->mediabox->elts[i]->type == PDFTYPE_INT)
561       v[i] = pgdesc->mediabox->elts[i]->intval;
562     else if (pgdesc->mediabox->elts[i]->type == PDFTYPE_REAL)
563       v[i] = pgdesc->mediabox->elts[i]->realval;
564     else return str;
565   }
566   if (v[0]>v[2]) { t = v[0]; v[0] = v[2]; v[2] = t; }
567   if (v[1]>v[3]) { t = v[1]; v[1] = v[3]; v[3] = t; }
568   if (v[2]-v[0] < 1. || v[3]-v[1] < 1.) return str;
569   xscl = width/(v[2]-v[0]);
570   yscl = height/(v[3]-v[1]);
571   g_string_append_printf(str, "%.4f 0 0 %.4f %.2f %.2f cm ",
572     xscl, yscl, -v[0]*xscl, -v[1]*yscl);
573   return str;
574 }
575
576 // add an entry to a subentry of a directory
577
578 struct PdfObj *mk_pdfname(char *name)
579 {
580   struct PdfObj *obj;
581   
582   obj = g_malloc(sizeof(struct PdfObj));
583   obj->type = PDFTYPE_NAME;
584   obj->str = g_strdup(name);
585   return obj;
586 }
587
588 struct PdfObj *mk_pdfref(int num)
589 {
590   struct PdfObj *obj;
591   
592   obj = g_malloc(sizeof(struct PdfObj));
593   obj->type = PDFTYPE_REF;
594   obj->intval = num;
595   obj->num = 0;
596   return obj;
597 }
598
599 gboolean iseq_obj(struct PdfObj *a, struct PdfObj *b)
600 {
601   if (a==NULL || b==NULL) return (a==b);
602   if (a->type!=b->type) return FALSE;
603   if (a->type == PDFTYPE_CST || a->type == PDFTYPE_INT)
604     return (a->intval == b->intval);
605   if (a->type == PDFTYPE_REAL)
606     return (a->realval == b->realval);
607   if (a->type == PDFTYPE_NAME)
608     return !strcmp(a->str, b->str);
609   if (a->type == PDFTYPE_REF)
610     return (a->intval == b->intval && a->num == b->num);
611   return FALSE;
612 }
613
614 void add_dict_subentry(GString *pdfbuf, struct XrefTable *xref,
615    struct PdfObj *obj, char *section, int type, char *name, struct PdfObj *entry)
616 {
617   struct PdfObj *sec;
618   int i, subpos;
619   
620   subpos = -1;
621   for (i=0; i<obj->num; i++) 
622     if (!strcmp(obj->names[i], section)) subpos = i;
623   if (subpos == -1) {
624     subpos = obj->num;
625     obj->num++;
626     obj->elts = g_realloc(obj->elts, obj->num*sizeof(struct PdfObj*));
627     obj->names = g_realloc(obj->names, obj->num*sizeof(char *));
628     obj->names[subpos] = g_strdup(section);
629     obj->elts[subpos] = NULL;
630   }
631   if (obj->elts[subpos]!=NULL && obj->elts[subpos]->type==PDFTYPE_REF) {
632     sec = get_pdfobj(pdfbuf, xref, obj->elts[subpos]);
633     free_pdfobj(obj->elts[subpos]);
634     obj->elts[subpos] = sec;
635   }
636   if (obj->elts[subpos]!=NULL && obj->elts[subpos]->type!=type)
637     { free_pdfobj(obj->elts[subpos]); obj->elts[subpos] = NULL; }
638   if (obj->elts[subpos] == NULL) {
639     obj->elts[subpos] = sec = g_malloc(sizeof(struct PdfObj));
640     sec->type = type;
641     sec->num = 0;
642     sec->elts = NULL;
643     sec->names = NULL;
644   }
645   sec = obj->elts[subpos];
646
647   subpos = -1;
648   if (type==PDFTYPE_DICT) {
649     for (i=0; i<sec->num; i++) 
650       if (!strcmp(sec->names[i], name)) subpos = i;
651     if (subpos == -1) {
652       subpos = sec->num;
653       sec->num++;
654       sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
655       sec->names = g_realloc(sec->names, sec->num*sizeof(char *));
656       sec->names[subpos] = g_strdup(name);
657       sec->elts[subpos] = NULL;
658     }
659     free_pdfobj(sec->elts[subpos]);
660     sec->elts[subpos] = entry;
661   } 
662   if (type==PDFTYPE_ARRAY) {
663     for (i=0; i<sec->num; i++)
664       if (iseq_obj(sec->elts[i], entry)) subpos = i;
665     if (subpos == -1) {
666       subpos = sec->num;
667       sec->num++;
668       sec->elts = g_realloc(sec->elts, sec->num*sizeof(struct PdfObj*));
669       sec->elts[subpos] = entry;
670     }
671     else free_pdfobj(entry);
672   }
673 }
674
675 // draw a page's background
676
677 void pdf_draw_solid_background(struct Page *pg, GString *str)
678 {
679   double x, y;
680
681   g_string_append_printf(str, 
682     "%.2f %.2f %.2f rg 0 0 %.2f %.2f re f ",
683     RGBA_RGB(pg->bg->color_rgba), pg->width, pg->height);
684   if (!ui.print_ruling) return;
685   if (pg->bg->ruling == RULING_NONE) return;
686   g_string_append_printf(str,
687     "%.2f %.2f %.2f RG %.2f w ",
688     RGBA_RGB(RULING_COLOR), RULING_THICKNESS);
689   if (pg->bg->ruling == RULING_GRAPH) {
690     for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
691       g_string_append_printf(str, "%.2f 0 m %.2f %.2f l S ",
692         x, x, pg->height);
693     for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
694       g_string_append_printf(str, "0 %.2f m %.2f %.2f l S ",
695         y, pg->width, y);
696     return;
697   }
698   for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
699     g_string_append_printf(str, "0 %.2f m %.2f %.2f l S ",
700       y, pg->width, y);
701   if (pg->bg->ruling == RULING_LINED)
702     g_string_append_printf(str, 
703       "%.2f %.2f %.2f RG %.2f 0 m %.2f %.2f l S ",
704       RGBA_RGB(RULING_MARGIN_COLOR), 
705       RULING_LEFTMARGIN, RULING_LEFTMARGIN, pg->height);
706 }
707
708 int pdf_draw_bitmap_background(struct Page *pg, GString *str, 
709                                 struct XrefTable *xref, GString *pdfbuf)
710 {
711   BgPdfPage *pgpdf;
712   GdkPixbuf *pix;
713   GString *zpix;
714   PopplerPage *pdfpage;
715   char *buf, *p1, *p2;
716   int height, width, stride, x, y, chan;
717   double pgheight, pgwidth;
718   
719   if (pg->bg->type == BG_PDF) {
720     if (!bgpdf.document) return -1;
721     pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
722     if (!pdfpage) return -1;
723     poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
724     width = (int) (PDFTOPPM_PRINTING_DPI * pgwidth/72.0);
725     height = (int) (PDFTOPPM_PRINTING_DPI * pgheight/72.0);
726     pix = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);
727     poppler_page_render_to_pixbuf(
728        pdfpage, 0, 0, width, height, PDFTOPPM_PRINTING_DPI/72.0, 0, pix);
729     g_object_unref(pdfpage);
730   }
731   else pix = g_object_ref(pg->bg->pixbuf);
732   
733   if (gdk_pixbuf_get_bits_per_sample(pix) != 8 ||
734       gdk_pixbuf_get_colorspace(pix) != GDK_COLORSPACE_RGB)
735     { g_object_unref(pix); return -1; }
736                     
737   width = gdk_pixbuf_get_width(pix);
738   height = gdk_pixbuf_get_height(pix);
739   stride = gdk_pixbuf_get_rowstride(pix);
740   chan = gdk_pixbuf_get_n_channels(pix);
741   if (chan!=3 && chan!=4) { g_object_unref(pix); return -1; }
742
743   g_string_append_printf(str, "q %.2f 0 0 %.2f 0 %.2f cm /ImBg Do Q ",
744     pg->width, -pg->height, pg->height);
745   
746   p2 = buf = (char *)g_malloc(3*width*height);
747   for (y=0; y<height; y++) {
748     p1 = (char *)gdk_pixbuf_get_pixels(pix)+stride*y;
749     for (x=0; x<width; x++) {
750       *(p2++)=*(p1++); *(p2++)=*(p1++); *(p2++)=*(p1++);
751       if (chan==4) p1++;
752     }
753   }
754   zpix = do_deflate(buf, 3*width*height);
755   g_free(buf);
756   g_object_unref(pix);
757
758   make_xref(xref, xref->last+1, pdfbuf->len);
759   g_string_append_printf(pdfbuf, 
760     "%d 0 obj\n<< /Length %d /Filter /FlateDecode /Type /Xobject "
761     "/Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB "
762     "/BitsPerComponent 8 >> stream\n",
763     xref->last, zpix->len, width, height);
764   g_string_append_len(pdfbuf, zpix->str, zpix->len);
765   g_string_free(zpix, TRUE);
766   g_string_append(pdfbuf, "endstream\nendobj\n");
767  
768   return xref->last;
769 }
770
771 // manipulate Pdf fonts
772
773 struct PdfFont *new_pdffont(struct XrefTable *xref, GList **fonts,
774    char *filename, int font_id, FT_Face face, int glyph_page)
775 {
776   GList *list;
777   struct PdfFont *font;
778   int i;
779   const char *s;
780   
781   for (list = *fonts; list!=NULL; list = list->next) {
782     font = (struct PdfFont *)list->data;
783     if (!strcmp(font->filename, filename) && font->font_id == font_id 
784         && font->glyph_page == glyph_page)
785           { font->used_in_this_page = TRUE; return font; }
786   }
787   font = g_malloc(sizeof(struct PdfFont));
788   *fonts = g_list_append(*fonts, font);
789   font->n_obj = xref->last+1;
790   make_xref(xref, xref->last+1, 0); // will give it a value later
791   font->filename = g_strdup(filename);
792   font->font_id = font_id;
793   font->glyph_page = glyph_page;
794   font->used_in_this_page = TRUE;
795   font->num_glyphs_used = 0;
796   for (i=0; i<256; i++) {
797     font->glyphmap[i] = -1;
798     font->advance[i] = 0;
799     font->glyphpsnames[i] = NULL;
800   }
801   font->glyphmap[0] = 0;
802   // fill in info from the FT_Face
803   font->is_truetype = FT_IS_SFNT(face);
804   font->nglyphs = face->num_glyphs;
805   font->ft2ps = 1000.0 / face->units_per_EM;
806   font->ascender = (int)(font->ft2ps*face->ascender);
807   font->descender = (int)(font->ft2ps*face->descender);
808   if (face->bbox.xMin < -100000 || face->bbox.xMin > 100000) font->xmin = 0;
809   else font->xmin = (int)(font->ft2ps*face->bbox.xMin);
810   if (face->bbox.xMax < -100000 || face->bbox.xMax > 100000) font->xmax = 0;
811   else font->xmax = (int)(font->ft2ps*face->bbox.xMax);
812   if (face->bbox.yMin < -100000 || face->bbox.yMin > 100000) font->ymin = 0;
813   else font->ymin = (int)(font->ft2ps*face->bbox.yMin);
814   if (face->bbox.yMax < -100000 || face->bbox.yMax > 100000) font->ymax = 0;
815   else font->ymax = (int)(font->ft2ps*face->bbox.yMax);
816   if (font->is_truetype) font->flags = 4; // symbolic
817   else {
818     font->flags = 4; // symbolic
819     if (FT_IS_FIXED_WIDTH(face)) font->flags |= 1;
820     if (face->style_flags & FT_STYLE_FLAG_ITALIC) font->flags |= 64;
821   }
822   s = FT_Get_Postscript_Name(face);
823   if (s==NULL) s = "Noname";
824   if (glyph_page) font->fontname = g_strdup_printf("%s_%03d", s, glyph_page);
825   else font->fontname = g_strdup(s);
826   return font;
827 }
828
829 #define pfb_get_length(x) (((x)[3]<<24) + ((x)[2]<<16) + ((x)[1]<<8) + (x)[0])
830 #define T1_SEGMENT_1_END "currentfile eexec"
831 #define T1_SEGMENT_3_END "cleartomark"
832
833 void embed_pdffont(GString *pdfbuf, struct XrefTable *xref, struct PdfFont *font)
834 {
835   // this code inspired by libgnomeprint
836   gboolean fallback, is_binary;
837   guchar encoding[256];
838   gushort glyphs[256];
839   int i, j, num, len1, len2;
840   gsize len;
841   TrueTypeFont *ttfnt;
842   char *tmpfile, *seg1, *seg2;
843   char *fontdata, *p;
844   char prefix[8];
845   int nobj_fontprog, nobj_descr, lastchar;
846   
847   fallback = FALSE;
848   // embed the font file: TrueType case
849   if (font->is_truetype) {
850     glyphs[0] = encoding[0] = 0;
851     num = 1;
852     for (i=1; i<=255; i++) 
853       if (font->glyphmap[i]>=0) {
854         font->glyphmap[i] = num;
855         glyphs[num] = 255*font->glyph_page+i-1;
856         encoding[num] = i;
857         num++;
858       }
859     font->num_glyphs_used = num-1;
860     if (OpenTTFont(font->filename, 0, &ttfnt) == SF_OK) {
861       tmpfile = mktemp(g_strdup(TMPDIR_TEMPLATE));
862       CreateTTFromTTGlyphs(ttfnt, tmpfile, glyphs, encoding, num, 
863                            0, NULL, TTCF_AutoName | TTCF_IncludeOS2);
864       CloseTTFont(ttfnt);
865       if (g_file_get_contents(tmpfile, &fontdata, &len, NULL) && len>=8) {
866         make_xref(xref, xref->last+1, pdfbuf->len);
867         nobj_fontprog = xref->last;
868         g_string_append_printf(pdfbuf, 
869           "%d 0 obj\n<< /Length %d /Length1 %d >> stream\n",
870           nobj_fontprog, (int)len, (int)len);
871         g_string_append_len(pdfbuf, fontdata, len);
872         g_string_append(pdfbuf, "endstream\nendobj\n");
873         g_free(fontdata);
874       } 
875       else fallback = TRUE;
876       unlink(tmpfile);
877       g_free(tmpfile);
878     }
879     else fallback = TRUE;  
880   } else {
881   // embed the font file: Type1 case
882     if (g_file_get_contents(font->filename, &fontdata, &len, NULL) && len>=8) {
883       if (fontdata[0]==(char)0x80 && fontdata[1]==(char)0x01) {
884         is_binary = TRUE;
885         len1 = pfb_get_length((unsigned char *)fontdata+2);
886         if (fontdata[len1+6]!=(char)0x80 || fontdata[len1+7]!=(char)0x02) fallback = TRUE;
887         else {
888           len2 = pfb_get_length((unsigned char *)fontdata+len1+8);
889           if (fontdata[len1+len2+12]!=(char)0x80 || fontdata[len1+len2+13]!=(char)0x01)
890             fallback = TRUE;
891         }
892       }
893       else if (!strncmp(fontdata, "%!PS", 4)) {
894         is_binary = FALSE;
895         p = strstr(fontdata, T1_SEGMENT_1_END) + strlen(T1_SEGMENT_1_END);
896         if (p==NULL) fallback = TRUE;
897         else {
898           if (*p=='\n' || *p=='\r') p++;
899           if (*p=='\n' || *p=='\r') p++;
900           len1 = p-fontdata;
901           p = g_strrstr_len(fontdata, len, T1_SEGMENT_3_END);
902           if (p==NULL) fallback = TRUE;
903           else {
904             // rewind 512 zeros
905             i = 512; p--;
906             while (i>0 && p!=fontdata && (*p=='0' || *p=='\r' || *p=='\n')) {
907               if (*p=='0') i--;
908               p--;
909             }
910             while (p!=fontdata && (*p=='\r' || *p=='\n')) p--;
911             p++;
912             if (i>0) fallback = TRUE;
913             else len2 = p-fontdata-len1;
914           }
915         }
916       }
917       else fallback = TRUE;
918       if (!fallback) {
919         if (is_binary) {
920           seg1 = fontdata+6;
921           seg2 = fontdata + len1 + 12;
922         } else {
923           seg1 = fontdata;
924           seg2 = g_malloc(len2/2);
925           j=0;
926           p = fontdata+len1;
927           while (p+1 < fontdata+len1+len2) {
928             if (*p==' '||*p=='\t'||*p=='\n'||*p=='\r') { p++; continue; }
929             if (p[0]>'9') { p[0]|=0x20; p[0]-=39; }
930             if (p[1]>'9') { p[1]|=0x20; p[1]-=39; }
931             seg2[j++] = ((p[0]-'0')<<4) + (p[1]-'0');
932             p+=2;
933           }
934           len2 = j;
935         }
936         make_xref(xref, xref->last+1, pdfbuf->len);
937         nobj_fontprog = xref->last;
938         g_string_append_printf(pdfbuf, 
939           "%d 0 obj\n<< /Length %d /Length1 %d /Length2 %d /Length3 0 >> stream\n",
940           nobj_fontprog, len1+len2, len1, len2);
941         g_string_append_len(pdfbuf, seg1, len1);
942         g_string_append_len(pdfbuf, seg2, len2);
943         g_string_append(pdfbuf, "endstream\nendobj\n");
944         if (!is_binary) g_free(seg2);
945       }
946       g_free(fontdata);
947     }
948     else fallback = TRUE;
949   }
950   
951   // next, the font descriptor
952   if (!fallback) {
953     make_xref(xref, xref->last+1, pdfbuf->len);
954     nobj_descr = xref->last;
955     g_string_append_printf(pdfbuf,
956       "%d 0 obj\n<< /Type /FontDescriptor /FontName /%s /Flags %d "
957       "/FontBBox [%d %d %d %d] /ItalicAngle 0 /Ascent %d "
958       "/Descent %d /CapHeight %d /StemV 100 /%s %d 0 R >> endobj\n",
959       nobj_descr, font->fontname, font->flags, 
960       font->xmin, font->ymin, font->xmax, font->ymax, 
961       font->ascender, -font->descender, font->ascender, 
962       font->is_truetype ? "FontFile2":"FontFile",
963       nobj_fontprog);
964   }
965   
966   // finally, the font itself
967   /* Note: in Type1 case, font->glyphmap maps charcodes to glyph no's
968      in TrueType case, encoding lists the used charcodes by index,
969                        glyphs   list the used glyph no's by index
970                        font->glyphmap maps charcodes to indices        */
971   xref->data[font->n_obj] = pdfbuf->len;
972   if (font->is_truetype) lastchar = encoding[font->num_glyphs_used];
973   else lastchar = font->num_glyphs_used;
974   if (fallback) {
975     font->is_truetype = FALSE;
976     g_free(font->fontname);
977     font->fontname = g_strdup("Helvetica");
978   }
979   prefix[0]=0;
980   if (font->is_truetype) {
981     num = font->glyph_page;
982     for (i=0; i<6; i++) { prefix[i] = 'A'+(num%26); num/=26; }
983     prefix[6]='+'; prefix[7]=0;
984   }
985   g_string_append_printf(pdfbuf,
986     "%d 0 obj\n<< /Type /Font /Subtype /%s /BaseFont /%s%s /Name /F%d ",
987     font->n_obj, font->is_truetype?"TrueType":"Type1",
988     prefix, font->fontname, font->n_obj);
989   if (!fallback) {
990     g_string_append_printf(pdfbuf,
991       "/FontDescriptor %d 0 R /FirstChar 0 /LastChar %d /Widths [",
992       nobj_descr, lastchar);
993     for (i=0; i<=lastchar; i++)
994       g_string_append_printf(pdfbuf, "%d ", font->advance[i]);
995     g_string_append(pdfbuf, "] ");
996   }
997   if (!font->is_truetype) { /* encoding */
998     g_string_append(pdfbuf, "/Encoding << /Type /Encoding "
999       "/BaseEncoding /MacRomanEncoding /Differences [1 ");
1000     for (i=1; i<=lastchar; i++) {
1001       g_string_append_printf(pdfbuf, "/%s ", font->glyphpsnames[i]);
1002       g_free(font->glyphpsnames[i]);
1003     }
1004     g_string_append(pdfbuf, "] >> ");
1005   }
1006   g_string_append(pdfbuf, ">> endobj\n");
1007 }
1008
1009 // draw a page's graphics
1010
1011 void pdf_draw_page(struct Page *pg, GString *str, gboolean *use_hiliter, 
1012                   struct XrefTable *xref, GList **pdffonts)
1013 {
1014   GList *layerlist, *itemlist, *tmplist;
1015   struct Layer *l;
1016   struct Item *item;
1017   guint old_rgba, old_text_rgba;
1018   double old_thickness;
1019   double *pt;
1020   int i, j;
1021   PangoFontDescription *font_desc;
1022   PangoContext *context;
1023   PangoLayout *layout;
1024   PangoLayoutIter *iter;
1025   PangoRectangle logical_rect;
1026   PangoLayoutRun *run;
1027   PangoFcFont *fcfont;
1028   FcPattern *pattern;
1029   int baseline, advance;
1030   int glyph_no, glyph_page, current_page;
1031   char *filename;
1032   char tmpstr[200];
1033   int font_id;
1034   FT_Face ftface;
1035   struct PdfFont *cur_font;
1036   gboolean in_string;
1037   
1038   old_rgba = old_text_rgba = 0x12345678;    // not any values we use, so we'll reset them
1039   old_thickness = 0.0;
1040   for (tmplist = *pdffonts; tmplist!=NULL; tmplist = tmplist->next) {
1041     cur_font = (struct PdfFont *)tmplist->data;
1042     cur_font->used_in_this_page = FALSE;
1043   }
1044
1045   for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1046     l = (struct Layer *)layerlist->data;
1047     for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1048       item = (struct Item *)itemlist->data;
1049       if (item->type == ITEM_STROKE) {
1050         if ((item->brush.color_rgba & ~0xff) != old_rgba)
1051           g_string_append_printf(str, "%.2f %.2f %.2f RG ",
1052             RGBA_RGB(item->brush.color_rgba));
1053         if (item->brush.thickness != old_thickness)
1054           g_string_append_printf(str, "%.2f w ", item->brush.thickness);
1055         if ((item->brush.color_rgba & 0xf0) != 0xf0) { // transparent
1056           g_string_append(str, "q /XoHi gs ");
1057           *use_hiliter = TRUE;
1058         }
1059         old_rgba = item->brush.color_rgba & ~0xff;
1060         old_thickness = item->brush.thickness;
1061         pt = item->path->coords;
1062         if (!item->brush.variable_width) {
1063           g_string_append_printf(str, "%.2f %.2f m ", pt[0], pt[1]);
1064           for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1065             g_string_append_printf(str, "%.2f %.2f l ", pt[0], pt[1]);
1066           g_string_append_printf(str,"S\n");
1067           old_thickness = item->brush.thickness;
1068         } else {
1069           for (i=0; i<item->path->num_points-1; i++, pt+=2)
1070             g_string_append_printf(str, "%.2f w %.2f %.2f m %.2f %.2f l S\n", 
1071                item->widths[i], pt[0], pt[1], pt[2], pt[3]);
1072           old_thickness = 0.0;
1073         }
1074         if ((item->brush.color_rgba & 0xf0) != 0xf0) // undo transparent
1075           g_string_append(str, "Q ");
1076       }
1077       else if (item->type == ITEM_TEXT) {
1078         if ((item->brush.color_rgba & ~0xff) != old_text_rgba)
1079           g_string_append_printf(str, "%.2f %.2f %.2f rg ",
1080             RGBA_RGB(item->brush.color_rgba));
1081         old_text_rgba = item->brush.color_rgba & ~0xff;
1082         context = gnome_print_pango_create_context(gnome_print_pango_get_default_font_map());
1083         layout = pango_layout_new(context);
1084         g_object_unref(context);
1085         font_desc = pango_font_description_from_string(item->font_name);
1086         pango_font_description_set_absolute_size(font_desc,
1087           item->font_size*PANGO_SCALE);
1088         pango_layout_set_font_description(layout, font_desc);
1089         pango_font_description_free(font_desc);
1090         pango_layout_set_text(layout, item->text, -1);
1091         // this code inspired by the code in libgnomeprint
1092         iter = pango_layout_get_iter(layout);
1093         do {
1094           run = pango_layout_iter_get_run(iter);
1095           if (run==NULL) continue;
1096           pango_layout_iter_get_run_extents (iter, NULL, &logical_rect);
1097           baseline = pango_layout_iter_get_baseline (iter);
1098           if (!PANGO_IS_FC_FONT(run->item->analysis.font)) continue;
1099           fcfont = PANGO_FC_FONT(run->item->analysis.font);
1100           pattern = fcfont->font_pattern;
1101           if (FcPatternGetString(pattern, FC_FILE, 0, (unsigned char **)&filename) != FcResultMatch ||
1102               FcPatternGetInteger(pattern, FC_INDEX, 0, &font_id) != FcResultMatch)
1103                 continue;
1104           ftface = pango_fc_font_lock_face(fcfont);
1105           current_page = -1;
1106           cur_font = NULL;
1107           g_string_append_printf(str, "BT %.2f 0 0 %.2f %.2f %.2f Tm ",
1108             item->font_size, -item->font_size,
1109             item->bbox.left + (gdouble) logical_rect.x/PANGO_SCALE,
1110             item->bbox.top + (gdouble) baseline/PANGO_SCALE);
1111           in_string = FALSE;
1112           for (i=0; i<run->glyphs->num_glyphs; i++) {
1113             glyph_no = run->glyphs->glyphs[i].glyph;
1114             if (FT_IS_SFNT(ftface)) glyph_page = glyph_no/255;
1115             else glyph_page = 0;
1116             if (glyph_page != current_page) {
1117               cur_font = new_pdffont(xref, pdffonts, filename, font_id,
1118                  ftface, glyph_page);
1119               if (in_string) g_string_append(str, ") Tj ");
1120               in_string = FALSE;
1121               g_string_append_printf(str, "/F%d 1 Tf ", cur_font->n_obj);
1122             }
1123             current_page = glyph_page;
1124             FT_Load_Glyph(ftface, glyph_no, FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM);
1125             advance = (int)(ftface->glyph->metrics.horiAdvance * cur_font->ft2ps + 0.5);
1126             if (!in_string) g_string_append_c(str, '(');
1127             in_string = TRUE;
1128             if (cur_font->is_truetype) {
1129               if (glyph_no) glyph_no = (glyph_no%255)+1;
1130               cur_font->glyphmap[glyph_no] = glyph_no;
1131             }
1132             else {
1133               for (j=1; j<=cur_font->num_glyphs_used; j++)
1134                 if (cur_font->glyphmap[j] == glyph_no) break;
1135               if (j==256) j=0; // font is full, what do we do?
1136               if (j>cur_font->num_glyphs_used) {
1137                 cur_font->glyphmap[j] = glyph_no; 
1138                 cur_font->num_glyphs_used++;
1139                 if (FT_Get_Glyph_Name(ftface, glyph_no, tmpstr, 200) == FT_Err_Ok)
1140                   cur_font->glyphpsnames[j] = g_strdup(tmpstr);
1141                 else cur_font->glyphpsnames[j] = g_strdup(".notdef");
1142               }
1143               glyph_no = j;
1144             }
1145             cur_font->advance[glyph_no] = advance;
1146             if (glyph_no=='\\' || glyph_no == '(' || glyph_no == ')' || glyph_no == 10 || glyph_no == 13) 
1147               g_string_append_c(str, '\\');
1148             if (glyph_no==10) g_string_append_c(str,'n');
1149             else if (glyph_no==13) g_string_append_c(str,'r');
1150             else g_string_append_c(str, glyph_no);
1151           }
1152           if (in_string) g_string_append(str, ") Tj ");
1153           g_string_append(str, "ET ");
1154           pango_fc_font_unlock_face(fcfont);
1155         } while (pango_layout_iter_next_run(iter));
1156         pango_layout_iter_free(iter);
1157         g_object_unref(layout);
1158       }
1159     }
1160   }
1161 }
1162
1163 // main printing function
1164
1165 /* we use the following object numbers, starting with n_obj_catalog:
1166     0 the document catalog
1167     1 the page tree
1168     2 the GS for the hiliters
1169     3 ... the page objects
1170 */
1171
1172 gboolean print_to_pdf(char *filename)
1173 {
1174   FILE *f;
1175   GString *pdfbuf, *pgstrm, *zpgstrm, *tmpstr;
1176   int n_obj_catalog, n_obj_pages_offs, n_page, n_obj_bgpix, n_obj_prefix;
1177   int i, startxref;
1178   struct XrefTable xref;
1179   GList *pglist;
1180   struct Page *pg;
1181   gboolean annot, uses_pdf;
1182   gboolean use_hiliter;
1183   struct PdfInfo pdfinfo;
1184   struct PdfObj *obj;
1185   GList *pdffonts, *list;
1186   struct PdfFont *font;
1187   char *tmpbuf;
1188   
1189   f = fopen(filename, "w");
1190   if (f == NULL) return FALSE;
1191   setlocale(LC_NUMERIC, "C");
1192   annot = FALSE;
1193   xref.data = NULL;
1194   uses_pdf = FALSE;
1195   pdffonts = NULL;
1196   for (pglist = journal.pages; pglist!=NULL; pglist = pglist->next) {
1197     pg = (struct Page *)pglist->data;
1198     if (pg->bg->type == BG_PDF) uses_pdf = TRUE;
1199   }
1200   
1201   if (uses_pdf && bgpdf.status != STATUS_NOT_INIT && 
1202       bgpdf.file_contents!=NULL && !strncmp(bgpdf.file_contents, "%PDF-1.", 7)) {
1203     // parse the existing PDF file
1204     pdfbuf = g_string_new_len(bgpdf.file_contents, bgpdf.file_length);
1205     if (pdfbuf->str[7]<'4') pdfbuf->str[7] = '4'; // upgrade to 1.4
1206     annot = pdf_parse_info(pdfbuf, &pdfinfo, &xref);
1207     if (!annot) {
1208       g_string_free(pdfbuf, TRUE);
1209       if (xref.data != NULL) g_free(xref.data);
1210     }
1211   }
1212
1213   if (!annot) {
1214     pdfbuf = g_string_new("%PDF-1.4\n%\370\357\365\362\n");
1215     xref.n_alloc = xref.last = 0;
1216     xref.data = NULL;
1217   }
1218     
1219   // catalog and page tree
1220   n_obj_catalog = xref.last+1;
1221   n_obj_pages_offs = xref.last+4;
1222   make_xref(&xref, n_obj_catalog, pdfbuf->len);
1223   g_string_append_printf(pdfbuf, 
1224     "%d 0 obj\n<< /Type /Catalog /Pages %d 0 R >> endobj\n",
1225      n_obj_catalog, n_obj_catalog+1);
1226   make_xref(&xref, n_obj_catalog+1, pdfbuf->len);
1227   g_string_append_printf(pdfbuf,
1228     "%d 0 obj\n<< /Type /Pages /Kids [", n_obj_catalog+1);
1229   for (i=0;i<journal.npages;i++)
1230     g_string_append_printf(pdfbuf, "%d 0 R ", n_obj_pages_offs+i);
1231   g_string_append_printf(pdfbuf, "] /Count %d >> endobj\n", journal.npages);
1232   make_xref(&xref, n_obj_catalog+2, pdfbuf->len);
1233   g_string_append_printf(pdfbuf, 
1234     "%d 0 obj\n<< /Type /ExtGState /CA %.2f >> endobj\n",
1235      n_obj_catalog+2, ui.hiliter_opacity);
1236   xref.last = n_obj_pages_offs + journal.npages-1;
1237   
1238   for (pglist = journal.pages, n_page = 0; pglist!=NULL;
1239        pglist = pglist->next, n_page++) {
1240     pg = (struct Page *)pglist->data;
1241     
1242     // draw the background and page into pgstrm
1243     pgstrm = g_string_new("");
1244     g_string_printf(pgstrm, "q 1 0 0 -1 0 %.2f cm 1 J 1 j ", pg->height);
1245     n_obj_bgpix = -1;
1246     n_obj_prefix = -1;
1247     if (pg->bg->type == BG_SOLID)
1248       pdf_draw_solid_background(pg, pgstrm);
1249     else if (pg->bg->type == BG_PDF && annot && 
1250              pdfinfo.pages[pg->bg->file_page_seq-1].contents!=NULL) {
1251       make_xref(&xref, xref.last+1, pdfbuf->len);
1252       n_obj_prefix = xref.last;
1253       tmpstr = make_pdfprefix(pdfinfo.pages+(pg->bg->file_page_seq-1),
1254                               pg->width, pg->height);
1255       g_string_append_printf(pdfbuf,
1256         "%d 0 obj\n<< /Length %d >> stream\n%s\nendstream\nendobj\n",
1257         n_obj_prefix, tmpstr->len, tmpstr->str);
1258       g_string_free(tmpstr, TRUE);
1259       g_string_prepend(pgstrm, "Q Q Q ");
1260     }
1261     else if (pg->bg->type == BG_PIXMAP || pg->bg->type == BG_PDF)
1262       n_obj_bgpix = pdf_draw_bitmap_background(pg, pgstrm, &xref, pdfbuf);
1263     // draw the page contents
1264     use_hiliter = FALSE;
1265     pdf_draw_page(pg, pgstrm, &use_hiliter, &xref, &pdffonts);
1266     g_string_append_printf(pgstrm, "Q\n");
1267     
1268     // deflate pgstrm and write it
1269     zpgstrm = do_deflate(pgstrm->str, pgstrm->len);
1270     g_string_free(pgstrm, TRUE);
1271     
1272     make_xref(&xref, xref.last+1, pdfbuf->len);
1273     g_string_append_printf(pdfbuf, 
1274       "%d 0 obj\n<< /Length %d /Filter /FlateDecode>> stream\n",
1275       xref.last, zpgstrm->len);
1276     g_string_append_len(pdfbuf, zpgstrm->str, zpgstrm->len);
1277     g_string_free(zpgstrm, TRUE);
1278     g_string_append(pdfbuf, "endstream\nendobj\n");
1279     
1280     // write the page object
1281     
1282     make_xref(&xref, n_obj_pages_offs+n_page, pdfbuf->len);
1283     g_string_append_printf(pdfbuf, 
1284       "%d 0 obj\n<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %.2f %.2f] ",
1285       n_obj_pages_offs+n_page, n_obj_catalog+1, pg->width, pg->height);
1286     if (n_obj_prefix>0) {
1287       obj = get_pdfobj(pdfbuf, &xref, pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1288       if (obj->type != PDFTYPE_ARRAY) {
1289         free_pdfobj(obj);
1290         obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].contents);
1291       }
1292       g_string_append_printf(pdfbuf, "/Contents [%d 0 R ", n_obj_prefix);
1293       if (obj->type == PDFTYPE_REF) 
1294         g_string_append_printf(pdfbuf, "%d %d R ", obj->intval, obj->num);
1295       if (obj->type == PDFTYPE_ARRAY) {
1296         for (i=0; i<obj->num; i++) {
1297           show_pdfobj(obj->elts[i], pdfbuf);
1298           g_string_append_c(pdfbuf, ' ');
1299         }
1300       }
1301       free_pdfobj(obj);
1302       g_string_append_printf(pdfbuf, "%d 0 R] ", xref.last);
1303     }
1304     else g_string_append_printf(pdfbuf, "/Contents %d 0 R ", xref.last);
1305     g_string_append(pdfbuf, "/Resources ");
1306
1307     if (n_obj_prefix>0)
1308       obj = dup_pdfobj(pdfinfo.pages[pg->bg->file_page_seq-1].resources);
1309     else obj = NULL;
1310     if (obj!=NULL && obj->type!=PDFTYPE_DICT)
1311       { free_pdfobj(obj); obj=NULL; }
1312     if (obj==NULL) {
1313       obj = g_malloc(sizeof(struct PdfObj));
1314       obj->type = PDFTYPE_DICT;
1315       obj->num = 0;
1316       obj->elts = NULL;
1317       obj->names = NULL;
1318     }
1319     add_dict_subentry(pdfbuf, &xref,
1320         obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/PDF"));
1321     if (n_obj_bgpix>0)
1322       add_dict_subentry(pdfbuf, &xref,
1323         obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/ImageC"));
1324     if (use_hiliter)
1325       add_dict_subentry(pdfbuf, &xref,
1326         obj, "/ExtGState", PDFTYPE_DICT, "/XoHi", mk_pdfref(n_obj_catalog+2));
1327     if (n_obj_bgpix>0)
1328       add_dict_subentry(pdfbuf, &xref,
1329         obj, "/XObject", PDFTYPE_DICT, "/ImBg", mk_pdfref(n_obj_bgpix));
1330     for (list=pdffonts; list!=NULL; list = list->next) {
1331       font = (struct PdfFont *)list->data;
1332       if (font->used_in_this_page) {
1333         add_dict_subentry(pdfbuf, &xref,
1334           obj, "/ProcSet", PDFTYPE_ARRAY, NULL, mk_pdfname("/Text"));
1335         tmpbuf = g_strdup_printf("/F%d", font->n_obj);
1336         add_dict_subentry(pdfbuf, &xref,
1337           obj, "/Font", PDFTYPE_DICT, tmpbuf, mk_pdfref(font->n_obj));
1338         g_free(tmpbuf);
1339       }
1340     }
1341     show_pdfobj(obj, pdfbuf);
1342     free_pdfobj(obj);
1343     g_string_append(pdfbuf, " >> endobj\n");
1344   }
1345   
1346   // after the pages, we insert fonts
1347   for (list = pdffonts; list!=NULL; list = list->next) {
1348     font = (struct PdfFont *)list->data;
1349     embed_pdffont(pdfbuf, &xref, font);
1350     g_free(font->filename);
1351     g_free(font->fontname);
1352     g_free(font);
1353   }
1354   g_list_free(pdffonts);
1355   
1356   // PDF trailer
1357   startxref = pdfbuf->len;
1358   if (annot) g_string_append_printf(pdfbuf,
1359         "xref\n%d %d\n", n_obj_catalog, xref.last-n_obj_catalog+1);
1360   else g_string_append_printf(pdfbuf, 
1361         "xref\n0 %d\n0000000000 65535 f \n", xref.last+1);
1362   for (i=n_obj_catalog; i<=xref.last; i++)
1363     g_string_append_printf(pdfbuf, "%010d 00000 n \n", xref.data[i]);
1364   g_string_append_printf(pdfbuf, 
1365     "trailer\n<< /Size %d /Root %d 0 R ", xref.last+1, n_obj_catalog);
1366   if (annot) {
1367     g_string_append_printf(pdfbuf, "/Prev %d ", pdfinfo.startxref);
1368     // keeping encryption info somehow doesn't work.
1369     // xournal can't annotate encrypted PDFs anyway...
1370 /*    
1371     obj = get_dict_entry(pdfinfo.trailerdict, "/Encrypt");
1372     if (obj!=NULL) {
1373       g_string_append_printf(pdfbuf, "/Encrypt ");
1374       show_pdfobj(obj, pdfbuf);
1375     } 
1376 */
1377   }
1378   g_string_append_printf(pdfbuf, 
1379     ">>\nstartxref\n%d\n%%%%EOF\n", startxref);
1380   
1381   g_free(xref.data);
1382   if (annot) {
1383     free_pdfobj(pdfinfo.trailerdict);
1384     if (pdfinfo.pages!=NULL)
1385       for (i=0; i<pdfinfo.npages; i++) {
1386         free_pdfobj(pdfinfo.pages[i].resources);
1387         free_pdfobj(pdfinfo.pages[i].mediabox);
1388         free_pdfobj(pdfinfo.pages[i].contents);
1389       }
1390   }
1391   
1392   setlocale(LC_NUMERIC, "");
1393   if (fwrite(pdfbuf->str, 1, pdfbuf->len, f) < pdfbuf->len) {
1394     fclose(f);
1395     g_string_free(pdfbuf, TRUE);
1396     return FALSE;
1397   }
1398   fclose(f);
1399   g_string_free(pdfbuf, TRUE);
1400   return TRUE;
1401 }
1402
1403 /*********** Printing via libgnomeprint **********/
1404
1405 // does the same job as update_canvas_bg(), but to a print context
1406
1407 void print_background(GnomePrintContext *gpc, struct Page *pg, gboolean *abort)
1408 {
1409   double x, y;
1410   GdkPixbuf *pix;
1411   BgPdfPage *pgpdf;
1412   PopplerPage *pdfpage;
1413   int width, height;
1414   double pgwidth, pgheight;
1415
1416   if (pg->bg->type == BG_SOLID) {
1417     gnome_print_setopacity(gpc, 1.0);
1418     gnome_print_setrgbcolor(gpc, RGBA_RGB(pg->bg->color_rgba));
1419     gnome_print_rect_filled(gpc, 0, 0, pg->width, -pg->height);
1420
1421     if (!ui.print_ruling) return;
1422     if (pg->bg->ruling == RULING_NONE) return;
1423     gnome_print_setrgbcolor(gpc, RGBA_RGB(RULING_COLOR));
1424     gnome_print_setlinewidth(gpc, RULING_THICKNESS);
1425     
1426     if (pg->bg->ruling == RULING_GRAPH) {
1427       for (x=RULING_GRAPHSPACING; x<pg->width-1; x+=RULING_GRAPHSPACING)
1428         gnome_print_line_stroked(gpc, x, 0, x, -pg->height);
1429       for (y=RULING_GRAPHSPACING; y<pg->height-1; y+=RULING_GRAPHSPACING)
1430         gnome_print_line_stroked(gpc, 0, -y, pg->width, -y);
1431       return;
1432     }
1433     
1434     for (y=RULING_TOPMARGIN; y<pg->height-1; y+=RULING_SPACING)
1435       gnome_print_line_stroked(gpc, 0, -y, pg->width, -y);
1436     if (pg->bg->ruling == RULING_LINED) {
1437       gnome_print_setrgbcolor(gpc, RGBA_RGB(RULING_MARGIN_COLOR));
1438       gnome_print_line_stroked(gpc, RULING_LEFTMARGIN, 0, RULING_LEFTMARGIN, -pg->height);
1439     }
1440     return;
1441   }
1442   else 
1443   if (pg->bg->type == BG_PIXMAP || pg->bg->type == BG_PDF) {
1444     if (pg->bg->type == BG_PDF) {
1445       if (!bgpdf.document) return;
1446       pdfpage = poppler_document_get_page(bgpdf.document, pg->bg->file_page_seq-1);
1447       if (!pdfpage) return;
1448       poppler_page_get_size(pdfpage, &pgwidth, &pgheight);
1449       width = (int) (PDFTOPPM_PRINTING_DPI * pgwidth/72.0);
1450       height = (int) (PDFTOPPM_PRINTING_DPI * pgheight/72.0);
1451       pix = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, width, height);
1452       poppler_page_render_to_pixbuf(
1453          pdfpage, 0, 0, width, height, PDFTOPPM_PRINTING_DPI/72.0, 0, pix);
1454       g_object_unref(pdfpage);
1455     }
1456     else pix = g_object_ref(pg->bg->pixbuf);
1457
1458     if (gdk_pixbuf_get_bits_per_sample(pix) != 8 ||
1459         gdk_pixbuf_get_colorspace(pix) != GDK_COLORSPACE_RGB)
1460       { g_object_unref(pix); return; }
1461     gnome_print_gsave(gpc);
1462     gnome_print_scale(gpc, pg->width, pg->height);
1463     gnome_print_translate(gpc, 0., -1.);
1464     if (gdk_pixbuf_get_n_channels(pix) == 3)
1465        gnome_print_rgbimage(gpc, gdk_pixbuf_get_pixels(pix),
1466          gdk_pixbuf_get_width(pix), gdk_pixbuf_get_height(pix), gdk_pixbuf_get_rowstride(pix));
1467     else if (gdk_pixbuf_get_n_channels(pix) == 4)
1468        gnome_print_rgbaimage(gpc, gdk_pixbuf_get_pixels(pix),
1469          gdk_pixbuf_get_width(pix), gdk_pixbuf_get_height(pix), gdk_pixbuf_get_rowstride(pix));
1470     g_object_unref(pix);
1471     gnome_print_grestore(gpc);
1472     return;
1473   }
1474 }
1475
1476 void print_page(GnomePrintContext *gpc, struct Page *pg, int pageno,
1477                 double pgwidth, double pgheight, gboolean *abort)
1478 {
1479   char tmp[10];
1480   gdouble scale;
1481   guint old_rgba;
1482   double old_thickness;
1483   GList *layerlist, *itemlist;
1484   struct Layer *l;
1485   struct Item *item;
1486   int i;
1487   double *pt;
1488   PangoFontDescription *font_desc;
1489   PangoLayout *layout;
1490   
1491   if (pg==NULL) return;
1492   
1493   g_snprintf(tmp, 10, "Page %d", pageno);
1494   gnome_print_beginpage(gpc, (guchar *)tmp);
1495   gnome_print_gsave(gpc);
1496   
1497   scale = MIN(pgwidth/pg->width, pgheight/pg->height)*0.95;
1498   gnome_print_translate(gpc,
1499      (pgwidth - scale*pg->width)/2, (pgheight + scale*pg->height)/2);
1500   gnome_print_scale(gpc, scale, scale);
1501   gnome_print_setlinejoin(gpc, 1); // round
1502   gnome_print_setlinecap(gpc, 1); // round
1503
1504   print_background(gpc, pg, abort);
1505
1506   old_rgba = 0x12345678;    // not any values we use, so we'll reset them
1507   old_thickness = 0.0;
1508
1509   for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
1510     if (*abort) break;
1511     l = (struct Layer *)layerlist->data;
1512     for (itemlist = l->items; itemlist!=NULL; itemlist = itemlist->next) {
1513       if (*abort) break;
1514       item = (struct Item *)itemlist->data;
1515       if (item->type == ITEM_STROKE || item->type == ITEM_TEXT) {
1516         if ((item->brush.color_rgba & ~0xff) != (old_rgba & ~0xff))
1517           gnome_print_setrgbcolor(gpc, RGBA_RGB(item->brush.color_rgba));
1518         if ((item->brush.color_rgba & 0xff) != (old_rgba & 0xff))
1519           gnome_print_setopacity(gpc, RGBA_ALPHA(item->brush.color_rgba));
1520         old_rgba = item->brush.color_rgba;
1521       }
1522       if (item->type == ITEM_STROKE) {    
1523         if (item->brush.thickness != old_thickness)
1524           gnome_print_setlinewidth(gpc, item->brush.thickness);
1525         gnome_print_newpath(gpc);
1526         pt = item->path->coords;
1527         if (!item->brush.variable_width) {
1528           gnome_print_moveto(gpc, pt[0], -pt[1]);
1529           for (i=1, pt+=2; i<item->path->num_points; i++, pt+=2)
1530             gnome_print_lineto(gpc, pt[0], -pt[1]);
1531           gnome_print_stroke(gpc);
1532           old_thickness = item->brush.thickness;
1533         } else {
1534           for (i=0; i<item->path->num_points-1; i++, pt+=2) {
1535             gnome_print_moveto(gpc, pt[0], -pt[1]);
1536             gnome_print_setlinewidth(gpc, item->widths[i]);
1537             gnome_print_lineto(gpc, pt[2], -pt[3]);
1538             gnome_print_stroke(gpc);
1539           }
1540           old_thickness = 0.0;
1541         }
1542       }
1543       if (item->type == ITEM_TEXT) {
1544         layout = gnome_print_pango_create_layout(gpc);
1545         font_desc = pango_font_description_from_string(item->font_name);
1546         pango_font_description_set_absolute_size(font_desc,
1547           item->font_size*PANGO_SCALE);
1548         pango_layout_set_font_description(layout, font_desc);
1549         pango_font_description_free(font_desc);
1550         pango_layout_set_text(layout, item->text, -1);
1551         gnome_print_moveto(gpc, item->bbox.left, -item->bbox.top);
1552         gnome_print_pango_layout(gpc, layout);
1553         g_object_unref(layout);
1554       }
1555     }
1556   }
1557   
1558   gnome_print_grestore(gpc);
1559   gnome_print_showpage(gpc);
1560 }
1561
1562 void cb_print_abort(GtkDialog *dialog, gint response, gboolean *abort)
1563 {
1564   *abort = TRUE;
1565 }
1566
1567 void print_job_render(GnomePrintJob *gpj, int fromPage, int toPage)
1568 {
1569   GnomePrintConfig *config;
1570   GnomePrintContext *gpc;
1571   GtkWidget *wait_dialog;
1572   double pgwidth, pgheight;
1573   int i;
1574   gboolean abort;
1575   
1576   config = gnome_print_job_get_config(gpj);
1577   gnome_print_config_get_page_size(config, &pgwidth, &pgheight);
1578   g_object_unref(G_OBJECT(config));
1579
1580   gpc = gnome_print_job_get_context(gpj);
1581
1582   abort = FALSE;
1583   wait_dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
1584      GTK_MESSAGE_INFO, GTK_BUTTONS_CANCEL, "Preparing print job");
1585   gtk_widget_show(wait_dialog);
1586   g_signal_connect(wait_dialog, "response", G_CALLBACK (cb_print_abort), &abort);
1587   
1588   for (i = fromPage; i <= toPage; i++) {
1589 #if GTK_CHECK_VERSION(2,6,0)
1590     if (!gtk_check_version(2, 6, 0))
1591       gtk_message_dialog_format_secondary_text(
1592              GTK_MESSAGE_DIALOG(wait_dialog), "Page %d", i+1); 
1593 #endif
1594     while (gtk_events_pending()) gtk_main_iteration();
1595     print_page(gpc, (struct Page *)g_list_nth_data(journal.pages, i), i+1,
1596                                              pgwidth, pgheight, &abort);
1597     if (abort) break;
1598   }
1599 #if GTK_CHECK_VERSION(2,6,0)
1600   if (!gtk_check_version(2, 6, 0))
1601     gtk_message_dialog_format_secondary_text(
1602               GTK_MESSAGE_DIALOG(wait_dialog), "Finalizing...");
1603 #endif
1604   while (gtk_events_pending()) gtk_main_iteration();
1605
1606   gnome_print_context_close(gpc);  
1607   g_object_unref(G_OBJECT(gpc));  
1608
1609   gnome_print_job_close(gpj);
1610   if (!abort) gnome_print_job_print(gpj);
1611   g_object_unref(G_OBJECT(gpj));
1612
1613   gtk_widget_destroy(wait_dialog);
1614 }