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