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