c1484bb4a9e84296e4e26c4d30e19221097264f7
[swftools.git] / lib / devices / pdf.c
1 /* pdf.c
2
3    Part of the swftools package.
4
5    Copyright (c) 2007 Matthias Kramm <kramm@quiss.org> 
6  
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
20
21 #include <stdlib.h>
22 #include <stdio.h>
23 #include <stdarg.h>
24 #include <unistd.h>
25 #include <assert.h>
26 #include <memory.h>
27 #include <pdflib.h>
28 #include <math.h>
29 #include "../os.h"
30 #include "../q.h"
31 #include "../log.h"
32 #include "../jpeg.h"
33 #include "../types.h"
34 #include "../mem.h"
35 #include "../log.h"
36 #include "../gfxdevice.h"
37 #include "../gfxtools.h"
38 #include "../gfximage.h"
39 #include "../gfxfont.h"
40
41 typedef struct _internal {
42     PDF* p;
43     
44     char config_addblankpages;
45     double config_xpad;
46     double config_ypad;
47     int config_maxdpi;
48     int config_mindpi;
49
50     int width,height;
51     int num_pages;
52
53     char*tempfile;
54     char*page_opts;
55     double lastx,lasty;
56     gfxfontlist_t*fontlist;
57
58     char has_matrix;
59     double m00, m01, m10, m11;
60 } internal_t;
61
62 static void restore_matrix(internal_t*i)
63 {
64     if(i->has_matrix) {
65         PDF_restore(i->p);
66         i->has_matrix=0;
67         i->m00 = 0;
68         i->m01 = 0;
69         i->m10 = 0;
70         i->m11 = 0;
71     }
72 }
73 static void set_matrix(internal_t*i, double m00, double m01, double m10, double m11)
74 {
75     restore_matrix(i);
76
77     i->m00 = m00;
78     i->m01 = m01;
79     i->m10 = m10;
80     i->m11 = m11;
81
82     PDF_save(i->p);
83     PDF_setmatrix(i->p, m00, -m01, m10, -m11, 0, i->height+2*i->config_ypad);
84     i->has_matrix = 1;
85 }
86 static void reset_matrix(internal_t*i)
87 {
88     set_matrix(i, 1.0, 0.0, 0.0, 1.0);
89 }
90 static void transform_back(internal_t*i, double x, double y, double *ox, double *oy)
91 {
92     double det = i->m00*i->m11 - i->m10*i->m01;
93     if(!det) {
94         msg("<warning> Codependent text matrix");
95         *ox=*oy=0;
96         return;
97     }
98     *ox = (x*i->m11 - i->m10*y)/det;
99     *oy = (i->m00*y - x*i->m01)/det;
100 }
101
102 void pdf_startpage(gfxdevice_t*dev, int width, int height)
103 {
104     internal_t*i = (internal_t*)dev->internal;
105
106     if(!i->tempfile) {
107         i->tempfile = strdup(mktempname(0, "pdf"));
108
109         PDF_begin_document(i->p, i->tempfile, 0, "");
110         //PDF_set_value(i->p, "compress", 0);
111         PDF_set_parameter(i->p, "usercoordinates", "true");
112         PDF_set_parameter(i->p, "topdown", "true");
113     }
114
115     int width_plus_pad = width+floor(i->config_xpad*2);
116     int height_plus_pad = height+floor(i->config_ypad*2);
117     PDF_begin_page_ext(i->p, width_plus_pad, height_plus_pad, i->page_opts);
118     PDF_set_value(i->p, "CropBox/llx", 0);
119     PDF_set_value(i->p, "CropBox/lly", 0);
120     PDF_set_value(i->p, "CropBox/urx", width_plus_pad);
121     PDF_set_value(i->p, "CropBox/ury", height_plus_pad);
122     if(i->config_xpad || i->config_ypad) {
123         PDF_set_value(i->p, "TrimBox/llx", i->config_xpad);
124         PDF_set_value(i->p, "TrimBox/lly", i->config_ypad);
125         PDF_set_value(i->p, "TrimBox/urx", i->config_xpad+width);
126         PDF_set_value(i->p, "TrimBox/ury", i->config_ypad+height);
127     }
128
129     PDF_set_parameter(i->p, "fillrule", "evenodd");
130     i->width = width;
131     i->height = height;
132     i->num_pages++;
133
134     reset_matrix(i);
135 }
136
137 int pdf_setparameter(gfxdevice_t*dev, const char*key, const char*value)
138 {
139     internal_t*i = (internal_t*)dev->internal;
140     if(!strcmp(key, "addblankpages")) {
141         i->config_addblankpages = atoi(value);
142     } else if(!strcmp(key, "maxdpi")) {
143         i->config_maxdpi = atoi(value);
144     } else if(!strcmp(key, "mindpi")) {
145         i->config_mindpi = atoi(value);
146     } else if(!strcmp(key, "xpad")) {
147         i->config_xpad = atof(value);
148     } else if(!strcmp(key, "ypad")) {
149         i->config_ypad = atof(value);
150     }
151     return 0;
152 }
153
154
155 static int mkline(gfxline_t*line, PDF*p, double mx, double my, double scale, char fill)
156 {
157     double x=0,y=0;
158     char first = 1;
159     int ret = 0;
160     gfxline_t*free_line = 0;
161     if(fill) {
162         line = gfxline_restitch(gfxline_clone(line));
163         free_line = line;
164     }
165     while(line) {
166         if(line->type == gfx_moveTo && (x!=line->x || y!=line->y || first)) {
167             first = 0;
168             PDF_moveto(p, line->x*scale+mx, line->y*scale+my);
169         } else if(line->type == gfx_lineTo) {
170             PDF_lineto(p, line->x*scale+mx, line->y*scale+my);
171             ret = 1;
172         } else {
173             /* when converting a quadratic bezier to a cubic bezier, the
174                two new control points are both 2/3 the way from the
175                endpoints to the old control point */
176             double c1x = (x + line->sx*2)/3;
177             double c1y = (y + line->sy*2)/3;
178             double c2x = (line->x + line->sx*2)/3;
179             double c2y = (line->y + line->sy*2)/3;
180             PDF_curveto(p, c1x*scale+mx, c1y*scale+my, 
181                            c2x*scale+mx, c2y*scale+my, 
182                            line->x*scale+mx, line->y*scale+my);
183             ret = 1;
184         }
185         x = line->x;
186         y = line->y;
187         line = line->next;
188     }
189     if(free_line)
190         gfxline_free(free_line);
191     return ret;
192 }
193
194 void pdf_startclip(gfxdevice_t*dev, gfxline_t*line)
195 {
196     internal_t*i = (internal_t*)dev->internal;
197     
198     restore_matrix(i);
199     PDF_save(i->p);
200     
201     if(mkline(line, i->p, i->config_xpad, i->config_ypad, 1.0, 1))
202         PDF_clip(i->p);
203     else   
204         ; // TODO: strictly speaking, an empty clip clears everything
205     
206     reset_matrix(i);
207 }
208 void pdf_endclip(gfxdevice_t*dev)
209 {
210     internal_t*i = (internal_t*)dev->internal;
211     restore_matrix(i);
212     PDF_restore(i->p);
213 }
214 void pdf_stroke(gfxdevice_t*dev, gfxline_t*line, gfxcoord_t width, gfxcolor_t*color, gfx_capType cap_style, gfx_joinType joint_style, gfxcoord_t miterLimit)
215 {
216     internal_t*i = (internal_t*)dev->internal;
217     if(width<1e-6)
218         return;
219     reset_matrix(i);
220     PDF_setlinewidth(i->p, width);
221     PDF_setlinecap(i->p, cap_style==gfx_capButt?0:(cap_style==gfx_capRound?1:2));
222     PDF_setlinejoin(i->p, joint_style==gfx_joinMiter?0:(joint_style==gfx_joinRound?1:2));
223     
224     PDF_setrgbcolor_stroke(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
225
226     if(joint_style==gfx_joinMiter)
227         PDF_setmiterlimit(i->p, miterLimit);
228     if(mkline(line, i->p, i->config_xpad, i->config_ypad, 1.0, 0))
229         PDF_stroke(i->p);
230 }
231
232 void pdf_fill(gfxdevice_t*dev, gfxline_t*line, gfxcolor_t*color)
233 {
234     internal_t*i = (internal_t*)dev->internal;
235     reset_matrix(i);
236     PDF_setrgbcolor_fill(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
237     /*
238        pdf-x (pdf 1.3) doesn't support opacityfill
239     if(color->a!=255) {
240         char opacityfill[80];
241         sprintf(opacityfill, "opacityfill %f", color->a/256.0);
242         int gstate = PDF_create_gstate(i->p, opacityfill);
243         PDF_set_gstate(i->p, gstate);
244     }*/
245         
246     if(mkline(line, i->p, i->config_xpad, i->config_ypad, 1.0, 1)) {
247         PDF_fill(i->p);
248     }
249 }
250
251 void pdf_fillbitmap(gfxdevice_t*dev, gfxline_t*line, gfximage_t*img, gfxmatrix_t*matrix, gfxcxform_t*cxform)
252 {
253     internal_t*i = (internal_t*)dev->internal;
254
255     int t,size=img->width*img->height;
256     int has_alpha=0;
257     for(t=0;t<size;t++) {
258         if(img->data[t].a!=255) {
259             has_alpha=1;
260             break;
261         }
262     }
263
264     double w = sqrt(matrix->m00*matrix->m00+matrix->m01*matrix->m01);
265     double h = sqrt(matrix->m10*matrix->m10+matrix->m11*matrix->m11);
266     double l1 = w*img->width;
267     double l2 = h*img->height;
268
269     double dpi_x = 72.0 / w;
270     double dpi_y = 72.0 / h;
271     double dpi = dpi_x>dpi_y?dpi_x:dpi_y;
272     gfximage_t*rescaled_image = 0;
273     if(i->config_maxdpi && dpi > i->config_maxdpi) {
274         int newwidth = img->width*i->config_maxdpi/dpi;
275         int newheight = img->height*i->config_maxdpi/dpi;
276         rescaled_image = gfximage_rescale(img, newwidth, newheight);
277         msg("<notice> Downscaling %dx%d image (dpi %f, %.0fx%.0f on page) to %dx%d (dpi %d)", 
278                 img->width, img->height, dpi, l1, l2, newwidth, newheight, i->config_maxdpi);
279         img = rescaled_image;
280     }
281     if(i->config_mindpi && dpi < i->config_mindpi && img->width>1 && img->height>1) {
282         msg("<error> Found image of size %dx%d with dpi %f, minimum allowed dpi is %d", 
283                 img->width, img->height, dpi, i->config_mindpi);
284         exit(1);
285     }
286
287     char tempfile[128];
288     mktempname(tempfile, "jpg");
289
290     gfximage_save_jpeg(img, tempfile, 96);
291
292     int imgid=-1;
293     if(has_alpha) {
294         char tempfile2[128];
295         mktempname(tempfile2, "jpg");
296         int t;
297         int size = img->width*img->height;
298         unsigned char*alpha = malloc(size);
299         for(t=0;t<size;t++) {
300             alpha[t] = img->data[t].a;
301         }
302         jpeg_save_gray(alpha, img->width, img->height, 97, tempfile2);
303         free(alpha);
304         int maskid = PDF_load_image(i->p, "jpeg", tempfile2, 0, "mask");
305         unlink(tempfile2);
306         char masked[80];
307         if(maskid<0) {
308             msg("<error> Couldn't process mask jpeg of size %dx%d: error code %d", img->width, img->height, maskid);
309             return;
310         }
311         sprintf(masked, "masked %d", maskid);
312         imgid = PDF_load_image(i->p, "jpeg", tempfile, 0, masked);
313     } else {
314         imgid = PDF_load_image(i->p, "jpeg", tempfile, 0, "");
315     }
316
317     if(imgid<0) {
318         msg("<error> Couldn't process jpeg of size %dx%d: error code %d, file %s", img->width, img->height, imgid, tempfile);
319         return;
320     }
321     unlink(tempfile);
322     
323     char options[80];
324     set_matrix(i, matrix->m00, matrix->m01, matrix->m10, matrix->m11);
325     /* an image's (0,0) is at the lower left corner */
326     double x=matrix->tx + i->config_xpad + matrix->m10*img->height;
327     double y=matrix->ty + i->config_ypad + matrix->m11*img->height;
328     double tx,ty;
329     transform_back(i, x, y, &tx, &ty);
330     PDF_place_image(i->p, imgid, tx, ty, 1.0);
331     PDF_close_image(i->p, imgid);
332
333     if(rescaled_image)
334         gfximage_free(rescaled_image);
335 }
336
337 void pdf_fillgradient(gfxdevice_t*dev, gfxline_t*line, gfxgradient_t*gradient, gfxgradienttype_t type, gfxmatrix_t*matrix)
338 {
339     internal_t*i = (internal_t*)dev->internal;
340 }
341
342 static const char type3 = 0;
343 static const char ttf = 1;
344
345 void pdf_addfont(gfxdevice_t*dev, gfxfont_t*font)
346 {
347     internal_t*i = (internal_t*)dev->internal;
348
349     int num = font->num_glyphs<256-32?font->num_glyphs:256-32;
350     if(type3) {
351         int fontid = 0;
352         if(!gfxfontlist_hasfont(i->fontlist, font)) {
353
354             static int fontnr = 1;
355             char fontname[32];
356             sprintf(fontname, "font%d", fontnr++);
357             int l = strlen(fontname);
358             char fontname2[64];
359             int t;
360             for(t=0;t<l+1;t++) {
361                 fontname2[t*2+0] = fontname[t];
362                 fontname2[t*2+1] = 0;
363             }
364
365             PDF_begin_font(i->p, fontname2, l*2, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, "");
366             for(t=0;t<num;t++) {
367                 gfxglyph_t*g = &font->glyphs[t];
368                 gfxbbox_t bbox = gfxline_getbbox(g->line);
369                 char name[32];
370                 sprintf(name, "chr%d", t+32);
371                 PDF_encoding_set_char(i->p, fontname, t+32, name, 0);
372                 PDF_begin_glyph(i->p, name, g->advance, bbox.xmin/64.0, bbox.ymin/64.0, bbox.xmax/64.0, bbox.ymax/64.0);
373                 if(mkline(g->line, i->p, 0, 0, 1.0/64.0, 1))
374                     PDF_fill(i->p);
375                 PDF_end_glyph(i->p);
376             }
377             PDF_end_font(i->p);
378             fontid = PDF_load_font(i->p, fontname2, l*2, fontname, "");
379             
380             i->fontlist = gfxfontlist_addfont2(i->fontlist, font, (void*)(ptroff_t)fontid);
381         }
382     } else if(ttf) {
383         int fontid = 0;
384         if(!gfxfontlist_hasfont(i->fontlist, font)) {
385             char fontname[32],filename[32],fontname2[64];
386             static int fontnr = 1;
387             sprintf(fontname, "font%d", fontnr);
388             sprintf(filename, "font%d.ttf", fontnr);
389             fontnr++;
390             const char*old_id = font->id;
391             font->id = fontname;
392             int t;
393             for(t=0;t<num;t++) {
394                 font->glyphs[t].unicode = 32+t;
395             }
396             font->max_unicode = 0;
397             font->unicode2glyph = 0;
398             gfxfont_save(font, filename);
399             font->id=old_id;
400             
401 #ifdef RUN_TTX
402             /* for testing the generated fonts: run everything through ttx (fonttools) */
403             char cmd[256];
404             sprintf(cmd, "mv %s.ttf test.ttf", fontname);system(cmd);
405             system("rm -f test.ttx");
406             if(system("ttx test.ttf")&0xff00) exit(1);
407             sprintf(cmd, "mv test.ttf %s.old.ttf", fontname, fontname);system(cmd);
408             sprintf(cmd, "ttx test.ttx;mv test.ttf %s.ttf", fontname);system(cmd);
409             sprintf(cmd, "rm -f test.ttx");system(cmd);
410 #endif
411            
412             int l = strlen(fontname);
413             for(t=0;t<l+1;t++) {
414                 fontname2[t*2+0] = fontname[t];
415                 fontname2[t*2+1] = 0;
416             }
417             
418             fontid = PDF_load_font(i->p, fontname2, l*2, "host", "embedding=true");
419             i->fontlist = gfxfontlist_addfont2(i->fontlist, font, (void*)(ptroff_t)fontid);
420             unlink(filename);
421         }
422     }
423 }
424
425 void pdf_drawchar(gfxdevice_t*dev, gfxfont_t*font, int glyphnr, gfxcolor_t*color, gfxmatrix_t*matrix)
426 {
427     internal_t*i = (internal_t*)dev->internal;
428
429     if(!font)
430         return;
431
432     gfxglyph_t*glyph = &font->glyphs[glyphnr];
433     char as_shape = 0;
434     if(!type3 && !ttf) {msg("<warning> No type3 enabled. Drawing char %d as shape", glyphnr);as_shape=1;}
435     if(glyphnr>256-32) {msg("<warning> Drawing char %d as shape (not < 224)", glyphnr);as_shape=1;}
436         
437     if(as_shape) {
438         reset_matrix(i);
439         PDF_setrgbcolor_fill(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
440         gfxline_t*line2 = gfxline_clone(glyph->line);
441         gfxline_transform(line2, matrix);
442         if(mkline(line2, i->p, i->config_xpad, i->config_ypad, 1.0, 1)) {
443             PDF_fill(i->p);
444         }
445         gfxline_free(line2);
446     } else {
447         assert(gfxfontlist_hasfont(i->fontlist, font));
448         int fontid = (int)(ptroff_t)gfxfontlist_getuserdata(i->fontlist, font->id);
449
450         gfxmatrix_t m = *matrix;
451
452         m.m00*=64;
453         m.m01*=64;
454         m.m10*=64;
455         m.m11*=64;
456         if(ttf) {
457             m.m10 = -m.m10;
458             m.m11 = -m.m11;
459         }
460
461         if(!(fabs(m.m00 - i->m00) < 1e-6 &&
462              fabs(m.m01 - i->m01) < 1e-6 &&
463              fabs(m.m10 - i->m10) < 1e-6 &&
464              fabs(m.m11 - i->m11) < 1e-6)) {
465             set_matrix(i, m.m00, m.m01, m.m10, m.m11);
466         }
467         double tx, ty;
468         transform_back(i, m.tx+i->config_xpad, m.ty+i->config_ypad, &tx, &ty);
469         
470         PDF_setfont(i->p, fontid, ttf?16.0:1.0);
471         PDF_setrgbcolor_fill(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
472
473         char name[32];
474         sprintf(name, "%c", glyphnr+32);
475
476         if(fabs(tx - i->lastx) > 0.001 || ty != i->lasty) {
477             PDF_show_xy2(i->p, name, strlen(name), tx, ty);
478         } else {
479             PDF_show2(i->p, name, strlen(name));
480         }
481
482         i->lastx = tx + glyph->advance;
483         i->lasty = ty;
484     }
485 }
486
487 void pdf_drawlink(gfxdevice_t*dev, gfxline_t*line, const char*action)
488 {
489     internal_t*i = (internal_t*)dev->internal;
490 }
491
492 void pdf_endpage(gfxdevice_t*dev)
493 {
494     internal_t*i = (internal_t*)dev->internal;
495     restore_matrix(i);
496     PDF_end_page(i->p);
497 }
498
499 typedef struct pdfresult_internal {
500     char*tempfile;
501 } pdfresult_internal_t;
502
503 void pdfresult_destroy(gfxresult_t*gfx)
504 {
505     pdfresult_internal_t*i = (pdfresult_internal_t*)gfx->internal;
506     unlink(i->tempfile);
507     free(i->tempfile);
508     free(gfx->internal);gfx->internal = 0;
509     free(gfx);
510 }
511
512 int pdfresult_save(gfxresult_t*gfx, const char*filename)
513 {
514     pdfresult_internal_t*i = (pdfresult_internal_t*)gfx->internal;
515     FILE*fi = fopen(i->tempfile, "rb");
516     FILE*fo = fopen(filename, "wb");
517     if(!fo) {
518         perror(filename);
519         return -1;
520     }
521     char buffer[4096];
522     int size = 0;
523     while((size = fread(buffer, 1, 4096, fi))) {
524         fwrite(buffer, 1, size, fo);
525     }
526     fclose(fi);
527     fclose(fo);
528     return 0;
529 }
530
531 void* pdfresult_get(gfxresult_t*gfx, const char*name)
532 {
533     return 0; 
534 }
535
536 gfxresult_t* pdf_finish(gfxdevice_t*dev)
537 {
538     internal_t*i = (internal_t*)dev->internal;
539
540     if(i->config_addblankpages) {
541         int mod = i->num_pages%i->config_addblankpages;
542         if(mod) {
543             int count = i->config_addblankpages - mod;
544             int t;
545             for(t=0;t<count;t++) {
546                 dev->startpage(dev, i->width, i->height);
547                 dev->endpage(dev);
548             }
549         }
550     }
551    
552     PDF_end_document(i->p, "");
553     //PDF_close(i->p);
554     PDF_delete(i->p);
555
556     gfxresult_t*result = (gfxresult_t*)malloc(sizeof(gfxresult_t));
557     memset(result, 0, sizeof(gfxresult_t));
558     result->save = pdfresult_save;
559     result->get = pdfresult_get;
560     result->destroy = pdfresult_destroy;
561     result->internal = 0;
562     result->internal = malloc(sizeof(pdfresult_internal_t));
563     pdfresult_internal_t*ri = (pdfresult_internal_t*)result->internal;
564     ri->tempfile = i->tempfile;i->tempfile=0;
565     free(dev->internal);dev->internal = 0;i=0;
566     return result;
567 }
568
569 void gfxdevice_pdf_init(gfxdevice_t*dev)
570 {
571     internal_t*i = (internal_t*)rfx_calloc(sizeof(internal_t));
572     memset(dev, 0, sizeof(gfxdevice_t));
573
574     dev->name = "pdf";
575
576     dev->internal = i;
577
578     dev->setparameter = pdf_setparameter;
579     dev->startpage = pdf_startpage;
580     dev->startclip = pdf_startclip;
581     dev->endclip = pdf_endclip;
582     dev->stroke = pdf_stroke;
583     dev->fill = pdf_fill;
584     dev->fillbitmap = pdf_fillbitmap;
585     dev->fillgradient = pdf_fillgradient;
586     dev->addfont = pdf_addfont;
587     dev->drawchar = pdf_drawchar;
588     dev->drawlink = pdf_drawlink;
589     dev->endpage = pdf_endpage;
590     dev->finish = pdf_finish;
591
592     i->page_opts = "";
593     i->lastx = -1e38;
594     i->lasty = -1e38;
595     i->has_matrix = 0;
596     i->p = PDF_new();
597 }