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