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