if page range is given and % filename syntax is used, name files according to page...
[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     vsprintf(buf, 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->set_parameter(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 /*struct docoptions_t options[] =
443 {{"o","output","filename::Specify output file"},
444  {"V","version","Print program version"},
445  {"i","ignore","Ignore draw order (makes the SWF file smaller, but may produce graphic errors)"},
446  {"z","zlib","Use Flash 6 (MX) zlib compression (Needs at least Flash 6 Plugin to play)"},
447  {"s","shapes","Don't use SWF Fonts, but store everything as shape"},
448  {"j","jpegquality","Set quality of embedded jpeg pictures (default: 85)"},
449  {"p","pages","Convert only pages in range. (E.g. 3-85)"},
450  {"w","samewindow","Don't open a new browser window for links in the SWF"},
451  {"f","fonts","Stroe full fonts in SWF. (Don't reduce to used characters)"},
452  {"F","fontpath","path::Add directory to font search path"},
453  {"B","viewer","name::Link viewer \"name\" to the pdf"},
454  {"L","preloader","file.swf::Link preloader \"file.swf\" to the pdf"},
455  {"b","defaultviewer","Link default viewer to the pdf"},
456  {"l","defaultpreloader","Link default preloader to the pdf"}
457  {0,0}
458 };*/
459 static struct options_t options[] = {
460 {"h", "help"},
461 {"V", "version"},
462 {"o", "output"},
463 {"p", "pages"},
464 {"P", "password"},
465 {"v", "verbose"},
466 {"z", "zlib"},
467 {"i", "ignore"},
468 {"j", "jpegquality"},
469 {"s", "set"},
470 {"w", "samewindow"},
471 {"t", "stop"},
472 {"T", "flashversion"},
473 {"F", "fontdir"},
474 {"b", "defaultviewer"},
475 {"l", "defaultloader"},
476 {"B", "viewer"},
477 {"L", "preloader"},
478 {"q", "quiet"},
479 {"S", "shapes"},
480 {"f", "fonts"},
481 {"G", "flatten"},
482 {"I", "info"},
483 {"Q", "maxtime"},
484 {"X", "width"},
485 {"Y", "height"},
486 {0,0}
487 };
488
489 int args_callback_longoption(char*name,char*val) {
490     return args_long2shortoption(options, name, val);
491 }
492
493 int args_callback_command(char*name, char*val) {
494     if (!filename) 
495         filename = name;
496     else {
497         if(outputname)
498         {
499              fprintf(stderr, "Error: Do you want the output to go to %s or to %s?", 
500                      outputname, name);
501              exit(1);
502         }
503         outputname = name;
504     }
505     return 0;
506 }
507
508 void args_callback_usage(char *name)
509 {
510     printf("\n");
511     printf("Usage: %s [-options] file.pdf -o file.swf\n", name);
512     printf("\n");
513     printf("-h , --help                    Print short help message and exit\n");
514     printf("-V , --version                 Print version info and exit\n");
515     printf("-o , --output file.swf         Direct output to file.swf. If file.swf contains '%d' (file%d.swf), then each page \n");
516     printf("-p , --pages range             Convert only pages in range with range e.g. 1-20 or 1,4,6,9-11 or\n");
517     printf("-P , --password password       Use password for deciphering the pdf.\n");
518     printf("-v , --verbose                 Be verbose. Use more than one -v for greater effect.\n");
519     printf("-z , --zlib                    Use Flash 6 (MX) zlib compression.\n");
520     printf("-i , --ignore                  Allows pdf2swf to change the draw order of the pdf. This may make the generated\n");
521     printf("-j , --jpegquality quality     Set quality of embedded jpeg pictures to quality. 0 is worst (small), 100 is best (big). (default:85)\n");
522     printf("-s , --set param=value         Set a SWF encoder specific parameter.  See pdf2swf -s help for more information.\n");
523     printf("-w , --samewindow              When converting pdf hyperlinks, don't make the links open a new window. \n");
524     printf("-t , --stop                    Insert a stop() command in each page. \n");
525     printf("-T , --flashversion num        Set Flash Version in the SWF header to num.\n");
526     printf("-F , --fontdir directory       Add directory to the font search path.\n");
527     printf("-b , --defaultviewer           Link a standard viewer to the swf file. \n");
528     printf("-l , --defaultloader           Link a standard preloader to the swf file which will be displayed while the main swf is loading.\n");
529     printf("-B , --viewer filename         Link viewer filename to the swf file. \n");
530     printf("-L , --preloader filename      Link preloader filename to the swf file. \n");
531     printf("-q , --quiet                   Suppress normal messages.  Use -qq to suppress warnings, also.\n");
532     printf("-S , --shapes                  Don't use SWF Fonts, but store everything as shape.\n");
533     printf("-f , --fonts                   Store full fonts in SWF. (Don't reduce to used characters).\n");
534     printf("-G , --flatten                 Remove as many clip layers from file as possible. \n");
535     printf("-I , --info                    Don't do actual conversion, just display a list of all pages in the PDF.\n");
536     printf("-Q , --maxtime n               Abort conversion after n seconds. Only available on Unix.\n");
537     printf("\n");
538 }
539
540 float getRate(char*filename)
541 {
542     int fi;
543     SWF swf;
544     fi = open(filename,O_RDONLY|O_BINARY);
545     if(fi<0) { 
546         char buffer[256];
547         sprintf(buffer, "Couldn't open %s", filename);
548         perror(buffer);
549         exit(1);
550     }
551     if(swf_ReadSWF(fi,&swf) < 0)
552     { 
553         fprintf(stderr, "%s is not a valid SWF file or contains errors.\n",filename);
554         close(fi);
555         exit(1);
556     }
557     swf_FreeTags(&swf);
558     return swf.frameRate / 256.0;
559 }
560
561 void show_info(gfxsource_t*driver, char*filename)
562 {
563     gfxdocument_t* pdf = driver->open(driver, filename);
564     int pagenr;
565     FILE*fo=0;
566     if(!pdf) {
567         msg("<error> Couldn't open %s", filename);
568         exit(1);
569     }
570     if(outputname) {
571         fo = fopen(outputname, "wb");
572         if(!fo) {
573             perror(outputname);exit(1);;
574         }
575     } else {
576         fo = stdout;
577     }
578
579     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
580     {
581         gfxpage_t*page = pdf->getpage(pdf,pagenr);
582         if(is_in_range(pagenr, pagerange)) {
583             fprintf(fo, "page=%d width=%.2f height=%.2f\n", pagenr, page->width, page->height);
584         }
585     }
586     pdf->destroy(pdf);
587 }
588
589
590 static gfxdevice_t swf,wrap,rescale;
591 gfxdevice_t*create_output_device()
592 {
593     gfxdevice_swf_init(&swf);
594
595     /* set up filter chain */
596         
597     out = &swf;
598     if(flatten) {
599         gfxdevice_removeclippings_init(&wrap, &swf);
600         out = &wrap;
601     }
602
603     if(maxwidth || maxheight) {
604         gfxdevice_rescale_init(&rescale, out, maxwidth, maxheight, 0);
605         out = &rescale;
606     }
607
608     /* pass global parameters to output device */
609     parameter_t*p = device_config;
610     while(p) {
611         out->setparameter(out, p->name, p->value);
612         p = p->next;
613     }
614     return out;
615 }
616
617 int main(int argn, char *argv[])
618 {
619     int ret;
620     char buf[256];
621     int numfonts = 0;
622     int t;
623     char t1searchpath[1024];
624     int nup_pos = 0;
625     int x,y;
626     char* installPath = getInstallationPath();
627     int one_file_per_page = 0;
628     
629     initLog(0,-1,0,0,-1,loglevel);
630
631     /* not needed anymore since fonts are embedded
632        if(installPath) {
633         fontpaths[fontpathpos++] = concatPaths(installPath, "fonts");
634     }*/
635
636 #ifdef HAVE_SRAND48
637     srand48(time(0));
638 #else
639 #ifdef HAVE_SRAND
640     srand(time(0));
641 #endif
642 #endif
643
644     processargs(argn, argv);
645     
646     driver = gfxsource_pdf_create();
647     
648     /* pass global parameters to PDF driver*/
649     parameter_t*p = device_config;
650     while(p) {
651         driver->set_parameter(driver, p->name, p->value);
652         p = p->next;
653     }
654
655     if(!filename)
656     {
657         fprintf(stderr, "Please specify an input file\n");
658         exit(1);
659     }
660
661     if(info_only) {
662         show_info(driver, filename);
663         return 0;
664     }
665
666     if(!outputname)
667     {
668         if(filename) {
669             outputname = stripFilename(filename, ".swf");
670             msg("<notice> Output filename not given. Writing to %s", outputname);
671         } 
672     }
673         
674     if(!outputname)
675     {
676         fprintf(stderr, "Please use -o to specify an output file\n");
677         exit(1);
678     }
679
680     // test if the page range is o.k.
681     is_in_range(0x7fffffff, pagerange);
682
683     if(pagerange)
684         driver->set_parameter(driver, "pages", pagerange);
685
686     if (!filename) {
687         args_callback_usage(argv[0]);
688         exit(0);
689     }
690
691     /* add fonts */
692     for(t=0;t<fontpathpos;t++) {
693         driver->set_parameter(driver, "fontdir", fontpaths[t]);
694     }
695
696     char fullname[256];
697     if(password && *password) {
698         sprintf(fullname, "%s|%s", filename, password);
699         filename = fullname;
700     }
701
702     char*u = 0;
703     if((u = strchr(outputname, '%'))) {
704         if(strchr(u+1, '%') || 
705            strchr(outputname, '%')!=u)  {
706             msg("<error> only one %% allowed in filename\n");
707             return 1;
708         }
709         if(preloader || viewer) {
710             msg("<error> -b/-l/-B/-L not supported together with %% in filename\n");
711             return 1;
712         }
713         msg("<notice> outputting one file per page");
714         one_file_per_page = 1;
715         char*pattern = (char*)malloc(strlen(outputname)+2);
716         /* convert % to %d */
717         int l = u-outputname+1;
718         memcpy(pattern, outputname, l);
719         pattern[l]='d';
720         strcpy(pattern+l+1, outputname+l);
721         outputname = pattern;
722     }
723
724     gfxdocument_t* pdf = driver->open(driver, filename);
725     if(!pdf) {
726         msg("<error> Couldn't open %s", filename);
727         exit(1);
728     }
729     /* pass global parameters document */
730     p = device_config;
731     while(p) {
732         pdf->set_parameter(pdf, p->name, p->value);
733         p = p->next;
734     }
735
736     struct mypage_t {
737         int x;
738         int y;
739         gfxpage_t*page;
740     } pages[4];
741
742     int pagenum = 0;
743     int frame = 1;
744     int pagenr;
745     
746     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
747     {
748         if(is_in_range(pagenr, pagerange)) {
749             char mapping[80];
750             sprintf(mapping, "%d:%d", pagenr, frame);
751             pdf->set_parameter(pdf, "pagemap", mapping);
752             pagenum++;
753         }
754         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
755             pagenum = 0;
756             frame++;
757         }
758     }
759
760     pagenum = 0;
761
762     gfxdevice_t*out = create_output_device();;
763     for(pagenr = 1; pagenr <= pdf->num_pages; pagenr++) 
764     {
765         if(is_in_range(pagenr, pagerange)) {
766             gfxpage_t* page = pages[pagenum].page = pdf->getpage(pdf, pagenr);
767             pages[pagenum].x = 0;
768             pages[pagenum].y = 0;
769             pages[pagenum].page = page;
770             pagenum++;
771         }
772         if(pagenum == xnup*ynup || (pagenr == pdf->num_pages && pagenum>1)) {
773
774             int t;
775             int xmax[xnup], ymax[xnup];
776             int x,y;
777             int width=0, height=0;
778
779             memset(xmax, 0, xnup*sizeof(int));
780             memset(ymax, 0, ynup*sizeof(int));
781
782             for(y=0;y<ynup;y++)
783             for(x=0;x<xnup;x++) {
784                 int t = y*xnup + x;
785
786                 if(pages[t].page->width > xmax[x])
787                     xmax[x] = (int)pages[t].page->width;
788                 if(pages[t].page->height > ymax[y])
789                     ymax[y] = (int)pages[t].page->height;
790             }
791             for(x=0;x<xnup;x++) {
792                 width += xmax[x];
793                 xmax[x] = width;
794             }
795             for(y=0;y<ynup;y++) {
796                 height += ymax[y];
797                 ymax[y] = height;
798             }
799             if(custom_clip) {
800                 out->startpage(out,clip_x2 - clip_x1, clip_y2 - clip_y1);
801             } else {
802                 out->startpage(out,width,height);
803             }
804             for(t=0;t<pagenum;t++) {
805                 int x = t%xnup;
806                 int y = t/xnup;
807                 int xpos = x>0?xmax[x-1]:0;
808                 int ypos = y>0?ymax[y-1]:0;
809                 msg("<verbose> Render (%d,%d) move:%d/%d\n",
810                         (int)(pages[t].page->width + xpos),
811                         (int)(pages[t].page->height + ypos), xpos, ypos);
812                 pages[t].page->rendersection(pages[t].page, out, custom_move? move_x : xpos, 
813                                                            custom_move? move_y : ypos,
814                                                            custom_clip? clip_x1 : 0 + xpos, 
815                                                            custom_clip? clip_y1 : 0 + ypos, 
816                                                            custom_clip? clip_x2 : pages[t].page->width + xpos, 
817                                                            custom_clip? clip_y2 : pages[t].page->height + ypos);
818             }
819             out->endpage(out);
820             for(t=0;t<pagenum;t++)  {
821                 pages[t].page->destroy(pages[t].page);
822             }
823             pagenum = 0;
824
825             if(one_file_per_page) {
826                 gfxresult_t*result = out->finish(out);out=0;
827                 char buf[1024];
828                 sprintf(buf, outputname, pagenr);
829                 if(result->save(result, buf) < 0) {
830                     return 1;
831                 }
832                 result->destroy(result);result=0;
833                 out = create_output_device();;
834                 msg("<notice> Writing SWF file %s", buf);
835             }
836         }
837     }
838    
839     if(one_file_per_page) {
840         // remove empty device
841         gfxresult_t*result = out->finish(out);out=0;
842         result->destroy(result);result=0;
843     } else {
844         gfxresult_t*result = out->finish(out);
845         msg("<notice> Writing SWF file %s", outputname);
846         if(result->save(result, outputname) < 0) {
847             exit(1);
848         }
849         int width = (int)result->get(result, "width");
850         int height = (int)result->get(result, "height");
851         result->destroy(result);result=0;
852
853         if(preloader || viewer) {
854             const char*zip = "";
855             if(zlib) {
856                 zip = "-z";
857             }
858             if(!preloader && viewer) {
859                 systemf("swfcombine %s -X %d -Y %d \"%s\" viewport=\"%s\" -o \"%s\"",zip,width,height,
860                         viewer, outputname, outputname);
861                 if(!system_quiet)
862                     printf("\n");
863             }
864             if(preloader && !viewer) {
865                 msg("<warning> --preloader option without --viewer option doesn't make very much sense.");
866                 ret = systemf("swfcombine %s -Y %d -X %d %s/PreLoaderTemplate.swf loader=\"%s\" movie=\"%s\" -o \"%s\"",zip,width,height,
867                         SWFDIR, preloader, outputname, outputname);
868                 if(!system_quiet)
869                     printf("\n");
870             }
871             if(preloader && viewer) {
872 #ifdef HAVE_MKSTEMP
873                 char tmpname[] = "__swf__XXXXXX";
874                 mkstemp(tmpname);
875 #else 
876                 char*tmpname = "__tmp__.swf";
877 #endif
878                 systemf("swfcombine \"%s\" viewport=%s -o %s",
879                         viewer, outputname, tmpname);
880                 systemf("swfcombine %s -X %d -Y %d -r %f %s/PreLoaderTemplate.swf loader=%s movie=%s -o \"%s\"",zip,width,height,
881                         getRate(preloader), SWFDIR, preloader, tmpname, outputname);
882                 systemf("rm %s", tmpname);
883             }
884         }
885     }
886
887     pdf->destroy(pdf);
888     driver->destroy(driver);
889
890    
891     /* free global parameters */
892     p = device_config;
893     while(p) {
894         parameter_t*next = p->next;
895         if(p->name) free((void*)p->name);p->name = 0;
896         if(p->value) free((void*)p->value);p->value =0;
897         p->next = 0;free(p);
898         p = next;
899     }
900
901     return 0;
902 }
903