added '-s zoomtowidth' option to pdf2swf
[swftools.git] / lib / pdf / pdf.cc
1 #include "../gfxdevice.h"
2 #include "../gfxsource.h"
3 #include "../devices/rescale.h"
4 #include "../log.h"
5 #include "config.h"
6 #include "GlobalParams.h"
7 #include "InfoOutputDev.h"
8 #include "GFXOutputDev.h"
9 #include "FullBitmapOutputDev.h"
10 #include "BitmapOutputDev.h"
11 #include "../mem.h"
12 #include "pdf.h"
13 #define NO_ARGPARSER
14 #include "../args.h"
15
16 static double zoom = 72; /* xpdf: 86 */
17 static int zoomtowidth = 0;
18 static int multiply = 1;
19 static char* global_page_range = 0;
20
21 static int globalparams_count=0;
22
23 typedef struct _parameter
24 {
25     struct _parameter *next;
26     const char*name;
27     const char*value;
28 } parameter_t;
29 typedef struct _parameterlist
30 {
31     parameter_t* device_config;
32     parameter_t* device_config_next;
33 } parameterlist_t;
34
35 typedef struct _pdf_page_info
36 {
37     int xMin, yMin, xMax, yMax;
38     int width,height;
39     int number_of_images;
40     int number_of_links;
41     int number_of_fonts;
42     char has_info;
43 } pdf_page_info_t;
44
45 typedef struct _pdf_doc_internal
46 {
47     char config_bitmap_optimizing;
48     char config_full_bitmap_optimizing;
49     char config_print;
50     parameterlist_t parameters;
51
52     int protect;
53     int nocopy;
54     int noprint;
55     
56     PDFDoc*doc;
57     Object docinfo;
58     InfoOutputDev*info;
59
60     pdf_page_info_t*pages;
61     char*filename;
62
63     /* page map */
64     int*pagemap;
65     int pagemap_size;
66     int pagemap_pos;
67
68     gfxsource_t*parent;
69 } pdf_doc_internal_t;
70
71 typedef struct _pdf_page_internal
72 {
73 } pdf_page_internal_t;
74
75 typedef struct _dev_output_internal
76 {
77     CommonOutputDev*outputDev;
78 } dev_output_internal_t;
79
80
81 typedef struct _gfxsource_internal
82 {
83     parameterlist_t parameters;
84 } gfxsource_internal_t;
85
86
87 static const char* dirseparator()
88 {
89 #ifdef WIN32
90     return "\\";
91 #else
92     return "/";
93 #endif
94 }
95
96 static void storeDeviceParameter(parameterlist_t*i, const char*name, const char*value)
97 {
98     parameter_t*o = i->device_config;
99     while(o) {
100         if(!strcmp(name, o->name)) {
101             /* overwrite old value */
102             free((void*)o->value);
103             o->value = strdup(value);
104             return;
105         }
106         o = o->next;
107     }
108     parameter_t*p = new parameter_t();
109     p->name = strdup(name);
110     p->value = strdup(value);
111     p->next = 0;
112
113     if(i->device_config_next) {
114         i->device_config_next->next = p;
115         i->device_config_next = p;
116     } else {
117         i->device_config = p;
118         i->device_config_next = p;
119     }
120 }
121
122
123
124 void pdfpage_destroy(gfxpage_t*pdf_page)
125 {
126     pdf_page_internal_t*i= (pdf_page_internal_t*)pdf_page->internal;
127     free(pdf_page->internal);pdf_page->internal = 0;
128     free(pdf_page);pdf_page=0;
129 }
130
131 static void render2(gfxpage_t*page, gfxdevice_t*dev, int x,int y, int x1,int y1,int x2,int y2)
132 {
133     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
134     gfxsource_internal_t*i = (gfxsource_internal_t*)pi->parent->internal;
135
136     if(!pi->config_print && pi->nocopy) {msg("<fatal> PDF disallows copying");exit(0);}
137     if(pi->config_print && pi->noprint) {msg("<fatal> PDF disallows printing");exit(0);}
138
139     CommonOutputDev*outputDev = 0;
140     if(pi->config_full_bitmap_optimizing) {
141         FullBitmapOutputDev*d = new FullBitmapOutputDev(pi->info, pi->doc);
142         outputDev = (CommonOutputDev*)d;
143     } else if(pi->config_bitmap_optimizing) {
144         BitmapOutputDev*d = new BitmapOutputDev(pi->info, pi->doc);
145         outputDev = (CommonOutputDev*)d;
146     } else {
147         GFXOutputDev*d = new GFXOutputDev(pi->info, pi->doc);
148         outputDev = (CommonOutputDev*)d;
149     }
150     /* pass global parameters to PDF driver*/
151     parameter_t*p = i->parameters.device_config;
152     while(p) {
153         outputDev->setParameter(p->name, p->value);
154         p = p->next;
155     }
156     p = pi->parameters.device_config;
157     while(p) {
158         outputDev->setParameter(p->name, p->value);
159         p = p->next;
160     }
161
162     outputDev->setPageMap(pi->pagemap, pi->pagemap_pos);
163     outputDev->setMove(x,y);
164     outputDev->setClip(x1,y1,x2,y2);
165
166     gfxdevice_t* middev=0;
167     if(multiply>1) {
168         middev = (gfxdevice_t*)malloc(sizeof(gfxdevice_t));
169         gfxdevice_rescale_init(middev, 0x00000000, 0, 0, 1.0 / multiply);
170         gfxdevice_rescale_setdevice(middev, dev);
171         middev->setparameter(middev, "protect", "1");
172         dev = middev;
173     } 
174         
175     if(!pi) {
176         msg("<fatal> pdf_page_render: Parent PDF this page belongs to doesn't exist yet/anymore");
177         return;
178     }
179
180     if(!pi->pages[page->nr-1].has_info) {
181         msg("<fatal> pdf_page_render: page %d was previously set as not-to-render via the \"pages\" option", page->nr);
182         return;
183     }
184
185     if(pi->protect) {
186         dev->setparameter(dev, "protect", "1");
187     }
188
189     outputDev->setDevice(dev);
190     pi->doc->displayPage((OutputDev*)outputDev, page->nr, zoom*multiply, zoom*multiply, /*rotate*/0, true, true, pi->config_print);
191     pi->doc->processLinks((OutputDev*)outputDev, page->nr);
192     outputDev->finishPage();
193     outputDev->setDevice(0);
194     delete outputDev;
195
196     if(middev) {
197         gfxdevice_rescale_setdevice(middev, 0x00000000);
198         middev->finish(middev);
199     }
200
201 }
202
203     
204 void pdfpage_render(gfxpage_t*page, gfxdevice_t*output)
205 {
206     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
207     render2(page, output, 0,0, 0,0,0,0);
208 }
209
210 void pdfpage_rendersection(gfxpage_t*page, gfxdevice_t*output, gfxcoord_t x, gfxcoord_t y, gfxcoord_t _x1, gfxcoord_t _y1, gfxcoord_t _x2, gfxcoord_t _y2)
211 {
212     pdf_doc_internal_t*pi = (pdf_doc_internal_t*)page->parent->internal;
213
214     int x1=(int)_x1,y1=(int)_y1,x2=(int)_x2,y2=(int)_y2;
215     if((x1|y1|x2|y2)==0) x2++;
216
217     render2(page, output, (int)x*multiply,(int)y*multiply,
218                           (int)x1*multiply,(int)y1*multiply,(int)x2*multiply,(int)y2*multiply);
219 }
220
221 void pdf_doc_destroy(gfxdocument_t*gfx)
222 {
223     pdf_doc_internal_t*i= (pdf_doc_internal_t*)gfx->internal;
224
225     delete i->doc; i->doc=0;
226     free(i->pages); i->pages = 0;
227
228     i->docinfo.free();
229
230     if(i->filename) {
231         free(i->filename);i->filename=0;
232     }
233     
234     if(i->info) {
235         delete i->info;i->info=0;
236     }
237
238     free(gfx->internal);gfx->internal=0;
239     free(gfx);gfx=0;
240
241     if(global_page_range) {
242         free(global_page_range);
243         global_page_range = 0;
244     }
245     
246     /*globalparams_count--;
247     if(!globalparams_count) {
248         delete globalParams;
249         globalParams = 0;
250         globalparams_count = 0;
251     }*/
252 }
253
254 static void add_page_to_map(gfxdocument_t*gfx, int pdfpage, int outputpage)
255 {
256     pdf_doc_internal_t*i= (pdf_doc_internal_t*)gfx->internal;
257     if(pdfpage < 0)
258         return;
259     if(pdfpage >= i->pagemap_size) {
260         int oldlen = i->pagemap_size;
261         i->pagemap_size = oldlen + 1024;
262         if(pdfpage > i->pagemap_size)
263             i->pagemap_size = pdfpage+1;
264
265         if(i->pages) {
266             i->pagemap = (int*)malloc(i->pagemap_size*sizeof(int));
267         } else {
268             i->pagemap = (int*)realloc(i->pages, i->pagemap_size*sizeof(int));
269         }
270         memset(&i->pagemap[oldlen], -1, (i->pagemap_size-oldlen)*sizeof(int));
271     }
272     i->pagemap[pdfpage] = outputpage;
273     if(pdfpage > i->pagemap_pos)
274         i->pagemap_pos = pdfpage;
275 }
276
277 void pdf_doc_set_parameter(gfxdocument_t*gfx, const char*name, const char*value)
278 {
279     pdf_doc_internal_t*i= (pdf_doc_internal_t*)gfx->internal;
280     if(!strcmp(name, "pagemap")) {
281         int pdfpage=0, outputpage=0;
282         sscanf(value,"%d:%d", &pdfpage, &outputpage);
283         add_page_to_map(gfx, pdfpage, outputpage);
284     } else if(!strcmp(name, "poly2bitmap")) {
285         i->config_bitmap_optimizing = atoi(value);
286     } else if(!strcmp(name, "bitmapfonts") || !strcmp(name, "bitmap")) {
287         i->config_full_bitmap_optimizing = atoi(value);
288     } else if(!strcmp(name, "asprint")) {
289         i->config_print = 1;
290     } else {
291         storeDeviceParameter(&i->parameters, name, value);
292     }
293 }
294
295 gfxpage_t* pdf_doc_getpage(gfxdocument_t*doc, int page)
296 {
297     pdf_doc_internal_t*di= (pdf_doc_internal_t*)doc->internal;
298
299     if(page < 1 || page > doc->num_pages)
300         return 0;
301     
302     gfxpage_t* pdf_page = (gfxpage_t*)malloc(sizeof(gfxpage_t));
303     pdf_page_internal_t*pi= (pdf_page_internal_t*)malloc(sizeof(pdf_page_internal_t));
304     memset(pi, 0, sizeof(pdf_page_internal_t));
305     pdf_page->internal = pi;
306
307     pdf_page->destroy = pdfpage_destroy;
308     pdf_page->render = pdfpage_render;
309     pdf_page->rendersection = pdfpage_rendersection;
310     pdf_page->width = di->pages[page-1].width;
311     pdf_page->height = di->pages[page-1].height;
312
313     pdf_page->parent = doc;
314     pdf_page->nr = page;
315     return pdf_page;
316 }
317
318 static char*getInfoString(Dict *infoDict, const char *key)
319 {
320     Object obj;
321     GString *s1, *s2;
322     int i;
323
324     if (infoDict && infoDict->lookup((char*)key, &obj)->isString()) {
325         s1 = obj.getString();
326         if ((s1->getChar(0) & 0xff) == 0xfe &&
327             (s1->getChar(1) & 0xff) == 0xff) {
328             s2 = new GString();
329             for (i = 2; i < obj.getString()->getLength(); i += 2) {
330               if (s1->getChar(i) == '\0') {
331                 s2->append(s1->getChar(i+1));
332               } else {
333                 delete s2;
334                 s2 = new GString("<unicode>");
335                 break;
336               }
337             }
338             char*ret = strdup(s2->getCString());
339             delete s2;
340             obj.free();
341             return ret;
342         } else {
343             char*ret = strdup(s1->getCString());
344             obj.free();
345             return ret;
346         }
347     }
348     return strdup("");
349 }
350
351 static char*getInfoDate(Dict *infoDict, const char *key) 
352 {
353     Object obj;
354     char *s;
355
356     if (infoDict && infoDict->lookup((char*)key, &obj)->isString()) {
357         s = obj.getString()->getCString();
358         if (s[0] == 'D' && s[1] == ':') {
359           s += 2;
360         }
361         char*ret = strdup(s);
362         obj.free();
363         return ret;
364     }
365     return strdup("");
366 }
367
368 char* pdf_doc_getinfo(gfxdocument_t*doc, const char*name)
369 {
370     pdf_doc_internal_t*i= (pdf_doc_internal_t*)doc->internal;
371     if(!strcmp(name, "title")) return getInfoString(i->docinfo.getDict(), "Title");
372     else if(!strcmp(name, "subject")) return getInfoString(i->docinfo.getDict(), "Subject");
373     else if(!strcmp(name, "keywords")) return getInfoString(i->docinfo.getDict(), "Keywords");
374     else if(!strcmp(name, "author")) return getInfoString(i->docinfo.getDict(), "Author");
375     else if(!strcmp(name, "creator")) return getInfoString(i->docinfo.getDict(), "Creator");
376     else if(!strcmp(name, "producer")) return getInfoString(i->docinfo.getDict(), "Producer");
377     else if(!strcmp(name, "creationdate")) return getInfoDate(i->docinfo.getDict(), "CreationDate");
378     else if(!strcmp(name, "moddate")) return getInfoDate(i->docinfo.getDict(), "ModDate");
379     else if(!strcmp(name, "linearized")) return strdup(i->doc->isLinearized() ? "yes" : "no");
380     else if(!strcmp(name, "tagged")) return strdup(i->doc->getStructTreeRoot()->isDict() ? "yes" : "no");
381     else if(!strcmp(name, "encrypted")) return strdup(i->doc->isEncrypted() ? "yes" : "no");
382     else if(!strcmp(name, "oktoprint")) return strdup(i->doc->okToPrint() ? "yes" : "no");
383     else if(!strcmp(name, "oktocopy")) return strdup(i->doc->okToCopy() ? "yes" : "no");
384     else if(!strcmp(name, "oktochange")) return strdup(i->doc->okToChange() ? "yes" : "no");
385     else if(!strcmp(name, "oktoaddnotes")) return strdup(i->doc->okToAddNotes() ? "yes" : "no");
386     else if(!strcmp(name, "version")) { 
387         char buf[32];
388         sprintf(buf, "%.1f", i->doc->getPDFVersion());
389         return strdup(buf);
390     }
391     return 0;
392 }
393
394
395 static void pdf_set_parameter(gfxsource_t*src, const char*name, const char*value)
396 {
397     gfxsource_internal_t*i = (gfxsource_internal_t*)src->internal;
398     parameterlist_t*p = &i->parameters;
399     msg("<verbose> setting parameter %s to \"%s\"", name, value);
400     if(!strncmp(name, "fontdir", strlen("fontdir"))) {
401         addGlobalFontDir(value);
402     } else if(!strcmp(name, "pages")) {
403         global_page_range = strdup(value);
404     } else if(!strncmp(name, "font", strlen("font")) && name[4]!='q') {
405         addGlobalFont(value);
406     } else if(!strncmp(name, "languagedir", strlen("languagedir"))) {
407         addGlobalLanguageDir(value);
408     } else if(!strcmp(name, "zoomtowidth")) {
409         zoomtowidth = atoi(value);
410     } else if(!strcmp(name, "zoom")) {
411         char buf[80];
412         zoom = atof(value);
413     } else if(!strcmp(name, "jpegdpi") || !strcmp(name, "ppmdpi")) {
414         msg("<error> %s not supported anymore. Please use jpegsubpixels/ppmsubpixels");
415     } else if(!strcmp(name, "multiply")) {
416         multiply = atoi(value);
417     } else if(!strcmp(name, "help")) {
418         printf("\nPDF device global parameters:\n");
419         printf("fontdir=<dir>     a directory with additional fonts\n");
420         printf("font=<filename>   an additional font filename\n");
421         printf("pages=<range>     the range of pages to convert (example: pages=1-100,210-)\n");
422         printf("zoom=<dpi>        the resultion (default: 72)\n");
423         printf("languagedir=<dir> Add an xpdf language directory\n");
424         printf("multiply=<times>  Render everything at <times> the resolution\n");
425         printf("poly2bitmap       Convert graphics to bitmaps\n");
426         printf("bitmap            Convert everything to bitmaps\n");
427     }   
428 }
429
430 void pdf_doc_prepare(gfxdocument_t*doc, gfxdevice_t*dev)
431 {
432     pdf_doc_internal_t*i= (pdf_doc_internal_t*)doc->internal;
433     i->info->dumpfonts(dev);
434 }
435
436 static gfxdocument_t*pdf_open(gfxsource_t*src, const char*filename)
437 {
438     gfxsource_internal_t*isrc = (gfxsource_internal_t*)src->internal;
439     gfxdocument_t*pdf_doc = (gfxdocument_t*)malloc(sizeof(gfxdocument_t));
440     memset(pdf_doc, 0, sizeof(gfxdocument_t));
441     pdf_doc_internal_t*i= (pdf_doc_internal_t*)malloc(sizeof(pdf_doc_internal_t));
442     memset(i, 0, sizeof(pdf_doc_internal_t));
443     i->parent = src;
444     pdf_doc->internal = i;
445     char*userPassword=0;
446     
447     i->filename = strdup(filename);
448
449     char*x = 0;
450     if((x = strchr(filename, '|'))) {
451         *x = 0;
452         userPassword = x+1;
453     }
454     
455     GString *fileName = new GString(filename);
456     GString *userPW;
457
458     // open PDF file
459     if (userPassword && userPassword[0]) {
460       userPW = new GString(userPassword);
461     } else {
462       userPW = NULL;
463     }
464     i->doc = new PDFDoc(fileName, userPW);
465     if (userPW) {
466       delete userPW;
467     }
468     if (!i->doc->isOk()) {
469         printf("xpdf reports document as broken.\n");
470         return 0;
471     }
472
473     // get doc info
474     i->doc->getDocInfo(&i->docinfo);
475     
476     pdf_doc->num_pages = i->doc->getNumPages();
477     i->protect = 0;
478     if (i->doc->isEncrypted()) {
479           if(!i->doc->okToCopy()) {
480               i->nocopy = 1;
481           }
482           if(!i->doc->okToPrint()) {
483               i->noprint = 1;
484           }
485           if(!i->doc->okToChange() || !i->doc->okToAddNotes())
486               i->protect = 1;
487     }
488         
489     if(zoomtowidth && i->doc->getNumPages()) {
490         Page*page = i->doc->getCatalog()->getPage(1);
491         PDFRectangle *r = page->getCropBox();
492         double width_before = r->x2 - r->x1;
493         zoom = 72.0 * zoomtowidth / width_before;
494         msg("<notice> Rendering at %f DPI. (Page width at 72 DPI: %f, target width: %d)", zoom, width_before, zoomtowidth);
495     }
496
497     i->info = new InfoOutputDev(i->doc->getXRef());
498     int t;
499     i->pages = (pdf_page_info_t*)malloc(sizeof(pdf_page_info_t)*pdf_doc->num_pages);
500     memset(i->pages,0,sizeof(pdf_page_info_t)*pdf_doc->num_pages);
501     for(t=1;t<=pdf_doc->num_pages;t++) {
502         if(!global_page_range || is_in_range(t, global_page_range)) {
503             i->doc->displayPage((OutputDev*)i->info, t, zoom, zoom, /*rotate*/0, /*usemediabox*/true, /*crop*/true, i->config_print);
504             i->doc->processLinks((OutputDev*)i->info, t);
505             i->pages[t-1].xMin = i->info->x1;
506             i->pages[t-1].yMin = i->info->y1;
507             i->pages[t-1].xMax = i->info->x2;
508             i->pages[t-1].yMax = i->info->y2;
509             i->pages[t-1].width = i->info->x2 - i->info->x1;
510             i->pages[t-1].height = i->info->y2 - i->info->y1;
511             i->pages[t-1].number_of_images = i->info->num_ppm_images + i->info->num_jpeg_images;
512             i->pages[t-1].number_of_links = i->info->num_links;
513             i->pages[t-1].number_of_fonts = i->info->num_fonts;
514             i->pages[t-1].has_info = 1;
515         }
516     }
517
518     pdf_doc->get = 0;
519     pdf_doc->destroy = pdf_doc_destroy;
520     pdf_doc->set_parameter = pdf_doc_set_parameter;
521     pdf_doc->getinfo = pdf_doc_getinfo;
522     pdf_doc->getpage = pdf_doc_getpage;
523     pdf_doc->prepare = pdf_doc_prepare;
524     
525     return pdf_doc;
526
527 }
528     
529 void pdf_destroy(gfxsource_t*src)
530 {
531     if(!src->internal)
532         return;
533     gfxsource_internal_t*i = (gfxsource_internal_t*)src->internal;
534     
535     parameter_t*p = i->parameters.device_config;
536     while(p) {
537         parameter_t*next = p->next;
538         if(p->name) free((void*)p->name);p->name = 0;
539         if(p->value) free((void*)p->value);p->value =0;
540         p->next = 0;delete p;
541         p = next;
542     }
543     i->parameters.device_config=i->parameters.device_config_next=0;
544     
545     free(src->internal);src->internal=0;
546
547     delete globalParams;globalParams = 0;
548     free(src);
549 }
550
551 gfxsource_t*gfxsource_pdf_create()
552 {
553     gfxsource_t*src = (gfxsource_t*)malloc(sizeof(gfxsource_t));
554     memset(src, 0, sizeof(gfxsource_t));
555     src->set_parameter = pdf_set_parameter;
556     src->open = pdf_open;
557     src->destroy = pdf_destroy;
558     src->internal = malloc(sizeof(gfxsource_internal_t));
559     memset(src->internal, 0, sizeof(gfxsource_internal_t));
560
561     if(!globalParams) {
562         globalParams = new GFXGlobalParams();
563         //globalparams_count++;
564     }
565     
566
567     return src;
568 }