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