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