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