don't use --flatten for -O2,3. Turn 'optimize_polygons' on for -G
[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/polyops.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 #ifndef WIN32
207     else if (!strcmp(name, "Q"))
208     {
209         int seconds = atoi(val);
210         alarm(seconds);
211         return 1;
212     }
213 #endif
214     else if (!strcmp(name, "z"))
215     {
216         driver->set_parameter(driver, "enablezlib", "1");
217         zlib = 1;
218         return 0;
219     }
220     else if (!strcmp(name, "n"))
221     {
222         driver->set_parameter(driver, "opennewwindow", "1");
223         return 0;
224     }
225     else if (!strcmp(name, "I"))
226     {
227         info_only = 1;
228         return 0;
229     }
230     else if (!strcmp(name, "t"))
231     {
232         driver->set_parameter(driver, "insertstop", "1");
233         return 0;
234     }
235     else if (!strcmp(name, "T"))
236     {
237         if(!strcasecmp(val, "mx"))
238             driver->set_parameter(driver, "flashversion", "6");
239         else
240             driver->set_parameter(driver, "flashversion", val);
241
242         return 1;
243     }
244     else if (!strcmp(name, "f"))
245     {
246         driver->set_parameter(driver, "storeallcharacters", "1");
247         driver->set_parameter(driver, "extrafontdata", "1");
248         return 0;
249     }
250     else if (!strcmp(name, "w"))
251     {
252         driver->set_parameter(driver, "linksopennewwindow", "0");
253         return 0;
254     }
255     else if (!strcmp(name, "O"))
256     {
257         int level = 1;
258         int ret=0;
259         if(val&& val[0] && val[1]==0 && isdigit(val[0])) {
260             level = atoi(val);
261             ret=1;
262         }
263         if(level>=1)
264             driver->set_parameter(driver, "poly2bitmap", "1");
265         if(level>=2)
266             driver->set_parameter(driver, "bitmapfonts", "1");
267         if(level>=3)
268             driver->set_parameter(driver, "ignoredraworder", "1");
269         return ret;
270     }
271     else if (!strcmp(name, "G"))
272     {
273         driver->set_parameter(driver, "optimize_polygons", "1");
274         flatten = 1;
275         return 0;
276     }
277     else if (!strcmp(name, "F"))
278     {
279         char *s = strdup(val);
280         int l = strlen(s);
281         while(l && s[l-1]=='/') {
282             s[l-1] = 0;
283             l--;
284         }
285         fontpaths[fontpathpos++] = s;
286         return 1;
287     }
288     else if (!strcmp(name, "l"))
289     {
290         char buf[256];
291         sprintf(buf, "%s/default_loader.swf", SWFDIR);
292         preloader = strdup(buf);
293         return 0;
294     }
295     else if (!strcmp(name, "b"))
296     {
297         char buf[256];
298         sprintf(buf, "%s/default_viewer.swf", SWFDIR);
299         viewer = strdup(buf);
300         return 0;
301     }
302     else if (!strcmp(name, "L"))
303     {
304         if(val)
305         {
306             preloader = val;
307         }
308         else
309         {
310             systemf("ls %s/*_loader.swf", SWFDIR);
311             if(!system_quiet)
312                 printf("\n");
313             exit(1);
314         }
315         return 1;
316     }
317     else if (!strcmp(name, "B"))
318     {
319         if(val)
320         {
321             viewer = val;
322         }
323         else
324         {
325             systemf("ls %s/*_viewer.swf", SWFDIR);
326             if(!system_quiet)
327                 printf("\n");
328             exit(1);
329         }
330         return 1;
331     }
332     else if (!strcmp(name, "j"))
333     {
334         if(name[1]) {
335             driver->set_parameter(driver, "jpegquality", &name[1]);
336             return 0;
337         } else {
338             driver->set_parameter(driver, "jpegquality", val);
339             return 1;
340         }
341     }
342     else if (!strcmp(name, "V"))
343     {   
344         printf("pdf2swf - part of %s %s\n", PACKAGE, VERSION);
345         exit(0);
346     }
347     else 
348     {
349         fprintf(stderr, "Unknown option: -%s\n", name);
350         exit(1);
351     }
352     return 0;
353 }
354
355 /*struct docoptions_t options[] =
356 {{"o","output","filename::Specify output file"},
357  {"V","version","Print program version"},
358  {"i","ignore","Ignore draw order (makes the SWF file smaller, but may produce graphic errors)"},
359  {"z","zlib","Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)"},
360  {"s","shapes","Don't use SWF Fonts, but store everything as shape"},
361  {"j","jpegquality","Set quality of embedded jpeg pictures (default: 85)"},
362  {"p","pages","Convert only pages in range. (E.g. 3-85)"},
363  {"w","samewindow","Don't open a new browser window for links in the SWF"},
364  {"f","fonts","Stroe full fonts in SWF. (Don't reduce to used characters)"},
365  {"F","fontpath","path::Add directory to font search path"},
366  {"B","viewer","name::Link viewer \"name\" to the pdf"},
367  {"L","preloader","file.swf::Link preloader \"file.swf\" to the pdf"},
368  {"b","defaultviewer","Link default viewer to the pdf"},
369  {"l","defaultpreloader","Link default preloader to the pdf"}
370  {0,0}
371 };*/
372 struct options_t options[] =
373 {{"o","output"},
374  {"q","quiet"},
375  {"V","version"},
376  {"i","ignore"},
377  {"I","info"},
378  {"z","zlib"},
379  {"s","set"},
380  {"S","shapes"},
381  {"Q","maxtime"},
382  {"j","jpegquality"},
383  {"p","pages"},
384  {"w","samewindow"},
385  {"f","fonts"},
386  {"F","fontdir"},
387  {"B","viewer"},
388  {"G","flatten"},
389  {"L","preloader"},
390  {"b","defaultviewer"},
391  {"l","defaultpreloader"},
392  {"t","stop"},
393  {"T","flashversion"},
394  {0,0}
395 };
396
397 int args_callback_longoption(char*name,char*val) {
398     return args_long2shortoption(options, name, val);
399 }
400
401 int args_callback_command(char*name, char*val) {
402     if (!filename) 
403         filename = name;
404     else {
405         if(outputname)
406         {
407              fprintf(stderr, "Error: Do you want the output to go to %s or to %s?", 
408                      outputname, name);
409              exit(1);
410         }
411         outputname = name;
412     }
413     return 0;
414 }
415
416 void args_callback_usage(char*name)
417 {
418     printf("Usage: %s [Options] input.pdf [-o output.swf]\n", name);
419     printf("\nBasic options:\n");
420     printf("-p  --pages=range          Convert only pages in range\n");
421     printf("-P  --password=password    Use password for deciphering the pdf\n");
422     printf("-v  --verbose              Be verbose. Use more than one -v for greater effect\n");
423     printf("-q  --quiet                Suppress normal messages. Use -qq to suppress warnings, also.\n");
424 #ifdef HAVE_DIRENT_H
425     printf("-F  --fontdir directory    Add directory to font search path\n");
426 #endif
427     printf("-V  --version              Print program version\n");
428     printf("\nEnhanced conversion options:\n");
429     printf("-S  --shapes               Don't use SWF Fonts, but store everything as shape\n");
430     printf("-z  --zlib                 Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)\n");
431     printf("-w  --samewindow           Don't open a new Browser Window for Links in the SWF\n");
432     printf("-f  --fonts                Store full fonts in SWF. (Don't reduce to used characters)\n");
433     printf("-T  --flashversion=num     Set the flash version in the header to num (default: 4)\n");
434     printf("-s insertstop              Insert a \"Stop\" Tag in every frame (don't turn pages automatically)\n");
435     printf("-s zoom=factor             Scale result, default: 72\n");
436     printf("-s jpegquality=quality     Set quality of embedded jpeg pictures (default:85)\n");
437     printf("-s caplinewidth=value      Set the minimum line width to trigger cap style handling to value. (3)\n");
438     printf("-s splinequality=value     Set the quality of spline convertion to value (0-100, default: 100).\n");
439     printf("-s fontquality=value       Set the quality of font convertion to value (0-100, default: 100).\n");
440     printf("-s ignoredraworder         Ignore draw order (makes the SWF file smaller and faster, but may produce\n"
441            "                           graphic errors)\n");
442     printf("-s filloverlap             Make intersecting shapes overlap, instead of canceling each\n"
443            "                           other out. (Needed for some Powerpoint PDFs)\n");
444     printf("-s transparent             Make the SWF transparent\n");
445     //deliberately undocumented (for now)
446     //printf("-2                         Put 2 pages into each frame.\n");
447     //printf("-4                         Put 4 pages into each frame.\n");
448     printf("Postprocessing options:\n");
449     printf("-b  --defaultviewer        Link default viewer to the pdf (%s)\n", concatPaths(SWFDIR, "default_viewer.swf"));
450     printf("-l  --defaultpreloader     Link default preloader the pdf (%s)\n", concatPaths(SWFDIR, "default_loader.swf"));
451     printf("-B  --viewer=filename      Link viewer \"name\" to the pdf (\"%s -B\" for list)\n", name);
452     printf("-L  --preloader=filename   Link preloader \"name\" to the pdf (\"%s -L\" for list)\n",name);
453 }
454
455 float getRate(char*filename)
456 {
457     int fi;
458     SWF swf;
459     fi = open(filename,O_RDONLY|O_BINARY);
460     if(fi<0) { 
461         char buffer[256];
462         sprintf(buffer, "Couldn't open %s", filename);
463         perror(buffer);
464         exit(1);
465     }
466     if(swf_ReadSWF(fi,&swf) < 0)
467     { 
468         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
469         close(fi);
470         exit(1);
471     }
472     swf_FreeTags(&swf);
473     return swf.frameRate / 256.0;
474 }
475
476 void show_info(gfxsource_t*driver, char*filename)
477 {
478     gfxdocument_t* pdf = driver->open(driver, filename);
479     int pagenr;
480     FILE*fo=0;
481     if(!pdf) {
482         msg("<error> Couldn't open %s", filename);
483         exit(1);
484     }
485     if(outputname) {
486         fo = fopen(outputname, "wb");
487         if(!fo) {
488             perror(outputname);exit(1);;
489         }
490     } else {
491         fo = stdout;
492     }
493
494     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
495     {
496         gfxpage_t*page = pdf->getpage(pdf,pagenr);
497         if(is_in_range(pagenr, pagerange)) {
498             fprintf(fo, "page=%d width=%.2f height=%.2f\n", pagenr, page->width, page->height);
499         }
500     }
501     pdf->destroy(pdf);
502 }
503
504 int main(int argn, char *argv[])
505 {
506     int ret;
507     char buf[256];
508     int numfonts = 0;
509     int t;
510     char t1searchpath[1024];
511     int nup_pos = 0;
512     int x,y;
513     char* installPath = getInstallationPath();
514     
515     initLog(0,-1,0,0,-1,loglevel);
516
517     /* not needed anymore since fonts are embedded
518        if(installPath) {
519         fontpaths[fontpathpos++] = concatPaths(installPath, "fonts");
520     }*/
521
522 #ifdef HAVE_SRAND48
523     srand48(time(0));
524 #else
525 #ifdef HAVE_SRAND
526     srand(time(0));
527 #endif
528 #endif
529     driver = gfxsource_pdf_create();
530
531     processargs(argn, argv);
532     
533     if(!filename)
534     {
535         fprintf(stderr, "Please specify an input file\n");
536         exit(1);
537     }
538
539     if(info_only) {
540         show_info(driver, filename);
541         return 0;
542     }
543
544     if(!outputname)
545     {
546         if(filename) {
547             outputname = stripFilename(filename, ".swf");
548             msg("<notice> Output filename not given. Writing to %s", outputname);
549         } 
550     }
551         
552     if(!outputname)
553     {
554         fprintf(stderr, "Please use -o to specify an output file\n");
555         exit(1);
556     }
557
558     // test if the page range is o.k.
559     is_in_range(0x7fffffff, pagerange);
560
561     if(pagerange)
562         driver->set_parameter(driver, "pages", pagerange);
563
564     if (!filename) {
565         args_callback_usage(argv[0]);
566         exit(0);
567     }
568
569     /* add fonts */
570     for(t=0;t<fontpathpos;t++) {
571         driver->set_parameter(driver, "fontdir", fontpaths[t]);
572     }
573
574     char fullname[256];
575     if(password && *password) {
576         sprintf(fullname, "%s|%s", filename, password);
577         filename = fullname;
578     }
579
580     gfxdocument_t* pdf = driver->open(driver, filename);
581     if(!pdf) {
582         msg("<error> Couldn't open %s", filename);
583         exit(1);
584     }
585
586     gfxdevice_t swf,wrap;
587     gfxdevice_swf_init(&swf);
588     gfxdevice_t*out;
589     
590     if(flatten) {
591         gfxdevice_removeclippings_init(&wrap, &swf);
592         out = &wrap;
593     } else {
594         out = &swf;
595     }
596
597     struct mypage_t {
598         int x;
599         int y;
600         gfxpage_t*page;
601     } pages[4];
602
603     int pagenum = 0;
604     int frame = 1;
605     int pagenr;
606     
607     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
608     {
609         if(is_in_range(pagenr, pagerange)) {
610             char mapping[80];
611             sprintf(mapping, "%d:%d", pagenr, frame);
612             pdf->set_parameter(pdf, "pagemap", mapping);
613             pagenum++;
614         }
615         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
616             pagenum = 0;
617             frame++;
618         }
619     }
620
621     pagenum = 0;
622
623     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
624     {
625         if(is_in_range(pagenr, pagerange)) {
626             gfxpage_t* page = pages[pagenum].page = pdf->getpage(pdf, pagenr);
627             pages[pagenum].x = 0;
628             pages[pagenum].y = 0;
629             pages[pagenum].page = page;
630             pagenum++;
631         }
632         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
633
634             int t;
635             int xmax[xnup], ymax[xnup];
636             int x,y;
637             int width=0, height=0;
638
639             memset(xmax, 0, xnup*sizeof(int));
640             memset(ymax, 0, ynup*sizeof(int));
641
642             for(y=0;y<ynup;y++)
643             for(x=0;x<xnup;x++) {
644                 int t = y*xnup + x;
645
646                 if(pages[t].page->width > xmax[x])
647                     xmax[x] = (int)pages[t].page->width;
648                 if(pages[t].page->height > ymax[y])
649                     ymax[y] = (int)pages[t].page->height;
650             }
651             for(x=0;x<xnup;x++) {
652                 width += xmax[x];
653                 xmax[x] = width;
654             }
655             for(y=0;y<ynup;y++) {
656                 height += ymax[y];
657                 ymax[y] = height;
658             }
659             if(custom_clip) {
660                 out->startpage(out,clip_x2 - clip_x1, clip_y2 - clip_y1);
661             } else {
662                 out->startpage(out,width,height);
663             }
664             for(t=0;t<pagenum;t++) {
665                 int x = t%xnup;
666                 int y = t/xnup;
667                 int xpos = x>0?xmax[x-1]:0;
668                 int ypos = y>0?ymax[y-1]:0;
669                 msg("<verbose> Render (%d,%d) move:%d/%d\n",
670                         (int)(pages[t].page->width + xpos),
671                         (int)(pages[t].page->height + ypos), xpos, ypos);
672                 pages[t].page->rendersection(pages[t].page, out, custom_move? move_x : xpos, 
673                                                            custom_move? move_y : ypos,
674                                                            custom_clip? clip_x1 : 0 + xpos, 
675                                                            custom_clip? clip_y1 : 0 + ypos, 
676                                                            custom_clip? clip_x2 : pages[t].page->width + xpos, 
677                                                            custom_clip? clip_y2 : pages[t].page->height + ypos);
678             }
679             out->endpage(out);
680             for(t=0;t<pagenum;t++)  {
681                 pages[t].page->destroy(pages[t].page);
682             }
683             pagenum = 0;
684         }
685     }
686     
687     gfxresult_t*result = out->finish(out);
688
689     if(result->save(result, outputname) < 0) {
690         exit(1);
691     }
692
693     int width = (int)result->get(result, "width");
694     int height = (int)result->get(result, "height");
695     msg("<notice> SWF written");
696     
697     result->destroy(result);
698
699     pdf->destroy(pdf);
700     driver->destroy(driver);
701
702     const char*zip = "";
703     if(zlib) {
704         zip = "-z";
705     }
706     if(!preloader && viewer) {
707         systemf("swfcombine %s -X %d -Y %d \"%s\" viewport=\"%s\" -o \"%s\"",zip,width,height,
708                 viewer, outputname, outputname);
709         if(!system_quiet)
710             printf("\n");
711     }
712     if(preloader && !viewer) {
713         msg("<warning> --preloader option without --viewer option doesn't make very much sense.");
714         ret = systemf("swfcombine %s -Y %d -X %d %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",zip,width,height,
715                 SWFDIR, preloader, outputname, outputname);
716         if(!system_quiet)
717             printf("\n");
718     }
719     if(preloader && viewer) {
720 #ifdef HAVE_MKSTEMP
721         char tmpname[] = "__swf__XXXXXX";
722         mkstemp(tmpname);
723 #else 
724         char*tmpname = "__tmp__.swf";
725 #endif
726         systemf("swfcombine \"%s\" viewport=%s -o %s",
727                 viewer, outputname, tmpname);
728         systemf("swfcombine %s -X %d -Y %d -r %f %s/PreLoaderTemplate.swf loader=%s movie=%s -o \"%s\"",zip,width,height,
729                 getRate(preloader), SWFDIR, preloader, tmpname, outputname);
730         systemf("rm %s", tmpname);
731     }
732
733
734     return 0;
735 }
736