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