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