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