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