more ttf bug fixes
[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+2*i->config_ypad);
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     reset_matrix(i);
232     PDF_setrgbcolor_fill(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
233     /*
234        pdf-x (pdf 1.3) doesn't support opacityfill
235     if(color->a!=255) {
236         char opacityfill[80];
237         sprintf(opacityfill, "opacityfill %f", color->a/256.0);
238         int gstate = PDF_create_gstate(i->p, opacityfill);
239         PDF_set_gstate(i->p, gstate);
240     }*/
241         
242     if(mkline(line, i->p, i->config_xpad, i->config_ypad, 1.0, 1)) {
243         PDF_fill(i->p);
244     }
245 }
246
247 void pdf_fillbitmap(gfxdevice_t*dev, gfxline_t*line, gfximage_t*img, gfxmatrix_t*matrix, gfxcxform_t*cxform)
248 {
249     internal_t*i = (internal_t*)dev->internal;
250
251     int t,size=img->width*img->height;
252     int has_alpha=0;
253     for(t=0;t<size;t++) {
254         if(img->data[t].a!=255) {
255             has_alpha=1;
256             break;
257         }
258     }
259
260     double w = sqrt(matrix->m00*matrix->m00+matrix->m01*matrix->m01);
261     double h = sqrt(matrix->m10*matrix->m10+matrix->m11*matrix->m11);
262     double l1 = w*img->width;
263     double l2 = h*img->height;
264
265     double dpi_x = 72.0 / w;
266     double dpi_y = 72.0 / h;
267     double dpi = dpi_x>dpi_y?dpi_x:dpi_y;
268     gfximage_t*rescaled_image = 0;
269     if(i->config_maxdpi && dpi > i->config_maxdpi) {
270         int newwidth = img->width*i->config_maxdpi/dpi;
271         int newheight = img->height*i->config_maxdpi/dpi;
272         rescaled_image = gfximage_rescale(img, newwidth, newheight);
273         msg("<notice> Downscaling %dx%d image (dpi %f, %.0fx%.0f on page) to %dx%d (dpi %d)", 
274                 img->width, img->height, dpi, l1, l2, newwidth, newheight, i->config_maxdpi);
275         img = rescaled_image;
276     }
277     if(i->config_mindpi && dpi < i->config_mindpi && img->width>1 && img->height>1) {
278         msg("<error> Found image of size %dx%d with dpi %f, minimum allowed dpi is %d", 
279                 img->width, img->height, dpi, i->config_mindpi);
280         exit(1);
281     }
282
283     char tempfile[128];
284     mktempname(tempfile);
285
286     gfximage_save_jpeg(img, tempfile, 96);
287
288     int imgid=-1;
289     if(has_alpha) {
290         char tempfile2[128];
291         mktempname(tempfile2);
292         int t;
293         int size = img->width*img->height;
294         unsigned char*alpha = malloc(size);
295         for(t=0;t<size;t++) {
296             alpha[t] = img->data[t].a;
297         }
298         jpeg_save_gray(alpha, img->width, img->height, 97, tempfile2);
299         free(alpha);
300         int maskid = PDF_load_image(i->p, "jpeg", tempfile2, 0, "mask");
301         unlink(tempfile2);
302         char masked[80];
303         if(maskid<0) {
304             msg("<error> Couldn't process mask jpeg of size %dx%d: error code %d", img->width, img->height, maskid);
305             return;
306         }
307         sprintf(masked, "masked %d", maskid);
308         imgid = PDF_load_image(i->p, "jpeg", tempfile, 0, masked);
309     } else {
310         imgid = PDF_load_image(i->p, "jpeg", tempfile, 0, "");
311     }
312
313     if(imgid<0) {
314         msg("<error> Couldn't process jpeg of size %dx%d: error code %d, file %s", img->width, img->height, imgid, tempfile);
315         return;
316     }
317     unlink(tempfile);
318     
319     char options[80];
320     set_matrix(i, matrix->m00, matrix->m01, matrix->m10, matrix->m11);
321     /* an image's (0,0) is at the lower left corner */
322     double x=matrix->tx + i->config_xpad + matrix->m10*img->height;
323     double y=matrix->ty + i->config_ypad + matrix->m11*img->height;
324     double tx,ty;
325     transform_back(i, x, y, &tx, &ty);
326     PDF_place_image(i->p, imgid, tx, ty, 1.0);
327     PDF_close_image(i->p, imgid);
328
329     if(rescaled_image)
330         gfximage_free(rescaled_image);
331 }
332
333 void pdf_fillgradient(gfxdevice_t*dev, gfxline_t*line, gfxgradient_t*gradient, gfxgradienttype_t type, gfxmatrix_t*matrix)
334 {
335     internal_t*i = (internal_t*)dev->internal;
336 }
337
338 static const char type3 = 0;
339 static const char ttf = 1;
340
341 void pdf_addfont(gfxdevice_t*dev, gfxfont_t*font)
342 {
343     internal_t*i = (internal_t*)dev->internal;
344
345     int num = font->num_glyphs<256-32?font->num_glyphs:256-32;
346     if(type3) {
347         int fontid = 0;
348         if(!gfxfontlist_hasfont(i->fontlist, font)) {
349
350             static int fontnr = 1;
351             char fontname[32];
352             sprintf(fontname, "font%d", fontnr++);
353             int l = strlen(fontname);
354             char fontname2[64];
355             int t;
356             for(t=0;t<l+1;t++) {
357                 fontname2[t*2+0] = fontname[t];
358                 fontname2[t*2+1] = 0;
359             }
360
361             PDF_begin_font(i->p, fontname2, l*2, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, "");
362             for(t=0;t<num;t++) {
363                 gfxglyph_t*g = &font->glyphs[t];
364                 gfxbbox_t bbox = gfxline_getbbox(g->line);
365                 char name[32];
366                 sprintf(name, "chr%d", t+32);
367                 PDF_encoding_set_char(i->p, fontname, t+32, name, 0);
368                 PDF_begin_glyph(i->p, name, g->advance, bbox.xmin/64.0, bbox.ymin/64.0, bbox.xmax/64.0, bbox.ymax/64.0);
369                 if(mkline(g->line, i->p, 0, 0, 1.0/64.0, 1))
370                     PDF_fill(i->p);
371                 PDF_end_glyph(i->p);
372             }
373             PDF_end_font(i->p);
374             fontid = PDF_load_font(i->p, fontname2, l*2, fontname, "");
375             
376             i->fontlist = gfxfontlist_addfont2(i->fontlist, font, (void*)(ptroff_t)fontid);
377         }
378     } else if(ttf) {
379         int fontid = 0;
380         if(!gfxfontlist_hasfont(i->fontlist, font)) {
381             char fontname[32],filename[32],fontname2[64];
382             static int fontnr = 1;
383             sprintf(fontname, "font%d", fontnr);
384             sprintf(filename, "font%d.ttf", fontnr);
385             fontnr++;
386             const char*old_id = font->id;
387             font->id = fontname;
388             int t;
389             for(t=0;t<num;t++) {
390                 font->glyphs[t].unicode = 32+t;
391             }
392             font->unicode2glyph = 0;
393             gfxfont_save(font, filename);
394             font->id=old_id;
395            
396             int l = strlen(font->id);
397             for(t=0;t<l+1;t++) {
398                 fontname2[t*2+0] = fontname[t];
399                 fontname2[t*2+1] = 0;
400             }
401             fontid = PDF_load_font(i->p, fontname2, l*2, "host", "embedding=true");
402             i->fontlist = gfxfontlist_addfont2(i->fontlist, font, (void*)(ptroff_t)fontid);
403         }
404     }
405 }
406
407 void pdf_drawchar(gfxdevice_t*dev, gfxfont_t*font, int glyphnr, gfxcolor_t*color, gfxmatrix_t*matrix)
408 {
409     internal_t*i = (internal_t*)dev->internal;
410
411     if(!font)
412         return;
413
414     gfxglyph_t*glyph = &font->glyphs[glyphnr];
415     char as_shape = 0;
416     if(!type3 && !ttf) {msg("<warning> No type3 enabled. Drawing char %d as shape", glyphnr);as_shape=1;}
417     if(glyphnr>256-32) {msg("<warning> Drawing char %d as shape (not < 224)", glyphnr);as_shape=1;}
418         
419     if(as_shape) {
420         reset_matrix(i);
421         PDF_setrgbcolor_fill(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
422         gfxline_t*line2 = gfxline_clone(glyph->line);
423         gfxline_transform(line2, matrix);
424         if(mkline(line2, i->p, i->config_xpad, i->config_ypad, 1.0, 1)) {
425             PDF_fill(i->p);
426         }
427         gfxline_free(line2);
428     } else {
429         assert(gfxfontlist_hasfont(i->fontlist, font));
430         int fontid = (int)(ptroff_t)gfxfontlist_getuserdata(i->fontlist, font->id);
431
432         gfxmatrix_t m = *matrix;
433
434         m.m00*=64;
435         m.m01*=64;
436         m.m10*=64;
437         m.m11*=64;
438         if(ttf) {
439             m.m10 = -m.m10;
440             m.m11 = -m.m11;
441         }
442
443         if(!(fabs(m.m00 - i->m00) < 1e-6 &&
444              fabs(m.m01 - i->m01) < 1e-6 &&
445              fabs(m.m10 - i->m10) < 1e-6 &&
446              fabs(m.m11 - i->m11) < 1e-6)) {
447             set_matrix(i, m.m00, m.m01, m.m10, m.m11);
448         }
449         double tx, ty;
450         transform_back(i, m.tx+i->config_xpad, m.ty+i->config_ypad, &tx, &ty);
451         
452         PDF_setfont(i->p, fontid, ttf?16.0:1.0);
453         PDF_setrgbcolor_fill(i->p, color->r/255.0, color->g/255.0, color->b/255.0);
454
455         char name[32];
456         sprintf(name, "%c", glyphnr+32);
457
458         if(fabs(tx - i->lastx) > 0.001 || ty != i->lasty) {
459             PDF_show_xy2(i->p, name, strlen(name), tx, ty);
460         } else {
461             PDF_show2(i->p, name, strlen(name));
462         }
463
464         i->lastx = tx + glyph->advance;
465         i->lasty = ty;
466     }
467 }
468
469 void pdf_drawlink(gfxdevice_t*dev, gfxline_t*line, const char*action)
470 {
471     internal_t*i = (internal_t*)dev->internal;
472 }
473
474 void pdf_endpage(gfxdevice_t*dev)
475 {
476     internal_t*i = (internal_t*)dev->internal;
477     restore_matrix(i);
478     PDF_end_page(i->p);
479 }
480
481 typedef struct pdfresult_internal {
482     char*tempfile;
483 } pdfresult_internal_t;
484
485 void pdfresult_destroy(gfxresult_t*gfx)
486 {
487     pdfresult_internal_t*i = (pdfresult_internal_t*)gfx->internal;
488     unlink(i->tempfile);
489     free(i->tempfile);
490     free(gfx->internal);gfx->internal = 0;
491     free(gfx);
492 }
493
494 int pdfresult_save(gfxresult_t*gfx, const char*filename)
495 {
496     pdfresult_internal_t*i = (pdfresult_internal_t*)gfx->internal;
497     FILE*fi = fopen(i->tempfile, "rb");
498     FILE*fo = fopen(filename, "wb");
499     if(!fo) {
500         perror(filename);
501         return -1;
502     }
503     char buffer[4096];
504     int size = 0;
505     while((size = fread(buffer, 1, 4096, fi))) {
506         fwrite(buffer, 1, size, fo);
507     }
508     fclose(fi);
509     fclose(fo);
510     return 0;
511 }
512
513 void* pdfresult_get(gfxresult_t*gfx, const char*name)
514 {
515     return 0; 
516 }
517
518 gfxresult_t* pdf_finish(gfxdevice_t*dev)
519 {
520     internal_t*i = (internal_t*)dev->internal;
521
522     if(i->config_addblankpages) {
523         int mod = i->num_pages%i->config_addblankpages;
524         if(mod) {
525             int count = i->config_addblankpages - mod;
526             int t;
527             for(t=0;t<count;t++) {
528                 dev->startpage(dev, i->width, i->height);
529                 dev->endpage(dev);
530             }
531         }
532     }
533    
534     PDF_end_document(i->p, "");
535     //PDF_close(i->p);
536     PDF_delete(i->p);
537
538     gfxresult_t*result = (gfxresult_t*)malloc(sizeof(gfxresult_t));
539     memset(result, 0, sizeof(gfxresult_t));
540     result->save = pdfresult_save;
541     result->get = pdfresult_get;
542     result->destroy = pdfresult_destroy;
543     result->internal = 0;
544     result->internal = malloc(sizeof(pdfresult_internal_t));
545     pdfresult_internal_t*ri = (pdfresult_internal_t*)result->internal;
546     ri->tempfile = i->tempfile;i->tempfile=0;
547     free(dev->internal);dev->internal = 0;i=0;
548     return result;
549 }
550
551 void gfxdevice_pdf_init(gfxdevice_t*dev)
552 {
553     internal_t*i = (internal_t*)rfx_calloc(sizeof(internal_t));
554     memset(dev, 0, sizeof(gfxdevice_t));
555
556     dev->name = "pdf";
557
558     dev->internal = i;
559
560     dev->setparameter = pdf_setparameter;
561     dev->startpage = pdf_startpage;
562     dev->startclip = pdf_startclip;
563     dev->endclip = pdf_endclip;
564     dev->stroke = pdf_stroke;
565     dev->fill = pdf_fill;
566     dev->fillbitmap = pdf_fillbitmap;
567     dev->fillgradient = pdf_fillgradient;
568     dev->addfont = pdf_addfont;
569     dev->drawchar = pdf_drawchar;
570     dev->drawlink = pdf_drawlink;
571     dev->endpage = pdf_endpage;
572     dev->finish = pdf_finish;
573
574     i->page_opts = "";
575     i->lastx = -1e38;
576     i->lasty = -1e38;
577     i->has_matrix = 0;
578     i->p = PDF_new();
579 }