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