added -O option
[swftools.git] / src / pdf2swf.c
1 /* pdf2swf.c
2    main routine for pdf2swf(1)
3
4    Part of the swftools package.
5    
6    Copyright (c) 2001,2002,2003 Matthias Kramm <kramm@quiss.org> 
7  
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include "../config.h"
28 #ifdef HAVE_DIRENT_H
29 #include <dirent.h>
30 #endif
31 #include "../lib/args.h"
32 #include "../lib/os.h"
33 #include "../lib/rfxswf.h"
34 #include "../lib/devices/swf.h"
35 #include "../lib/devices/arts.h"
36 #include "../lib/devices/record.h"
37 #include "../lib/pdf/pdf.h"
38 #include "../lib/log.h"
39
40 #define SWFDIR concatPaths(getInstallationPath(), "swfs")
41
42 gfxsource_t*driver;
43
44 static char * outputname = 0;
45 static int loglevel = 3;
46 static char * pagerange = 0;
47 static char * filename = 0;
48 static char * password = 0;
49 static int zlib = 0;
50
51 static char * preloader = 0;
52 static char * viewer = 0;
53 static int xnup = 1;
54 static int ynup = 1;
55
56 static int info_only = 0;
57
58 static int flatten = 0;
59
60 char* fontpaths[256];
61 int fontpathpos = 0;
62
63 int move_x=0;
64 int move_y=0;
65 int custom_move = 0;
66 int clip_x1=0,clip_y1=0,clip_x2=0,clip_y2=0;
67 int custom_clip = 0;
68
69 static int system_quiet=0;
70
71 int systemf(const char* format, ...)
72 {
73     char buf[1024];
74     int ret;
75     va_list arglist;
76     va_start(arglist, format);
77     vsprintf(buf, format, arglist);
78     va_end(arglist);
79
80     if(!system_quiet) {
81         printf("%s\n", buf);
82         fflush(stdout);
83     }
84     ret = system(buf);
85     if(ret) {
86         fprintf(stderr, "system() returned %d\n", ret);
87         exit(ret);
88     }
89     return ret;
90 }
91
92 int args_callback_option(char*name,char*val) {
93     if (!strcmp(name, "o"))
94     {
95         outputname = val;
96         return 1;
97     }
98     else if (!strcmp(name, "v"))
99     {
100         loglevel ++;
101         setConsoleLogging(loglevel);
102         return 0;
103     }
104     else if (!strcmp(name, "2"))
105     {
106         xnup = 2;
107         ynup = 1;
108         return 0;
109     }
110     else if (!strcmp(name, "4"))
111     {
112         xnup = 2;
113         ynup = 2;
114         return 0;
115     }
116     else if (!strcmp(name, "9"))
117     {
118         xnup = 3;
119         ynup = 3;
120         return 0;
121     }
122     else if (!strcmp(name, "q"))
123     {
124         loglevel --;
125         setConsoleLogging(loglevel);
126         system_quiet = 1;
127         return 0;
128     }
129     else if (name[0]=='p')
130     {
131         /* check whether the page range follows the p directly, like 
132            in -p1,2 */
133         do {
134             name++;
135         } while(*name == 32 || *name == 13 || *name == 10 || *name == '\t');
136
137         if(*name) {
138             pagerange = name;
139             return 0;
140         } 
141         pagerange = val;        
142         return 1;
143     }
144     else if (!strcmp(name, "P"))
145     {
146         password = val;
147         return 1;
148     }
149     else if (!strcmp(name, "c"))
150     {
151         char*s = strdup(val);
152         char*x1 = strtok(s, ":");
153         char*y1 = strtok(0, ":");
154         char*x2 = strtok(0, ":");
155         char*y2 = strtok(0, ":");
156         if(!(x1 && y1 && x2 && y2)) {
157             fprintf(stderr, "-m option requires four arguments, <x1>:<y1>:<x2>:<y2>\n");
158             exit(1);
159         }
160         custom_clip = 1;
161         clip_x1 = atoi(x1);
162         clip_y1 = atoi(y1);
163         clip_x2 = atoi(x2);
164         clip_y2 = atoi(y2);
165         free(s);
166         return 1;
167     }
168     else if (!strcmp(name, "m"))
169     {
170         char*s = strdup(val);
171         char*c = strchr(s, ':');
172         if(!c) {
173             fprintf(stderr, "-m option requires two arguments, <x>:<y>\n");
174             exit(1);
175         }
176         *c = 0;
177         custom_move = 1;
178         move_x = atoi(val);
179         move_y = atoi(c+1);
180         free(s);
181         return 1;
182     }
183     else if (!strcmp(name, "s"))
184     {
185         char*s = strdup(val);
186         char*c = strchr(s, '=');
187         if(c && *c && c[1])  {
188             *c = 0;
189             c++;
190             driver->set_parameter(driver, s,c);
191         }
192         else
193             driver->set_parameter(driver, s,"1");
194         return 1;
195     }
196     else if (!strcmp(name, "S"))
197     {
198         driver->set_parameter(driver, "drawonlyshapes", "1");
199         return 0;
200     }
201     else if (!strcmp(name, "i"))
202     {
203         driver->set_parameter(driver, "ignoredraworder", "1");
204         return 0;
205     }
206     else if (!strcmp(name, "z"))
207     {
208         driver->set_parameter(driver, "enablezlib", "1");
209         zlib = 1;
210         return 0;
211     }
212     else if (!strcmp(name, "n"))
213     {
214         driver->set_parameter(driver, "opennewwindow", "1");
215         return 0;
216     }
217     else if (!strcmp(name, "I"))
218     {
219         info_only = 1;
220         return 0;
221     }
222     else if (!strcmp(name, "t"))
223     {
224         driver->set_parameter(driver, "insertstop", "1");
225         return 0;
226     }
227     else if (!strcmp(name, "T"))
228     {
229         if(!strcasecmp(val, "mx"))
230             driver->set_parameter(driver, "flashversion", "6");
231         else
232             driver->set_parameter(driver, "flashversion", val);
233
234         return 1;
235     }
236     else if (!strcmp(name, "f"))
237     {
238         driver->set_parameter(driver, "storeallcharacters", "1");
239         driver->set_parameter(driver, "extrafontdata", "1");
240         return 0;
241     }
242     else if (!strcmp(name, "w"))
243     {
244         driver->set_parameter(driver, "linksopennewwindow", "0");
245         return 0;
246     }
247     else if (!strcmp(name, "O"))
248     {
249         int level = 1;
250         int ret=0;
251         if(val&& val[0] && val[1]==0 && isdigit(val[0])) {
252             level = atoi(val);
253             ret=1;
254         }
255         if(level>=1)
256             driver->set_parameter(driver, "poly2bitmap", "1");
257         if(level>=2)
258             driver->set_parameter(driver, "bitmapfonts", "1");
259         if(level>=3)
260             driver->set_parameter(driver, "ignoredraworder", "1");
261
262         flatten = 1;
263         return ret;
264     }
265     else if (!strcmp(name, "G"))
266     {
267         flatten = 1;
268         return 0;
269     }
270     else if (!strcmp(name, "F"))
271     {
272         char *s = strdup(val);
273         int l = strlen(s);
274         while(l && s[l-1]=='/') {
275             s[l-1] = 0;
276             l--;
277         }
278         fontpaths[fontpathpos++] = s;
279         return 1;
280     }
281     else if (!strcmp(name, "l"))
282     {
283         char buf[256];
284         sprintf(buf, "%s/default_loader.swf", SWFDIR);
285         preloader = strdup(buf);
286         return 0;
287     }
288     else if (!strcmp(name, "b"))
289     {
290         char buf[256];
291         sprintf(buf, "%s/default_viewer.swf", SWFDIR);
292         viewer = strdup(buf);
293         return 0;
294     }
295     else if (!strcmp(name, "L"))
296     {
297         if(val)
298         {
299             preloader = val;
300         }
301         else
302         {
303             systemf("ls %s/*_loader.swf", SWFDIR);
304             if(!system_quiet)
305                 printf("\n");
306             exit(1);
307         }
308         return 1;
309     }
310     else if (!strcmp(name, "B"))
311     {
312         if(val)
313         {
314             viewer = val;
315         }
316         else
317         {
318             systemf("ls %s/*_viewer.swf", SWFDIR);
319             if(!system_quiet)
320                 printf("\n");
321             exit(1);
322         }
323         return 1;
324     }
325     else if (!strcmp(name, "j"))
326     {
327         if(name[1]) {
328             driver->set_parameter(driver, "jpegquality", &name[1]);
329             return 0;
330         } else {
331             driver->set_parameter(driver, "jpegquality", val);
332             return 1;
333         }
334     }
335     else if (!strcmp(name, "V"))
336     {   
337         printf("pdf2swf - part of %s %s\n", PACKAGE, VERSION);
338         exit(0);
339     }
340     else 
341     {
342         fprintf(stderr, "Unknown option: -%s\n", name);
343         exit(1);
344     }
345     return 0;
346 }
347
348 /*struct docoptions_t options[] =
349 {{"o","output","filename::Specify output file"},
350  {"V","version","Print program version"},
351  {"i","ignore","Ignore draw order (makes the SWF file smaller, but may produce graphic errors)"},
352  {"z","zlib","Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)"},
353  {"s","shapes","Don't use SWF Fonts, but store everything as shape"},
354  {"j","jpegquality","Set quality of embedded jpeg pictures (default: 85)"},
355  {"p","pages","Convert only pages in range. (E.g. 3-85)"},
356  {"w","samewindow","Don't open a new browser window for links in the SWF"},
357  {"f","fonts","Stroe full fonts in SWF. (Don't reduce to used characters)"},
358  {"F","fontpath","path::Add directory to font search path"},
359  {"B","viewer","name::Link viewer \"name\" to the pdf"},
360  {"L","preloader","file.swf::Link preloader \"file.swf\" to the pdf"},
361  {"b","defaultviewer","Link default viewer to the pdf"},
362  {"l","defaultpreloader","Link default preloader to the pdf"}
363  {0,0}
364 };*/
365 struct options_t options[] =
366 {{"o","output"},
367  {"q","quiet"},
368  {"V","version"},
369  {"i","ignore"},
370  {"I","info"},
371  {"z","zlib"},
372  {"s","set"},
373  {"S","shapes"},
374  {"j","jpegquality"},
375  {"p","pages"},
376  {"w","samewindow"},
377  {"f","fonts"},
378  {"F","fontdir"},
379  {"B","viewer"},
380  {"G","flatten"},
381  {"L","preloader"},
382  {"b","defaultviewer"},
383  {"l","defaultpreloader"},
384  {"t","stop"},
385  {"T","flashversion"},
386  {0,0}
387 };
388
389 int args_callback_longoption(char*name,char*val) {
390     return args_long2shortoption(options, name, val);
391 }
392
393 int args_callback_command(char*name, char*val) {
394     if (!filename) 
395         filename = name;
396     else {
397         if(outputname)
398         {
399              fprintf(stderr, "Error: Do you want the output to go to %s or to %s?", 
400                      outputname, name);
401              exit(1);
402         }
403         outputname = name;
404     }
405     return 0;
406 }
407
408 void args_callback_usage(char*name)
409 {
410     printf("Usage: %s [Options] input.pdf [-o output.swf]\n", name);
411     printf("\nBasic options:\n");
412     printf("-p  --pages=range          Convert only pages in range\n");
413     printf("-P  --password=password    Use password for deciphering the pdf\n");
414     printf("-v  --verbose              Be verbose. Use more than one -v for greater effect\n");
415     printf("-q  --quiet                Suppress normal messages. Use -qq to suppress warnings, also.\n");
416 #ifdef HAVE_DIRENT_H
417     printf("-F  --fontdir directory    Add directory to font search path\n");
418 #endif
419     printf("-V  --version              Print program version\n");
420     printf("\nEnhanced conversion options:\n");
421     printf("-S  --shapes               Don't use SWF Fonts, but store everything as shape\n");
422     printf("-z  --zlib                 Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)\n");
423     printf("-w  --samewindow           Don't open a new Browser Window for Links in the SWF\n");
424     printf("-f  --fonts                Store full fonts in SWF. (Don't reduce to used characters)\n");
425     printf("-T  --flashversion=num     Set the flash version in the header to num (default: 4)\n");
426     printf("-s insertstop              Insert a \"Stop\" Tag in every frame (don't turn pages automatically)\n");
427     printf("-s zoom=factor             Scale result, default: 72\n");
428     printf("-s jpegquality=quality     Set quality of embedded jpeg pictures (default:85)\n");
429     printf("-s caplinewidth=value      Set the minimum line width to trigger cap style handling to value. (3)\n");
430     printf("-s splinequality=value     Set the quality of spline convertion to value (0-100, default: 100).\n");
431     printf("-s fontquality=value       Set the quality of font convertion to value (0-100, default: 100).\n");
432     printf("-s ignoredraworder         Ignore draw order (makes the SWF file smaller and faster, but may produce\n"
433            "                           graphic errors)\n");
434     printf("-s filloverlap             Make intersecting shapes overlap, instead of canceling each\n"
435            "                           other out. (Needed for some Powerpoint PDFs)\n");
436     printf("-s transparent             Make the SWF transparent\n");
437     //deliberately undocumented (for now)
438     //printf("-2                         Put 2 pages into each frame.\n");
439     //printf("-4                         Put 4 pages into each frame.\n");
440     printf("Postprocessing options:\n");
441     printf("-b  --defaultviewer        Link default viewer to the pdf (%s)\n", concatPaths(SWFDIR, "default_viewer.swf"));
442     printf("-l  --defaultpreloader     Link default preloader the pdf (%s)\n", concatPaths(SWFDIR, "default_loader.swf"));
443     printf("-B  --viewer=filename      Link viewer \"name\" to the pdf (\"%s -B\" for list)\n", name);
444     printf("-L  --preloader=filename   Link preloader \"name\" to the pdf (\"%s -L\" for list)\n",name);
445 }
446
447 float getRate(char*filename)
448 {
449     int fi;
450     SWF swf;
451     fi = open(filename,O_RDONLY|O_BINARY);
452     if(fi<0) { 
453         char buffer[256];
454         sprintf(buffer, "Couldn't open %s", filename);
455         perror(buffer);
456         exit(1);
457     }
458     if(swf_ReadSWF(fi,&swf) < 0)
459     { 
460         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
461         close(fi);
462         exit(1);
463     }
464     swf_FreeTags(&swf);
465     return swf.frameRate / 256.0;
466 }
467
468 void show_info(gfxsource_t*driver, char*filename)
469 {
470     gfxdocument_t* pdf = driver->open(driver, filename);
471     int pagenr;
472     FILE*fo=0;
473     if(!pdf) {
474         msg("<error> Couldn't open %s", filename);
475         exit(1);
476     }
477     if(outputname) {
478         fo = fopen(outputname, "wb");
479         if(!fo) {
480             perror(outputname);exit(1);;
481         }
482     } else {
483         fo = stdout;
484     }
485
486     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
487     {
488         gfxpage_t*page = pdf->getpage(pdf,pagenr);
489         if(is_in_range(pagenr, pagerange)) {
490             fprintf(fo, "page=%d width=%.2f height=%.2f\n", pagenr, page->width, page->height);
491         }
492     }
493     pdf->destroy(pdf);
494 }
495
496 int main(int argn, char *argv[])
497 {
498     int ret;
499     char buf[256];
500     int numfonts = 0;
501     int t;
502     char t1searchpath[1024];
503     int nup_pos = 0;
504     int x,y;
505     char* installPath = getInstallationPath();
506     
507     initLog(0,-1,0,0,-1,loglevel);
508
509     /* not needed anymore since fonts are embedded
510        if(installPath) {
511         fontpaths[fontpathpos++] = concatPaths(installPath, "fonts");
512     }*/
513
514 #ifdef HAVE_SRAND48
515     srand48(time(0));
516 #else
517 #ifdef HAVE_SRAND
518     srand(time(0));
519 #endif
520 #endif
521     driver = gfxsource_pdf_create();
522
523     processargs(argn, argv);
524     
525     if(!filename)
526     {
527         fprintf(stderr, "Please specify an input file\n");
528         exit(1);
529     }
530
531     if(info_only) {
532         show_info(driver, filename);
533         return 0;
534     }
535
536     if(!outputname)
537     {
538         if(filename) {
539             outputname = stripFilename(filename, ".swf");
540             msg("<notice> Output filename not given. Writing to %s", outputname);
541         } 
542     }
543         
544     if(!outputname)
545     {
546         fprintf(stderr, "Please use -o to specify an output file\n");
547         exit(1);
548     }
549
550     // test if the page range is o.k.
551     is_in_range(0x7fffffff, pagerange);
552
553     if(pagerange)
554         driver->set_parameter(driver, "pages", pagerange);
555
556     if (!filename) {
557         args_callback_usage(argv[0]);
558         exit(0);
559     }
560
561     /* add fonts */
562     for(t=0;t<fontpathpos;t++) {
563         driver->set_parameter(driver, "fontdir", fontpaths[t]);
564     }
565
566     char fullname[256];
567     if(password && *password) {
568         sprintf(fullname, "%s|%s", filename, password);
569         filename = fullname;
570     }
571
572     gfxdocument_t* pdf = driver->open(driver, filename);
573     if(!pdf) {
574         msg("<error> Couldn't open %s", filename);
575         exit(1);
576     }
577
578     gfxdevice_t swf,wrap;
579     gfxdevice_swf_init(&swf);
580     gfxdevice_t*out;
581     
582     if(flatten) {
583         gfxdevice_removeclippings_init(&wrap, &swf);
584         out = &wrap;
585     } else {
586         out = &swf;
587     }
588
589     struct mypage_t {
590         int x;
591         int y;
592         gfxpage_t*page;
593     } pages[4];
594
595     int pagenum = 0;
596     int frame = 1;
597     int pagenr;
598     
599     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
600     {
601         if(is_in_range(pagenr, pagerange)) {
602             char mapping[80];
603             sprintf(mapping, "%d:%d", pagenr, frame);
604             pdf->set_parameter(pdf, "pagemap", mapping);
605             pagenum++;
606         }
607         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
608             pagenum = 0;
609             frame++;
610         }
611     }
612
613     pagenum = 0;
614
615     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
616     {
617         if(is_in_range(pagenr, pagerange)) {
618             gfxpage_t* page = pages[pagenum].page = pdf->getpage(pdf, pagenr);
619             pages[pagenum].x = 0;
620             pages[pagenum].y = 0;
621             pages[pagenum].page = page;
622             pagenum++;
623         }
624         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
625
626             int t;
627             int xmax[xnup], ymax[xnup];
628             int x,y;
629             int width=0, height=0;
630
631             memset(xmax, 0, xnup*sizeof(int));
632             memset(ymax, 0, ynup*sizeof(int));
633
634             for(y=0;y<ynup;y++)
635             for(x=0;x<xnup;x++) {
636                 int t = y*xnup + x;
637
638                 if(pages[t].page->width > xmax[x])
639                     xmax[x] = (int)pages[t].page->width;
640                 if(pages[t].page->height > ymax[y])
641                     ymax[y] = (int)pages[t].page->height;
642             }
643             for(x=0;x<xnup;x++) {
644                 width += xmax[x];
645                 xmax[x] = width;
646             }
647             for(y=0;y<ynup;y++) {
648                 height += ymax[y];
649                 ymax[y] = height;
650             }
651             if(custom_clip) {
652                 out->startpage(out,clip_x2 - clip_x1, clip_y2 - clip_y1);
653             } else {
654                 out->startpage(out,width,height);
655             }
656             for(t=0;t<pagenum;t++) {
657                 int x = t%xnup;
658                 int y = t/xnup;
659                 int xpos = x>0?xmax[x-1]:0;
660                 int ypos = y>0?ymax[y-1]:0;
661                 msg("<verbose> Render (%d,%d) move:%d/%d\n",
662                         (int)(pages[t].page->width + xpos),
663                         (int)(pages[t].page->height + ypos), xpos, ypos);
664                 pages[t].page->rendersection(pages[t].page, out, custom_move? move_x : xpos, 
665                                                            custom_move? move_y : ypos,
666                                                            custom_clip? clip_x1 : 0 + xpos, 
667                                                            custom_clip? clip_y1 : 0 + ypos, 
668                                                            custom_clip? clip_x2 : pages[t].page->width + xpos, 
669                                                            custom_clip? clip_y2 : pages[t].page->height + ypos);
670             }
671             out->endpage(out);
672             for(t=0;t<pagenum;t++)  {
673                 pages[t].page->destroy(pages[t].page);
674             }
675             pagenum = 0;
676         }
677     }
678     
679     gfxresult_t*result = out->finish(out);
680
681     if(result->save(result, outputname) < 0) {
682         exit(1);
683     }
684
685     int width = (int)result->get(result, "width");
686     int height = (int)result->get(result, "height");
687     msg("<notice> SWF written");
688     
689     result->destroy(result);
690
691     pdf->destroy(pdf);
692     driver->destroy(driver);
693
694     const char*zip = "";
695     if(zlib) {
696         zip = "-z";
697     }
698     if(!preloader && viewer) {
699         systemf("swfcombine %s -X %d -Y %d \"%s\" viewport=\"%s\" -o \"%s\"",zip,width,height,
700                 viewer, outputname, outputname);
701         if(!system_quiet)
702             printf("\n");
703     }
704     if(preloader && !viewer) {
705         msg("<warning> --preloader option without --viewer option doesn't make very much sense.");
706         ret = systemf("swfcombine %s -Y %d -X %d %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",zip,width,height,
707                 SWFDIR, preloader, outputname, outputname);
708         if(!system_quiet)
709             printf("\n");
710     }
711     if(preloader && viewer) {
712 #ifdef HAVE_MKSTEMP
713         char tmpname[] = "__swf__XXXXXX";
714         mkstemp(tmpname);
715 #else 
716         char*tmpname = "__tmp__.swf";
717 #endif
718         systemf("swfcombine \"%s\" viewport=%s -o %s",
719                 viewer, outputname, tmpname);
720         systemf("swfcombine %s -X %d -Y %d -r %f %s/PreLoaderTemplate.swf loader=%s movie=%s -o \"%s\"",zip,width,height,
721                 getRate(preloader), SWFDIR, preloader, tmpname, outputname);
722         systemf("rm %s", tmpname);
723     }
724
725
726     return 0;
727 }
728