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