c++/c fixes
[swftools.git] / pdf2swf / pdf2swf.cc
1 /* pdf2swf.cc
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 "SWFOutputDev.h"
36 #include "log.h"
37
38 #ifndef WIN32
39 #define FONTDIR SWFTOOLS_DATADIR "/fonts"
40 #define SWFDIR SWFTOOLS_DATADIR "/swfs"
41 #else
42 #define FONTDIR "C:\\swftools\\fonts"
43 #define SWFDIR "C:\\swftools\\swfs"
44 #endif
45
46 static char * outputname = 0;
47 static int loglevel = 3;
48 static char * pagerange = 0;
49 static char * filename = 0;
50 static char * password = 0;
51
52 static char * preloader = 0;
53 static char * viewer = 0;
54
55 char* fontpaths[256];
56 int fontpathpos = 0;
57
58 static int system_quiet=0;
59
60 int systemf(const char* format, ...)
61 {
62     char buf[1024];
63     int ret;
64     va_list arglist;
65     va_start(arglist, format);
66     vsprintf(buf, format, arglist);
67     va_end(arglist);
68
69     if(!system_quiet) {
70         printf("%s\n", buf);
71         fflush(stdout);
72     }
73     ret = system(buf);
74     if(ret) {
75         fprintf(stderr, "system() returned %d\n", ret);
76         exit(ret);
77     }
78     return ret;
79 }
80
81 int args_callback_option(char*name,char*val) {
82     if (!strcmp(name, "o"))
83     {
84         outputname = val;
85         return 1;
86     }
87     else if (!strcmp(name, "v"))
88     {
89         loglevel ++;
90         return 0;
91     }
92     else if (!strcmp(name, "q"))
93     {
94         loglevel --;
95         system_quiet = 1;
96         return 0;
97     }
98     else if (name[0]=='p')
99     {
100         /* check whether the page range follows the p directly, like 
101            in -p1,2 */
102         do {
103             name++;
104         } while(*name == 32 || *name == 13 || *name == 10 || *name == '\t');
105
106         if(*name) {
107             pagerange = name;
108             return 0;
109         } 
110         pagerange = val;        
111         return 1;
112     }
113     else if (!strcmp(name, "P"))
114     {
115         password = val;
116         return 1;
117     }
118     else if (!strcmp(name, "s"))
119     {
120         char*s = strdup(val);
121         char*c = strchr(s, '=');
122         if(c && *c && c[1])  {
123             *c = 0;
124             c++;
125             pdfswf_setparameter(s,c);
126         }
127         else
128             pdfswf_setparameter(s,"1");
129         return 1;
130     }
131     else if (!strcmp(name, "S"))
132     {
133         pdfswf_setparameter("drawonlyshapes", "1");
134         return 0;
135     }
136     else if (!strcmp(name, "i"))
137     {
138         pdfswf_setparameter("ignoredraworder", "1");
139         return 0;
140     }
141     else if (!strcmp(name, "z"))
142     {
143         pdfswf_setparameter("enablezlib", "1");
144         return 0;
145     }
146     else if (!strcmp(name, "n"))
147     {
148         pdfswf_setparameter("opennewwindow", "1");
149         return 0;
150     }
151     else if (!strcmp(name, "t"))
152     {
153         pdfswf_setparameter("insertstop", "1");
154         return 0;
155     }
156     else if (!strcmp(name, "T"))
157     {
158         if(!strcasecmp(val, "mx"))
159             pdfswf_setparameter("flashversion", "6");
160         else
161             pdfswf_setparameter("flashversion", val);
162
163         return 1;
164     }
165     else if (!strcmp(name, "f"))
166     {
167         pdfswf_setparameter("storeallcharacters", "1");
168         return 0;
169     }
170     else if (!strcmp(name, "F"))
171     {
172         char *s = strdup(val);
173         int l = strlen(s);
174         while(l && s[l-1]=='/') {
175             s[l-1] = 0;
176             l--;
177         }
178         fontpaths[fontpathpos++] = s;
179         return 1;
180     }
181     else if (!strcmp(name, "l"))
182     {
183         char buf[256];
184         sprintf(buf, "%s/default_loader.swf", SWFDIR);
185         preloader = strdup(buf);
186         return 0;
187     }
188     else if (!strcmp(name, "b"))
189     {
190         char buf[256];
191         sprintf(buf, "%s/default_viewer.swf", SWFDIR);
192         viewer = strdup(buf);
193         return 0;
194     }
195     else if (!strcmp(name, "L"))
196     {
197         if(val)
198         {
199             preloader = val;
200         }
201         else
202         {
203             systemf("ls %s/*_loader.swf", SWFDIR);
204             if(!system_quiet)
205                 printf("\n");
206             exit(1);
207         }
208         return 1;
209     }
210     else if (!strcmp(name, "B"))
211     {
212         if(val)
213         {
214             viewer = val;
215         }
216         else
217         {
218             systemf("ls %s/*_viewer.swf", SWFDIR);
219             if(!system_quiet)
220                 printf("\n");
221             exit(1);
222         }
223         return 1;
224     }
225     else if (!strcmp(name, "j"))
226     {
227         if(name[1]) {
228             pdfswf_setparameter("jpegquality", &name[1]);
229             return 0;
230         } else {
231             pdfswf_setparameter("jpegquality", val);
232             return 1;
233         }
234     }
235     else if (!strcmp(name, "V"))
236     {   
237         printf("pdf2swf - part of %s %s\n", PACKAGE, VERSION);
238         exit(0);
239     }
240     else 
241     {
242         fprintf(stderr, "Unknown option: -%s\n", name);
243         exit(1);
244     }
245     return 0;
246 }
247
248 /*struct docoptions_t options[] =
249 {{"o","output","filename::Specify output file"},
250  {"V","version","Print program version"},
251  {"i","ignore","Ignore draw order (makes the SWF file smaller, but may produce graphic errors)"},
252  {"z","zlib","Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)"},
253  {"s","shapes","Don't use SWF Fonts, but store everything as shape"},
254  {"j","jpegquality","Set quality of embedded jpeg pictures (default: 85)"},
255  {"p","pages","Convert only pages in range. (E.g. 3-85)"},
256  {"w","samewindow","Don't open a new browser window for links in the SWF"},
257  {"f","fonts","Stroe full fonts in SWF. (Don't reduce to used characters)"},
258  {"F","fontpath","path::Add directory to font search path"},
259  {"B","viewer","name::Link viewer \"name\" to the pdf"},
260  {"L","preloader","file.swf::Link preloader \"file.swf\" to the pdf"},
261  {"b","defaultviewer","Link default viewer to the pdf"},
262  {"l","defaultpreloader","Link default preloader to the pdf"}
263  {0,0}
264 };*/
265 struct options_t options[] =
266 {{"o","output"},
267  {"q","quiet"},
268  {"V","version"},
269  {"i","ignore"},
270  {"z","zlib"},
271  {"s","set"},
272  {"S","shapes"},
273  {"j","jpegquality"},
274  {"p","pages"},
275  {"w","samewindow"},
276  {"f","fonts"},
277  {"F","fontdir"},
278  {"B","viewer"},
279  {"L","preloader"},
280  {"b","defaultviewer"},
281  {"l","defaultpreloader"},
282  {"t","stop"},
283  {"T","flashversion"},
284  {0,0}
285 };
286
287 int args_callback_longoption(char*name,char*val) {
288     return args_long2shortoption(options, name, val);
289 }
290
291 int args_callback_command(char*name, char*val) {
292     if (!filename) 
293         filename = name;
294     else {
295         if(outputname)
296         {
297              fprintf(stderr, "Error: Do you want the output to go to %s or to %s?", 
298                      outputname, name);
299              exit(1);
300         }
301         outputname = name;
302     }
303     return 0;
304 }
305
306 void args_callback_usage(char*name)
307 {
308     printf("Usage: %s [Options] input.pdf [-o output.swf]\n", name);
309     printf("\nBasic options:\n");
310     printf("-p  --pages=range          Convert only pages in range\n");
311     printf("-P  --password=password    Use password for deciphering the pdf\n");
312     printf("-v  --verbose              Be verbose. Use more than one -v for greater effect\n");
313     printf("-q  --quiet                Suppress normal messages. Use -qq to suppress warnings, also.\n");
314 #ifdef HAVE_DIRENT_H
315     printf("-F  --fontdir directory    Add directory to font search path\n");
316 #endif
317     printf("-V  --version              Print program version\n");
318     printf("\nEnhanced conversion options:\n");
319     printf("-S  --shapes               Don't use SWF Fonts, but store everything as shape\n");
320     printf("-z  --zlib                 Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)\n");
321     printf("-w  --samewindow           Don't open a new Browser Window for Links in the SWF\n");
322     printf("-f  --fonts                Store full fonts in SWF. (Don't reduce to used characters)\n");
323     printf("-T  --flashversion=num     Set the flash version in the header to num (default: 4)\n");
324     printf("-s insertstop              Insert a \"Stop\" Tag in every frame (don't turn pages automatically)\n");
325     printf("-s zoom=factor             Scale result, default: 72\n");
326     printf("-s jpegquality=quality     Set quality of embedded jpeg pictures (default:85)\n");
327     printf("-s caplinewidth=value      Set the minimum line width to trigger cap style handling to value. (3)\n");
328     printf("-s splinequality=value     Set the quality of spline convertion to value (0-100, default: 100).\n");
329     printf("-s fontquality=value       Set the quality of font convertion to value (0-100, default: 100).\n");
330     printf("-s ignoredraworder         Ignore draw order (makes the SWF file smaller and faster, but may produce\n"
331            "                           graphic errors)\n");
332     printf("-s filloverlap             Make intersecting shapes overlap, instead of canceling each\n"
333            "                           other out. (Needed for some Powerpoint PDFs)\n");
334     printf("Postprocessing options:\n");
335 #ifndef SYSTEM_BACKTICKS
336     printf("(They might not work because your system call doesn't support command substitution)\n");
337 #endif
338     printf("-b  --defaultviewer        Link default viewer to the pdf (%s/swfs/default_viewer.swf)\n", SWFTOOLS_DATADIR);
339     printf("-l  --defaultpreloader     Link default preloader the pdf (%s/swfs/default_loader.swf)\n", SWFTOOLS_DATADIR);
340     printf("-B  --viewer=filename      Link viewer \"name\" to the pdf (\"%s -B\" for list)\n", name);
341     printf("-L  --preloader=filename   Link preloader \"name\" to the pdf (\"%s -L\" for list)\n",name);
342 }
343
344 #ifdef HAVE_DIRENT_H
345 static void addfontdir(char* dirname, int*numfonts)
346 {
347     if(!numfonts)
348         msg("<verbose> Adding %s to search path\n", dirname);
349
350     DIR*dir = opendir(dirname);
351     if(!dir) {
352         msg("<warning> Couldn't open directory %s\n", dirname);
353         return;
354     }
355     struct dirent*ent;
356     while(1) {
357         ent = readdir (dir);
358         if (!ent) 
359             break;
360         int l;
361         char*name = ent->d_name;
362         char type = 0;
363         if(!name) continue;
364         l=strlen(name);
365         if(l<4)
366             continue;
367         if(!strncasecmp(&name[l-4], ".pfa", 4)) 
368             type=1;
369         if(!strncasecmp(&name[l-4], ".pfb", 4)) 
370             type=3;
371         if(!strncasecmp(&name[l-4], ".ttf", 4)) 
372             type=2;
373         if(type)
374         {
375             char*fontname = (char*)malloc(strlen(dirname)+strlen(name)+2);
376             strcpy(fontname, dirname);
377 #ifdef WIN32
378                 strcat(fontname, "\\");
379 #else
380                 strcat(fontname, "/");
381 #endif
382             strcat(fontname, name);
383             if(!numfonts)
384                 msg("<debug> Adding %s to fonts", fontname);
385             pdfswf_addfont(fontname);
386             if(numfonts)
387                 (*numfonts)++;
388         }
389     }
390     closedir(dir);
391 }
392 #endif
393
394 static char* stripfilename(char*filename, char*newext)
395 {
396     char*last1 = strrchr(filename, '/');
397     char*last2 = strrchr(filename, '\\');
398     char*pos = filename;
399     char*name;
400     char*dot;
401     if(last1>pos) pos = last1 + 1;
402     if(last2>pos) pos = last2 + 1;
403     name = (char*)malloc(strlen(pos)+5);
404     strcpy(name, pos);
405     dot = strrchr(name, '.');
406     if(dot) {
407         *dot = 0;
408     }
409     strcat(name, newext);
410     return name;
411 }
412
413 int main(int argn, char *argv[])
414 {
415     int ret;
416     char buf[256];
417     int numfonts = 0;
418     int t;
419     char t1searchpath[1024];
420
421 #if defined(WIN32) && defined(HAVE_STAT) && defined(HAVE_SYS_STAT_H)
422     FILE*test = fopen(FONTDIR "\\d050000l.afm", "rb");
423     if(!test) {
424         fprintf(stderr, "Couldn't find file " FONTDIR "\\d050000l.afm- pdf2swf not installed properly? OS says:\n");
425         perror("open");
426         exit(1);
427     }
428     fclose(test);
429 #endif
430
431 #ifdef HAVE_SRAND48
432     srand48(time(0));
433 #else
434 #ifdef HAVE_SRAND
435     srand(time(0));
436 #endif
437 #endif
438     processargs(argn, argv);
439     initLog(0,-1,0,0,-1,loglevel);
440
441     if(!filename)
442     {
443         fprintf(stderr, "Please specify an input file\n");
444         exit(1);
445     }
446
447     if(!outputname)
448     {
449         if(filename) {
450             outputname = stripfilename(filename, ".swf");
451             msg("<notice> Output filename not given. Writing to %s", outputname);
452         } 
453     }
454         
455     if(!outputname)
456     {
457         fprintf(stderr, "Please use -o to specify an output file\n");
458         exit(1);
459     }
460
461     // test if the page range is o.k.
462     is_in_range(0x7fffffff, pagerange);
463
464     if (!filename) {
465         args_callback_usage(argv[0]);
466         exit(0);
467     }
468
469 #ifdef HAVE_DIRENT_H
470     // pass 1
471     addfontdir(FONTDIR, &numfonts);
472     for(t=0;t<fontpathpos;t++) {
473         addfontdir(fontpaths[t], &numfonts);
474     }
475     // pass 2
476     addfontdir(FONTDIR, 0);
477     for(t=0;t<fontpathpos;t++) {
478         addfontdir(fontpaths[t], 0);
479     }
480 #else
481     msg("<error> Couldn't find any fonts!");
482 #endif
483
484     pdf_doc_t* pdf = pdf_init(filename, password);
485     if(!pdf) {
486         msg("<error> Couldn't open %s", filename);
487         exit(1);
488     }
489     swf_output_t* swf = swf_output_init();
490
491     for(t = 1; t <= pdf->num_pages; t++) 
492     {
493         if(is_in_range(t, pagerange)) {
494             /* for links: FIXME */
495             pdfswf_preparepage(t);
496         }
497         if(is_in_range(t, pagerange)) {
498             pdf_page_t*page = pdf_getpage(pdf, t);
499             pdf_page_render(page, swf);
500             pdf_page_destroy(page);
501         }
502     }
503     swf_output_save(swf, outputname);
504     swf_output_destroy(swf);
505
506     pdf_destroy(pdf);
507
508     if(viewer || preloader) {
509 #ifndef SYSTEM_BACKTICKS
510         msg("<warning> Not sure whether system() can handle command substitution");
511         msg("<warning> (According to config.h, it can't)");
512 #endif
513         if(!system_quiet)
514             printf("\n");
515     }
516
517     if(viewer && !preloader) {
518         systemf("swfcombine `swfdump -XY \"%s\"` \"%s\" viewport=\"%s\" -o \"%s\"",
519                 outputname, viewer, outputname, outputname);
520         if(!system_quiet)
521             printf("\n");
522     }
523     if(preloader && !viewer) {
524         msg("<warning> --preloader option without --viewer option doesn't make very much sense.");
525         ret = systemf("swfcombine `swfdump -r \"%s\"` %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",
526                 preloader, SWFDIR, preloader, outputname, outputname);
527         if(!system_quiet)
528             printf("\n");
529     }
530     if(preloader && viewer) {
531         systemf("swfcombine \"%s\" viewport=%s -o __tmp__.swf",
532                 viewer, outputname, outputname);
533         systemf("swfcombine `swfdump -XY \"%s\"` `swfdump -r \"%s\"` %s/PreLoaderTemplate.swf loader=%s movie=__tmp__.swf -o \"%s\"",
534                 outputname, preloader, SWFDIR, preloader, outputname);
535         systemf("rm __tmp__.swf");
536     }
537
538     return 0;
539 }
540