more parameter refactoring
[swftools.git] / src / pdf2swf.c
1 /* pdf2swf.c
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 <memory.h>
27 #include <unistd.h>
28 #include "../config.h"
29 #ifdef HAVE_SIGNAL_H
30 #include <signal.h>
31 #endif
32 #ifdef HAVE_DIRENT_H
33 #include <dirent.h>
34 #endif
35 #ifdef HAVE_MALLOC_H
36 #include <malloc.h>
37 #endif
38
39 #include "../lib/args.h"
40 #include "../lib/os.h"
41 #include "../lib/rfxswf.h"
42 #include "../lib/devices/swf.h"
43 #include "../lib/devices/polyops.h"
44 #include "../lib/devices/record.h"
45 #include "../lib/devices/rescale.h"
46 #include "../lib/pdf/pdf.h"
47 #include "../lib/log.h"
48
49 #define SWFDIR concatPaths(getInstallationPath(), "swfs")
50
51 static gfxsource_t*driver = 0;
52 static gfxdevice_t*out = 0;
53
54 static int maxwidth=0, maxheight=0;
55
56 static char * outputname = 0;
57 static int loglevel = 3;
58 static char * pagerange = 0;
59 static char * filename = 0;
60 static char * password = 0;
61 static int zlib = 0;
62
63 static char * preloader = 0;
64 static char * viewer = 0;
65 static int xnup = 1;
66 static int ynup = 1;
67
68 static int info_only = 0;
69
70 static int max_time = 0;
71
72 static int flatten = 0;
73
74 char* fontpaths[256];
75 int fontpathpos = 0;
76
77 int move_x=0;
78 int move_y=0;
79 int custom_move = 0;
80 int clip_x1=0,clip_y1=0,clip_x2=0,clip_y2=0;
81 int custom_clip = 0;
82
83 static int system_quiet=0;
84
85 int systemf(const char* format, ...)
86 {
87     char buf[1024];
88     int ret;
89     va_list arglist;
90     va_start(arglist, format);
91     vsnprintf(buf, sizeof(buf)-1, format, arglist);
92     va_end(arglist);
93
94     if(!system_quiet) {
95         printf("%s\n", buf);
96         fflush(stdout);
97     }
98     ret = system(buf);
99     if(ret) {
100         fprintf(stderr, "system() returned %d\n", ret);
101         exit(ret);
102     }
103     return ret;
104 }
105
106 #ifdef HAVE_SIGNAL_H
107 void sigalarm(int signal)
108 {
109     msg("<fatal> Aborting rendering after %d seconds", max_time);
110 #if 0 && defined(HAVE_SYS_TIME_H) && defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRUSAGE)
111     struct rusage usage;
112     getrusage(RUSAGE_CHILDREN, &usage);
113     msg("<fatal> Memory used: %d,%d,%d", usage.ru_maxrss, usage.ru_idrss, usage.ru_isrss);
114 #endif 
115 #if defined(HAVE_MALLINFO) && defined(HAVE_MALLOC_H)
116     struct mallinfo info = mallinfo();
117     msg("<fatal> Memory used: %d Mb (%d bytes)", info.uordblks/1048576, info.uordblks);
118 #endif
119     exit(1);
120 }
121 #endif
122
123 typedef struct _parameter {
124     struct _parameter*next;
125     const char*name;
126     const char*value;
127 } parameter_t;
128
129 static parameter_t* device_config = 0;
130 static parameter_t* device_config_next = 0;
131 static void store_parameter(const char*name, const char*value)
132 {
133     parameter_t*o = device_config;
134     while(o) {
135         if(!strcmp(name, o->name)) {
136             /* overwrite old value */
137             free((void*)o->value);
138             o->value = strdup(value);
139             return;
140         }
141         o = o->next;
142     }
143     parameter_t*p = (parameter_t*)malloc(sizeof(parameter_t));
144     p->name = strdup(name);
145     p->value = strdup(value);
146     p->next = 0;
147
148     if(device_config_next) {
149         device_config_next->next = p;
150         device_config_next = p;
151     } else {
152         device_config = p;
153         device_config_next = p;
154     }
155 }
156
157 int args_callback_option(char*name,char*val) {
158     if (!strcmp(name, "o"))
159     {
160         outputname = val;
161         return 1;
162     }
163     else if (!strcmp(name, "v"))
164     {
165         loglevel ++;
166         setConsoleLogging(loglevel);
167         return 0;
168     }
169     else if (!strcmp(name, "2"))
170     {
171         xnup = 2;
172         ynup = 1;
173         return 0;
174     }
175     else if (!strcmp(name, "4"))
176     {
177         xnup = 2;
178         ynup = 2;
179         return 0;
180     }
181     else if (!strcmp(name, "9"))
182     {
183         xnup = 3;
184         ynup = 3;
185         return 0;
186     }
187     else if (!strcmp(name, "X"))
188     {
189         maxwidth = atoi(val);
190         return 1;
191     }
192     else if (!strcmp(name, "Y"))
193     {
194         maxheight = atoi(val);
195         return 1;
196     }
197     else if (!strcmp(name, "q"))
198     {
199         loglevel --;
200         setConsoleLogging(loglevel);
201         system_quiet = 1;
202         return 0;
203     }
204     else if (name[0]=='p')
205     {
206         /* check whether the page range follows the p directly, like 
207            in -p1,2 */
208         do {
209             name++;
210         } while(*name == 32 || *name == 13 || *name == 10 || *name == '\t');
211
212         if(*name) {
213             pagerange = name;
214             return 0;
215         } 
216         pagerange = val;        
217         return 1;
218     }
219     else if (!strcmp(name, "P"))
220     {
221         password = val;
222         return 1;
223     }
224     else if (!strcmp(name, "c"))
225     {
226         char*s = strdup(val);
227         char*x1 = strtok(s, ":");
228         char*y1 = strtok(0, ":");
229         char*x2 = strtok(0, ":");
230         char*y2 = strtok(0, ":");
231         if(!(x1 && y1 && x2 && y2)) {
232             fprintf(stderr, "-c option requires four arguments, <x1>:<y1>:<x2>:<y2>\n");
233             exit(1);
234         }
235         custom_clip = 1;
236         clip_x1 = atoi(x1);
237         clip_y1 = atoi(y1);
238         clip_x2 = atoi(x2);
239         clip_y2 = atoi(y2);
240         free(s);
241         return 1;
242     }
243     else if (!strcmp(name, "m"))
244     {
245         char*s = strdup(val);
246         char*c = strchr(s, ':');
247         if(!c) {
248             fprintf(stderr, "-m option requires two arguments, <x>:<y>\n");
249             exit(1);
250         }
251         *c = 0;
252         custom_move = 1;
253         move_x = atoi(val);
254         move_y = atoi(c+1);
255         free(s);
256         return 1;
257     }
258     else if (!strcmp(name, "s"))
259     {
260         char*s = strdup(val);
261         char*c = strchr(s, '=');
262         if(c && *c && c[1])  {
263             *c = 0;
264             c++;
265             store_parameter(s,c);
266         } else if(!strcmp(s,"help")) {
267             printf("PDF Parameters:\n");
268             gfxsource_t*pdf = gfxsource_pdf_create();
269             pdf->setparameter(pdf, "help", "");
270             gfxdevice_t swf;
271             gfxdevice_swf_init(&swf);
272             printf("SWF Parameters:\n");
273             swf.setparameter(&swf, "help", "");
274             exit(0);
275         } else {
276             store_parameter(s,"1");
277         }
278         return 1;
279     }
280     else if (!strcmp(name, "S"))
281     {
282         store_parameter("drawonlyshapes", "1");
283         return 0;
284     }
285     else if (!strcmp(name, "i"))
286     {
287         store_parameter("ignoredraworder", "1");
288         return 0;
289     }
290 #ifndef WIN32
291     else if (!strcmp(name, "Q"))
292     {
293         max_time = atoi(val);
294         alarm(max_time);
295 # ifdef HAVE_SIGNAL_H
296         signal(SIGALRM, sigalarm);
297 # endif
298         return 1;
299     }
300 #endif
301     else if (!strcmp(name, "z"))
302     {
303         store_parameter("enablezlib", "1");
304         zlib = 1;
305         return 0;
306     }
307     else if (!strcmp(name, "n"))
308     {
309         store_parameter("opennewwindow", "1");
310         return 0;
311     }
312     else if (!strcmp(name, "I"))
313     {
314         info_only = 1;
315         return 0;
316     }
317     else if (!strcmp(name, "t"))
318     {
319         store_parameter("insertstop", "1");
320         return 0;
321     }
322     else if (!strcmp(name, "T"))
323     {
324         if(!strcasecmp(val, "mx"))
325             store_parameter("flashversion", "6");
326         else
327             store_parameter("flashversion", val);
328
329         return 1;
330     }
331     else if (!strcmp(name, "f"))
332     {
333         store_parameter("storeallcharacters", "1");
334         store_parameter("extrafontdata", "1");
335         return 0;
336     }
337     else if (!strcmp(name, "w"))
338     {
339         store_parameter("linksopennewwindow", "0");
340         return 0;
341     }
342     else if (!strcmp(name, "O"))
343     {
344         int level = 1;
345         int ret=0;
346         if(val&& val[0] && val[1]==0 && isdigit(val[0])) {
347             level = atoi(val);
348             ret=1;
349         }
350         if(level>=1)
351             store_parameter("poly2bitmap", "1");
352         if(level>=2)
353             store_parameter("bitmapfonts", "1");
354         if(level>=3)
355             store_parameter("ignoredraworder", "1");
356         return ret;
357     }
358     else if (!strcmp(name, "G"))
359     {
360         //store_parameter("optimize_polygons", "1");
361         flatten = 1;
362         return 0;
363     }
364     else if (!strcmp(name, "F"))
365     {
366         char *s = strdup(val);
367         int l = strlen(s);
368         while(l && s[l-1]=='/') {
369             s[l-1] = 0;
370             l--;
371         }
372         fontpaths[fontpathpos++] = s;
373         return 1;
374     }
375     else if (!strcmp(name, "l"))
376     {
377         char buf[256];
378         sprintf(buf, "%s/default_loader.swf", SWFDIR);
379         preloader = strdup(buf);
380         return 0;
381     }
382     else if (!strcmp(name, "b"))
383     {
384         char buf[256];
385         sprintf(buf, "%s/default_viewer.swf", SWFDIR);
386         viewer = strdup(buf);
387         return 0;
388     }
389     else if (!strcmp(name, "L"))
390     {
391         if(val)
392         {
393             preloader = val;
394         }
395         else
396         {
397             systemf("ls %s/*_loader.swf", SWFDIR);
398             if(!system_quiet)
399                 printf("\n");
400             exit(1);
401         }
402         return 1;
403     }
404     else if (!strcmp(name, "B"))
405     {
406         if(val)
407         {
408             viewer = val;
409         }
410         else
411         {
412             systemf("ls %s/*_viewer.swf", SWFDIR);
413             if(!system_quiet)
414                 printf("\n");
415             exit(1);
416         }
417         return 1;
418     }
419     else if (!strcmp(name, "j"))
420     {
421         if(name[1]) {
422             store_parameter("jpegquality", &name[1]);
423             return 0;
424         } else {
425             store_parameter("jpegquality", val);
426             return 1;
427         }
428     }
429     else if (!strcmp(name, "V"))
430     {   
431         printf("pdf2swf - part of %s %s\n", PACKAGE, VERSION);
432         exit(0);
433     }
434     else 
435     {
436         fprintf(stderr, "Unknown option: -%s\n", name);
437         exit(1);
438     }
439     return 0;
440 }
441
442 static struct options_t options[] = {
443 {"h", "help"},
444 {"V", "version"},
445 {"o", "output"},
446 {"p", "pages"},
447 {"P", "password"},
448 {"v", "verbose"},
449 {"z", "zlib"},
450 {"i", "ignore"},
451 {"j", "jpegquality"},
452 {"s", "set"},
453 {"w", "samewindow"},
454 {"t", "stop"},
455 {"T", "flashversion"},
456 {"F", "fontdir"},
457 {"b", "defaultviewer"},
458 {"l", "defaultloader"},
459 {"B", "viewer"},
460 {"L", "preloader"},
461 {"q", "quiet"},
462 {"S", "shapes"},
463 {"f", "fonts"},
464 {"G", "flatten"},
465 {"I", "info"},
466 {"Q", "maxtime"},
467 {"X", "width"},
468 {"Y", "height"},
469 {0,0}
470 };
471
472 int args_callback_longoption(char*name,char*val) {
473     return args_long2shortoption(options, name, val);
474 }
475
476 int args_callback_command(char*name, char*val) {
477     if (!filename) 
478         filename = name;
479     else {
480         if(outputname)
481         {
482              fprintf(stderr, "Error: Do you want the output to go to %s or to %s?", 
483                      outputname, name);
484              exit(1);
485         }
486         outputname = name;
487     }
488     return 0;
489 }
490
491 void args_callback_usage(char *name)
492 {
493     printf("\n");
494     printf("Usage: %s [-options] file.pdf -o file.swf\n", name);
495     printf("\n");
496     printf("-h , --help                    Print short help message and exit\n");
497     printf("-V , --version                 Print version info and exit\n");
498     printf("-o , --output file.swf         Direct output to file.swf. If file.swf contains '%%' (file%%.swf), then each page goes to a seperate file.\n");
499     printf("-p , --pages range             Convert only pages in range with range e.g. 1-20 or 1,4,6,9-11 or\n");
500     printf("-P , --password password       Use password for deciphering the pdf.\n");
501     printf("-v , --verbose                 Be verbose. Use more than one -v for greater effect.\n");
502     printf("-z , --zlib                    Use Flash 6 (MX) zlib compression.\n");
503     printf("-i , --ignore                  Allows pdf2swf to change the draw order of the pdf. This may make the generated\n");
504     printf("-j , --jpegquality quality     Set quality of embedded jpeg pictures to quality. 0 is worst (small), 100 is best (big). (default:85)\n");
505     printf("-s , --set param=value         Set a SWF encoder specific parameter.  See pdf2swf -s help for more information.\n");
506     printf("-w , --samewindow              When converting pdf hyperlinks, don't make the links open a new window. \n");
507     printf("-t , --stop                    Insert a stop() command in each page. \n");
508     printf("-T , --flashversion num        Set Flash Version in the SWF header to num.\n");
509     printf("-F , --fontdir directory       Add directory to the font search path.\n");
510     printf("-b , --defaultviewer           Link a standard viewer to the swf file. \n");
511     printf("-l , --defaultloader           Link a standard preloader to the swf file which will be displayed while the main swf is loading.\n");
512     printf("-B , --viewer filename         Link viewer filename to the swf file. \n");
513     printf("-L , --preloader filename      Link preloader filename to the swf file. \n");
514     printf("-q , --quiet                   Suppress normal messages.  Use -qq to suppress warnings, also.\n");
515     printf("-S , --shapes                  Don't use SWF Fonts, but store everything as shape.\n");
516     printf("-f , --fonts                   Store full fonts in SWF. (Don't reduce to used characters).\n");
517     printf("-G , --flatten                 Remove as many clip layers from file as possible. \n");
518     printf("-I , --info                    Don't do actual conversion, just display a list of all pages in the PDF.\n");
519     printf("-Q , --maxtime n               Abort conversion after n seconds. Only available on Unix.\n");
520     printf("\n");
521 }
522
523 float getRate(char*filename)
524 {
525     int fi;
526     SWF swf;
527     fi = open(filename,O_RDONLY|O_BINARY);
528     if(fi<0) { 
529         char buffer[256];
530         sprintf(buffer, "Couldn't open %s", filename);
531         perror(buffer);
532         exit(1);
533     }
534     if(swf_ReadSWF(fi,&swf) < 0)
535     { 
536         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
537         close(fi);
538         exit(1);
539     }
540     swf_FreeTags(&swf);
541     return swf.frameRate / 256.0;
542 }
543
544 void show_info(gfxsource_t*driver, char*filename)
545 {
546     gfxdocument_t* pdf = driver->open(driver, filename);
547     int pagenr;
548     FILE*fo=0;
549     if(!pdf) {
550         msg("<error> Couldn't open %s", filename);
551         exit(1);
552     }
553     if(outputname) {
554         fo = fopen(outputname, "wb");
555         if(!fo) {
556             perror(outputname);exit(1);;
557         }
558     } else {
559         fo = stdout;
560     }
561
562     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
563     {
564         gfxpage_t*page = pdf->getpage(pdf,pagenr);
565         if(is_in_range(pagenr, pagerange)) {
566             fprintf(fo, "page=%d width=%.2f height=%.2f\n", pagenr, page->width, page->height);
567         }
568     }
569     pdf->destroy(pdf);
570 }
571
572
573 static gfxdevice_t swf,wrap,rescale;
574 gfxdevice_t*create_output_device()
575 {
576     gfxdevice_swf_init(&swf);
577
578     /* set up filter chain */
579         
580     out = &swf;
581     if(flatten) {
582         gfxdevice_removeclippings_init(&wrap, &swf);
583         out = &wrap;
584     }
585
586     if(maxwidth || maxheight) {
587         gfxdevice_rescale_init(&rescale, out, maxwidth, maxheight, 0);
588         out = &rescale;
589     }
590
591     /* pass global parameters to output device */
592     parameter_t*p = device_config;
593     while(p) {
594         out->setparameter(out, p->name, p->value);
595         p = p->next;
596     }
597     return out;
598 }
599
600 int main(int argn, char *argv[])
601 {
602     int ret;
603     char buf[256];
604     int numfonts = 0;
605     int t;
606     char t1searchpath[1024];
607     int nup_pos = 0;
608     int x,y;
609     int one_file_per_page = 0;
610     
611     initLog(0,-1,0,0,-1,loglevel);
612
613     /* not needed anymore since fonts are embedded
614        if(installPath) {
615         fontpaths[fontpathpos++] = concatPaths(installPath, "fonts");
616     }*/
617
618 #ifdef HAVE_SRAND48
619     srand48(time(0));
620 #else
621 #ifdef HAVE_SRAND
622     srand(time(0));
623 #endif
624 #endif
625
626     processargs(argn, argv);
627     
628     driver = gfxsource_pdf_create();
629     
630     /* pass global parameters to PDF driver*/
631     parameter_t*p = device_config;
632     while(p) {
633         driver->setparameter(driver, p->name, p->value);
634         p = p->next;
635     }
636
637     if(!filename)
638     {
639         fprintf(stderr, "Please specify an input file\n");
640         exit(1);
641     }
642
643     if (!info_only) {
644         if(!outputname)
645         {
646             if(filename) {
647                 outputname = stripFilename(filename, ".swf");
648                 msg("<notice> Output filename not given. Writing to %s", outputname);
649             } 
650         }
651             
652         if(!outputname)
653         {
654             fprintf(stderr, "Please use -o to specify an output file\n");
655             exit(1);
656         }
657     }
658
659     // test if the page range is o.k.
660     is_in_range(0x7fffffff, pagerange);
661
662     if (!filename) {
663         args_callback_usage(argv[0]);
664         exit(0);
665     }
666     
667     char fullname[256];
668     if(password && *password) {
669         sprintf(fullname, "%s|%s", filename, password);
670         filename = fullname;
671     }
672     
673     if(pagerange)
674         driver->setparameter(driver, "pages", pagerange);
675
676     /* add fonts */
677     for(t=0;t<fontpathpos;t++) {
678         driver->setparameter(driver, "fontdir", fontpaths[t]);
679     }
680
681     if(info_only) {
682         show_info(driver, filename);
683         return 0;
684     }
685
686     char*u = 0;
687     if((u = strchr(outputname, '%'))) {
688         if(strchr(u+1, '%') || 
689            strchr(outputname, '%')!=u)  {
690             msg("<error> only one %% allowed in filename\n");
691             return 1;
692         }
693         if(preloader || viewer) {
694             msg("<error> -b/-l/-B/-L not supported together with %% in filename\n");
695             return 1;
696         }
697         msg("<notice> outputting one file per page");
698         one_file_per_page = 1;
699         char*pattern = (char*)malloc(strlen(outputname)+2);
700         /* convert % to %d */
701         int l = u-outputname+1;
702         memcpy(pattern, outputname, l);
703         pattern[l]='d';
704         strcpy(pattern+l+1, outputname+l);
705         outputname = pattern;
706     }
707
708     gfxdocument_t* pdf = driver->open(driver, filename);
709     if(!pdf) {
710         msg("<error> Couldn't open %s", filename);
711         exit(1);
712     }
713     /* pass global parameters document */
714     p = device_config;
715     while(p) {
716         pdf->setparameter(pdf, p->name, p->value);
717         p = p->next;
718     }
719
720     struct mypage_t {
721         int x;
722         int y;
723         gfxpage_t*page;
724     } pages[4];
725
726     int pagenum = 0;
727     int frame = 1;
728     int pagenr;
729     
730     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
731     {
732         if(is_in_range(pagenr, pagerange)) {
733             char mapping[80];
734             sprintf(mapping, "%d:%d", pagenr, frame);
735             pdf->setparameter(pdf, "pagemap", mapping);
736             pagenum++;
737         }
738         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
739             pagenum = 0;
740             frame++;
741         }
742     }
743     if(pagerange && !pagenum && frame==1) {
744         fprintf(stderr, "No pages in range %s", pagerange);
745         exit(1);
746     }
747
748     pagenum = 0;
749
750     gfxdevice_t*out = create_output_device();;
751     pdf->prepare(pdf, out);
752
753     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
754     {
755         if(is_in_range(pagenr, pagerange)) {
756             gfxpage_t* page = pages[pagenum].page = pdf->getpage(pdf, pagenr);
757             pages[pagenum].x = 0;
758             pages[pagenum].y = 0;
759             pages[pagenum].page = page;
760             pagenum++;
761         }
762         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
763
764             int t;
765             int xmax[xnup], ymax[xnup];
766             int x,y;
767             int width=0, height=0;
768
769             memset(xmax, 0, xnup*sizeof(int));
770             memset(ymax, 0, ynup*sizeof(int));
771
772             for(y=0;y<ynup;y++)
773             for(x=0;x<xnup;x++) {
774                 int t = y*xnup + x;
775
776                 if(pages[t].page->width > xmax[x])
777                     xmax[x] = (int)pages[t].page->width;
778                 if(pages[t].page->height > ymax[y])
779                     ymax[y] = (int)pages[t].page->height;
780             }
781             for(x=0;x<xnup;x++) {
782                 width += xmax[x];
783                 xmax[x] = width;
784             }
785             for(y=0;y<ynup;y++) {
786                 height += ymax[y];
787                 ymax[y] = height;
788             }
789             if(custom_clip) {
790                 out->startpage(out,clip_x2 - clip_x1, clip_y2 - clip_y1);
791             } else {
792                 out->startpage(out,width,height);
793             }
794             for(t=0;t<pagenum;t++) {
795                 int x = t%xnup;
796                 int y = t/xnup;
797                 int xpos = x>0?xmax[x-1]:0;
798                 int ypos = y>0?ymax[y-1]:0;
799                 msg("<verbose> Render (%d,%d) move:%d/%d\n",
800                         (int)(pages[t].page->width + xpos),
801                         (int)(pages[t].page->height + ypos), xpos, ypos);
802                 pages[t].page->rendersection(pages[t].page, out, custom_move? move_x : xpos, 
803                                                            custom_move? move_y : ypos,
804                                                            custom_clip? clip_x1 : 0 + xpos, 
805                                                            custom_clip? clip_y1 : 0 + ypos, 
806                                                            custom_clip? clip_x2 : pages[t].page->width + xpos, 
807                                                            custom_clip? clip_y2 : pages[t].page->height + ypos);
808             }
809             out->endpage(out);
810             for(t=0;t<pagenum;t++)  {
811                 pages[t].page->destroy(pages[t].page);
812             }
813             pagenum = 0;
814
815             if(one_file_per_page) {
816                 gfxresult_t*result = out->finish(out);out=0;
817                 char buf[1024];
818                 sprintf(buf, outputname, pagenr);
819                 if(result->save(result, buf) < 0) {
820                     return 1;
821                 }
822                 result->destroy(result);result=0;
823                 out = create_output_device();;
824                 msg("<notice> Writing SWF file %s", buf);
825             }
826         }
827     }
828    
829     if(one_file_per_page) {
830         // remove empty device
831         gfxresult_t*result = out->finish(out);out=0;
832         result->destroy(result);result=0;
833     } else {
834         gfxresult_t*result = out->finish(out);
835         msg("<notice> Writing SWF file %s", outputname);
836         if(result->save(result, outputname) < 0) {
837             exit(1);
838         }
839         int width = (int)(ptroff_t)result->get(result, "width");
840         int height = (int)(ptroff_t)result->get(result, "height");
841         result->destroy(result);result=0;
842
843         if(preloader || viewer) {
844             const char*zip = "";
845             if(zlib) {
846                 zip = "-z";
847             }
848             if(!preloader && viewer) {
849                 systemf("swfcombine %s -X %d -Y %d \"%s\" viewport=\"%s\" -o \"%s\"",zip,width,height,
850                         viewer, outputname, outputname);
851                 if(!system_quiet)
852                     printf("\n");
853             }
854             if(preloader && !viewer) {
855                 msg("<warning> --preloader option without --viewer option doesn't make very much sense.");
856                 ret = systemf("swfcombine %s -Y %d -X %d %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",zip,width,height,
857                         SWFDIR, preloader, outputname, outputname);
858                 if(!system_quiet)
859                     printf("\n");
860             }
861             if(preloader && viewer) {
862 #ifdef HAVE_MKSTEMP
863                 char tmpname[] = "__swf__XXXXXX";
864                 mkstemp(tmpname);
865 #else 
866                 char*tmpname = "__tmp__.swf";
867 #endif
868                 systemf("swfcombine \"%s\" viewport=%s -o %s",
869                         viewer, outputname, tmpname);
870                 systemf("swfcombine %s -X %d -Y %d -r %f %s/PreLoaderTemplate.swf loader=%s movie=%s -o \"%s\"",zip,width,height,
871                         getRate(preloader), SWFDIR, preloader, tmpname, outputname);
872                 systemf("rm %s", tmpname);
873             }
874         }
875     }
876
877     pdf->destroy(pdf);
878     driver->destroy(driver);
879
880    
881     /* free global parameters */
882     p = device_config;
883     while(p) {
884         parameter_t*next = p->next;
885         if(p->name) free((void*)p->name);p->name = 0;
886         if(p->value) free((void*)p->value);p->value =0;
887         p->next = 0;free(p);
888         p = next;
889     }
890
891     return 0;
892 }
893