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