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