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