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