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