]> granicus.if.org Git - imagemagick/blob - coders/pdf.c
Check for sampling-factor option only if sampling-factor image property is NULL.
[imagemagick] / coders / pdf.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            PPPP   DDDD   FFFFF                              %
7 %                            P   P  D   D  F                                  %
8 %                            PPPP   D   D  FFF                                %
9 %                            P      D   D  F                                  %
10 %                            P      DDDD   F                                  %
11 %                                                                             %
12 %                                                                             %
13 %                   Read/Write Portable Document Format                       %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/attribute.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/color.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colorspace.h"
50 #include "MagickCore/colorspace-private.h"
51 #include "MagickCore/compress.h"
52 #include "MagickCore/constitute.h"
53 #include "MagickCore/delegate.h"
54 #include "MagickCore/delegate-private.h"
55 #include "MagickCore/draw.h"
56 #include "MagickCore/exception.h"
57 #include "MagickCore/exception-private.h"
58 #include "MagickCore/geometry.h"
59 #include "MagickCore/image.h"
60 #include "MagickCore/image-private.h"
61 #include "MagickCore/list.h"
62 #include "MagickCore/magick.h"
63 #include "MagickCore/memory_.h"
64 #include "MagickCore/monitor.h"
65 #include "MagickCore/monitor-private.h"
66 #include "MagickCore/option.h"
67 #include "MagickCore/pixel-accessor.h"
68 #include "MagickCore/profile.h"
69 #include "MagickCore/property.h"
70 #include "MagickCore/quantum-private.h"
71 #include "MagickCore/resource_.h"
72 #include "MagickCore/resize.h"
73 #include "MagickCore/signature.h"
74 #include "MagickCore/static.h"
75 #include "MagickCore/string_.h"
76 #include "MagickCore/module.h"
77 #include "MagickCore/token.h"
78 #include "MagickCore/transform.h"
79 #include "MagickCore/utility.h"
80 #include "MagickCore/module.h"
81 \f
82 /*
83   Define declarations.
84 */
85 #if defined(MAGICKCORE_TIFF_DELEGATE)
86 #define CCITTParam  "-1"
87 #else
88 #define CCITTParam  "0"
89 #endif
90 \f
91 /*
92   Forward declarations.
93 */
94 static MagickBooleanType
95   WritePDFImage(const ImageInfo *,Image *,ExceptionInfo *);
96 \f
97 /*
98 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
99 %                                                                             %
100 %                                                                             %
101 %                                                                             %
102 %   I n v o k e P D F D e l e g a t e                                         %
103 %                                                                             %
104 %                                                                             %
105 %                                                                             %
106 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
107 %
108 %  InvokePDFDelegate() executes the PDF interpreter with the specified command.
109 %
110 %  The format of the InvokePDFDelegate method is:
111 %
112 %      MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose,
113 %        const char *command,ExceptionInfo *exception)
114 %
115 %  A description of each parameter follows:
116 %
117 %    o verbose: A value other than zero displays the command prior to
118 %      executing it.
119 %
120 %    o command: the address of a character string containing the command to
121 %      execute.
122 %
123 %    o exception: return any errors or warnings in this structure.
124 %
125 */
126 static MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose,
127   const char *command,ExceptionInfo *exception)
128 {
129   int
130     status;
131
132 #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT)
133   char
134     **argv;
135
136   const GhostInfo
137     *ghost_info;
138
139   gs_main_instance
140     *interpreter;
141
142   int
143     argc,
144     code;
145
146   register ssize_t
147     i;
148
149 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
150   ghost_info=NTGhostscriptDLLVectors();
151 #else
152   GhostInfo
153     ghost_info_struct;
154
155   ghost_info=(&ghost_info_struct);
156   (void) ResetMagickMemory(&ghost_info,0,sizeof(ghost_info));
157   ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *))
158     gsapi_new_instance;
159   ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **))
160     gsapi_init_with_args;
161   ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int,
162     int *)) gsapi_run_string;
163   ghost_info_struct.delete_instance=(void (*)(gs_main_instance *))
164     gsapi_delete_instance;
165   ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit;
166 #endif
167   if (ghost_info == (GhostInfo *) NULL)
168     {
169       status=SystemCommand(MagickFalse,verbose,command,exception);
170       return(status == 0 ? MagickTrue : MagickFalse);
171     }
172   if (verbose != MagickFalse)
173     {
174       (void) fputs("[ghostscript library]",stdout);
175       (void) fputs(strchr(command,' '),stdout);
176     }
177   status=(ghost_info->new_instance)(&interpreter,(void *) NULL);
178   if (status < 0)
179     {
180       status=SystemCommand(MagickFalse,verbose,command,exception);
181       return(status == 0 ? MagickTrue : MagickFalse);
182     }
183   code=0;
184   argv=StringToArgv(command,&argc);
185   status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1);
186   if (status == 0)
187     status=(ghost_info->run_string)(interpreter,"systemdict /start get exec\n",
188       0,&code);
189   (ghost_info->exit)(interpreter);
190   (ghost_info->delete_instance)(interpreter);
191 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
192   NTGhostscriptUnLoadDLL();
193 #endif
194   for (i=0; i < (ssize_t) argc; i++)
195     argv[i]=DestroyString(argv[i]);
196   argv=(char **) RelinquishMagickMemory(argv);
197   if ((status != 0) && (status != -101))
198     {
199       char
200         *message;
201
202       message=GetExceptionMessage(errno);
203       (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,
204         "`%s': %s",command,message);
205       message=DestroyString(message);
206       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
207         "Ghostscript returns status %d, exit code %d",status,code);
208       return(MagickFalse);
209     }
210   return(MagickTrue);
211 #else
212   status=SystemCommand(MagickFalse,verbose,command,exception);
213   return(status == 0 ? MagickTrue : MagickFalse);
214 #endif
215 }
216 \f
217 /*
218 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
219 %                                                                             %
220 %                                                                             %
221 %                                                                             %
222 %   I s P D F                                                                 %
223 %                                                                             %
224 %                                                                             %
225 %                                                                             %
226 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
227 %
228 %  IsPDF() returns MagickTrue if the image format type, identified by the
229 %  magick string, is PDF.
230 %
231 %  The format of the IsPDF method is:
232 %
233 %      MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset)
234 %
235 %  A description of each parameter follows:
236 %
237 %    o magick: compare image format pattern against these bytes.
238 %
239 %    o offset: Specifies the offset of the magick string.
240 %
241 */
242 static MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset)
243 {
244   if (offset < 5)
245     return(MagickFalse);
246   if (LocaleNCompare((const char *) magick,"%PDF-",5) == 0)
247     return(MagickTrue);
248   return(MagickFalse);
249 }
250 \f
251 /*
252 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
253 %                                                                             %
254 %                                                                             %
255 %                                                                             %
256 %   R e a d P D F I m a g e                                                   %
257 %                                                                             %
258 %                                                                             %
259 %                                                                             %
260 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
261 %
262 %  ReadPDFImage() reads a Portable Document Format image file and
263 %  returns it.  It allocates the memory necessary for the new Image structure
264 %  and returns a pointer to the new image.
265 %
266 %  The format of the ReadPDFImage method is:
267 %
268 %      Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)
269 %
270 %  A description of each parameter follows:
271 %
272 %    o image_info: the image info.
273 %
274 %    o exception: return any errors or warnings in this structure.
275 %
276 */
277
278 static MagickBooleanType IsPDFRendered(const char *path)
279 {
280   MagickBooleanType
281     status;
282
283   struct stat
284     attributes;
285
286   if ((path == (const char *) NULL) || (*path == '\0'))
287     return(MagickFalse);
288   status=GetPathAttributes(path,&attributes);
289   if ((status != MagickFalse) && S_ISREG(attributes.st_mode) &&
290       (attributes.st_size > 0))
291     return(MagickTrue);
292   return(MagickFalse);
293 }
294
295 static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)
296 {
297 #define CMYKProcessColor  "CMYKProcessColor"
298 #define CropBox  "CropBox"
299 #define DefaultCMYK  "DefaultCMYK"
300 #define DeviceCMYK  "DeviceCMYK"
301 #define MediaBox  "MediaBox"
302 #define RenderPostscriptText  "Rendering Postscript...  "
303 #define PDFRotate  "Rotate"
304 #define SpotColor  "Separation"
305 #define TrimBox  "TrimBox"
306 #define PDFVersion  "PDF-"
307
308   char
309     command[MaxTextExtent],
310     density[MaxTextExtent],
311     filename[MaxTextExtent],
312     geometry[MaxTextExtent],
313     options[MaxTextExtent],
314     input_filename[MaxTextExtent],
315     postscript_filename[MaxTextExtent];
316
317   const char
318     *option;
319
320   const DelegateInfo
321     *delegate_info;
322
323   double
324     angle;
325
326   GeometryInfo
327     geometry_info;
328
329   Image
330     *image,
331     *next,
332     *pdf_image;
333
334   ImageInfo
335     *read_info;
336
337   int
338     c,
339     file;
340
341   MagickBooleanType
342     cmyk,
343     cropbox,
344     trimbox,
345     status;
346
347   MagickStatusType
348     flags;
349
350   PointInfo
351     delta;
352
353   RectangleInfo
354     bounding_box,
355     page;
356
357   register char
358     *p;
359
360   register ssize_t
361     i;
362
363   SegmentInfo
364     bounds,
365     hires_bounds;
366
367   size_t
368     scene,
369     spotcolor;
370
371   ssize_t
372     count;
373
374   assert(image_info != (const ImageInfo *) NULL);
375   assert(image_info->signature == MagickSignature);
376   if (image_info->debug != MagickFalse)
377     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
378       image_info->filename);
379   assert(exception != (ExceptionInfo *) NULL);
380   assert(exception->signature == MagickSignature);
381   /*
382     Open image file.
383   */
384   image=AcquireImage(image_info,exception);
385   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
386   if (status == MagickFalse)
387     {
388       image=DestroyImageList(image);
389       return((Image *) NULL);
390     }
391   status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);
392   if (status == MagickFalse)
393     {
394       ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
395         image_info->filename);
396       image=DestroyImageList(image);
397       return((Image *) NULL);
398     }
399   /*
400     Set the page density.
401   */
402   delta.x=DefaultResolution;
403   delta.y=DefaultResolution;
404   if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))
405     {
406       flags=ParseGeometry(PSDensityGeometry,&geometry_info);
407       image->resolution.x=geometry_info.rho;
408       image->resolution.y=geometry_info.sigma;
409       if ((flags & SigmaValue) == 0)
410         image->resolution.y=image->resolution.x;
411     }
412   if (image_info->density != (char *) NULL)
413     {
414       flags=ParseGeometry(image_info->density,&geometry_info);
415       image->resolution.x=geometry_info.rho;
416       image->resolution.y=geometry_info.sigma;
417       if ((flags & SigmaValue) == 0)
418         image->resolution.y=image->resolution.x;
419     }
420   (void) ParseAbsoluteGeometry(PSPageGeometry,&page);
421   if (image_info->page != (char *) NULL)
422     (void) ParseAbsoluteGeometry(image_info->page,&page);
423   page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)-
424     0.5);
425   page.height=(size_t) ceil((double) (page.height*image->resolution.y/delta.y)-
426     0.5);
427   /*
428     Determine page geometry from the PDF media box.
429   */
430   cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;
431   cropbox=IsStringTrue(GetImageOption(image_info,"pdf:use-cropbox"));
432   trimbox=IsStringTrue(GetImageOption(image_info,"pdf:use-trimbox"));
433   count=0;
434   spotcolor=0;
435   (void) ResetMagickMemory(&bounding_box,0,sizeof(bounding_box));
436   (void) ResetMagickMemory(&bounds,0,sizeof(bounds));
437   (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds));
438   (void) ResetMagickMemory(command,0,sizeof(command));
439   angle=0.0;
440   p=command;
441   for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
442   {
443     /*
444       Note PDF elements.
445     */
446     if (c == '\n')
447       c=' ';
448     *p++=(char) c;
449     if ((c != (int) '/') && (c != (int) '%') &&
450         ((size_t) (p-command) < (MaxTextExtent-1)))
451       continue;
452     *(--p)='\0';
453     p=command;
454     if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0)
455       count=(ssize_t) sscanf(command,"Rotate %lf",&angle);
456     /*
457       Is this a CMYK document?
458     */
459     if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0)
460       cmyk=MagickTrue;
461     if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)
462       cmyk=MagickTrue;
463     if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0)
464       cmyk=MagickTrue;
465     if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)
466       {
467         char
468           name[MaxTextExtent],
469           property[MaxTextExtent],
470           *value;
471
472         register ssize_t
473           i;
474
475         /*
476           Note spot names.
477         */
478         (void) FormatLocaleString(property,MaxTextExtent,"pdf:SpotColor-%.20g",
479           (double) spotcolor++);
480         i=0;
481         for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))
482         {
483           if ((isspace(c) != 0) || (c == '/') || ((i+1) == MaxTextExtent))
484             break;
485           name[i++]=(char) c;
486         }
487         name[i]='\0';
488         value=AcquireString(name);
489         (void) SubstituteString(&value,"#20"," ");
490         (void) SetImageProperty(image,property,value,exception);
491         value=DestroyString(value);
492         continue;
493       }
494     if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0)
495       (void) SetImageProperty(image,"pdf:Version",command,exception);
496     if (image_info->page != (char *) NULL)
497       continue;
498     count=0;
499     if (cropbox != MagickFalse)
500       {
501         if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)
502           {
503             /*
504               Note region defined by crop box.
505             */
506             count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf",
507               &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
508             if (count != 4)
509               count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf",
510                 &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
511           }
512       }
513     else
514       if (trimbox != MagickFalse)
515         {
516           if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0)
517             {
518               /*
519                 Note region defined by trim box.
520               */
521               count=(ssize_t) sscanf(command,"TrimBox [%lf %lf %lf %lf",
522                 &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
523               if (count != 4)
524                 count=(ssize_t) sscanf(command,"TrimBox[%lf %lf %lf %lf",
525                   &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
526             }
527         }
528       else
529         if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)
530           {
531             /*
532               Note region defined by media box.
533             */
534             count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf",
535               &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
536             if (count != 4)
537               count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf",
538                 &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);
539           }
540     if (count != 4)
541       continue;
542     if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) ||
543         (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1)))
544       continue;
545     hires_bounds=bounds;
546   }
547   if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && 
548       (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon))
549     {
550       /*
551         Set PDF render geometry.
552       */
553       (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g",
554         hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1,
555         hires_bounds.x1,hires_bounds.y1);
556       (void) SetImageProperty(image,"pdf:HiResBoundingBox",geometry,exception);
557       page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)*
558         image->resolution.x/delta.x)-0.5);
559       page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)*
560         image->resolution.y/delta.y)-0.5);
561     }
562   (void) CloseBlob(image);
563   if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0))
564     {
565       size_t
566         swap;
567
568       swap=page.width;
569       page.width=page.height;
570       page.height=swap;
571     }
572   if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)
573     cmyk=MagickFalse;
574   /*
575     Create Ghostscript control file.
576   */
577   file=AcquireUniqueFileResource(postscript_filename);
578   if (file == -1)
579     {
580       ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile",
581         image_info->filename);
582       image=DestroyImage(image);
583       return((Image *) NULL);
584     }
585   count=write(file," ",1);
586   file=close(file)-1;
587   /*
588     Render Postscript with the Ghostscript delegate.
589   */
590   if ((image_info->ping != MagickFalse) ||
591       (image_info->monochrome != MagickFalse))
592     delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception);
593   else
594      if (cmyk != MagickFalse)
595        delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception);
596      else
597        delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception);
598   if (delegate_info == (const DelegateInfo *) NULL)
599     {
600       (void) RelinquishUniqueFileResource(postscript_filename);
601       image=DestroyImage(image);
602       return((Image *) NULL);
603     }
604   *options='\0';
605   (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",image->resolution.x,
606     image->resolution.y);
607   if (image_info->page != (char *) NULL)
608     (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double)
609        page.width,(double) page.height);
610   if (cmyk != MagickFalse)
611     (void) ConcatenateMagickString(options,"-dUseCIEColor ",MaxTextExtent);
612   if (cropbox != MagickFalse)
613     (void) ConcatenateMagickString(options,"-dUseCropBox ",MaxTextExtent);
614   if (trimbox != MagickFalse)
615     (void) ConcatenateMagickString(options,"-dUseTrimBox ",MaxTextExtent);
616   read_info=CloneImageInfo(image_info);
617   *read_info->magick='\0';
618   if (read_info->number_scenes != 0)
619     {
620       char
621         pages[MaxTextExtent];
622
623       (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g "
624         "-dLastPage=%.20g",(double) read_info->scene+1,(double)
625         (read_info->scene+read_info->number_scenes));
626       (void) ConcatenateMagickString(options,pages,MaxTextExtent);
627       read_info->number_scenes=0;
628       if (read_info->scenes != (char *) NULL)
629         *read_info->scenes='\0';
630     }
631   option=GetImageOption(read_info,"authenticate");
632   if (option != (const char *) NULL)
633     (void) FormatLocaleString(options+strlen(options),MaxTextExtent,
634       " -sPCLPassword=%s",option);
635   (void) CopyMagickString(filename,read_info->filename,MaxTextExtent);
636   (void) AcquireUniqueFilename(filename);
637   (void) ConcatenateMagickString(filename,"-%08d",MaxTextExtent);
638   (void) FormatLocaleString(command,MaxTextExtent,
639     GetDelegateCommands(delegate_info),
640     read_info->antialias != MagickFalse ? 4 : 1,
641     read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,
642     postscript_filename,input_filename);
643   status=InvokePDFDelegate(read_info->verbose,command,exception);
644   (void) RelinquishUniqueFileResource(postscript_filename);
645   (void) RelinquishUniqueFileResource(input_filename);
646   pdf_image=(Image *) NULL;
647   if (status == MagickFalse)
648     for (i=1; ; i++)
649     {
650       (void) InterpretImageFilename(image_info,image,filename,(int) i,
651         read_info->filename,exception);
652       if (IsPDFRendered(read_info->filename) == MagickFalse)
653         break;
654       (void) RelinquishUniqueFileResource(read_info->filename);
655     }
656   else
657     for (i=1; ; i++)
658     {
659       (void) InterpretImageFilename(image_info,image,filename,(int) i,
660         read_info->filename,exception);
661       if (IsPDFRendered(read_info->filename) == MagickFalse)
662         break;
663       read_info->blob=NULL;
664       read_info->length=0;
665       next=ReadImage(read_info,exception);
666       (void) RelinquishUniqueFileResource(read_info->filename);
667       if (next == (Image *) NULL)
668         break;
669       AppendImageToList(&pdf_image,next);
670     }
671   read_info=DestroyImageInfo(read_info);
672   if (pdf_image == (Image *) NULL)
673     {
674       ThrowFileException(exception,DelegateError,"PostscriptDelegateFailed",
675         image_info->filename);
676       image=DestroyImage(image);
677       return((Image *) NULL);
678     }
679   if (LocaleCompare(pdf_image->magick,"BMP") == 0)
680     {
681       Image
682         *cmyk_image;
683
684       cmyk_image=ConsolidateCMYKImages(pdf_image,exception);
685       if (cmyk_image != (Image *) NULL)
686         {
687           pdf_image=DestroyImageList(pdf_image);
688           pdf_image=cmyk_image;
689         }
690     }
691   if (image_info->number_scenes != 0)
692     {
693       Image
694         *clone_image;
695
696       register ssize_t
697         i;
698
699       /*
700         Add place holder images to meet the subimage specification requirement.
701       */
702       for (i=0; i < (ssize_t) image_info->scene; i++)
703       {
704         clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception);
705         if (clone_image != (Image *) NULL)
706           PrependImageToList(&pdf_image,clone_image);
707       }
708     }
709   do
710   {
711     (void) CopyMagickString(pdf_image->filename,filename,MaxTextExtent);
712     pdf_image->page=page;
713     (void) CloneImageProfiles(pdf_image,image);
714     (void) CloneImageProperties(pdf_image,image);
715     next=SyncNextImageInList(pdf_image);
716     if (next != (Image *) NULL)
717       pdf_image=next;
718   } while (next != (Image *) NULL);
719   image=DestroyImage(image);
720   scene=0;
721   for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; )
722   {
723     next->scene=scene++;
724     next=GetNextImageInList(next);
725   }
726   return(GetFirstImageInList(pdf_image));
727 }
728 \f
729 /*
730 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
731 %                                                                             %
732 %                                                                             %
733 %                                                                             %
734 %   R e g i s t e r P D F I m a g e                                           %
735 %                                                                             %
736 %                                                                             %
737 %                                                                             %
738 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
739 %
740 %  RegisterPDFImage() adds properties for the PDF image format to
741 %  the list of supported formats.  The properties include the image format
742 %  tag, a method to read and/or write the format, whether the format
743 %  supports the saving of more than one frame to the same file or blob,
744 %  whether the format supports native in-memory I/O, and a brief
745 %  description of the format.
746 %
747 %  The format of the RegisterPDFImage method is:
748 %
749 %      size_t RegisterPDFImage(void)
750 %
751 */
752 ModuleExport size_t RegisterPDFImage(void)
753 {
754   MagickInfo
755     *entry;
756
757   entry=SetMagickInfo("AI");
758   entry->decoder=(DecodeImageHandler *) ReadPDFImage;
759   entry->encoder=(EncodeImageHandler *) WritePDFImage;
760   entry->adjoin=MagickFalse;
761   entry->blob_support=MagickFalse;
762   entry->seekable_stream=MagickTrue;
763   entry->thread_support=EncoderThreadSupport;
764   entry->description=ConstantString("Adobe Illustrator CS2");
765   entry->module=ConstantString("PDF");
766   (void) RegisterMagickInfo(entry);
767   entry=SetMagickInfo("EPDF");
768   entry->decoder=(DecodeImageHandler *) ReadPDFImage;
769   entry->encoder=(EncodeImageHandler *) WritePDFImage;
770   entry->adjoin=MagickFalse;
771   entry->blob_support=MagickFalse;
772   entry->seekable_stream=MagickTrue;
773   entry->thread_support=EncoderThreadSupport;
774   entry->description=ConstantString("Encapsulated Portable Document Format");
775   entry->module=ConstantString("PDF");
776   (void) RegisterMagickInfo(entry);
777   entry=SetMagickInfo("PDF");
778   entry->decoder=(DecodeImageHandler *) ReadPDFImage;
779   entry->encoder=(EncodeImageHandler *) WritePDFImage;
780   entry->magick=(IsImageFormatHandler *) IsPDF;
781   entry->blob_support=MagickFalse;
782   entry->seekable_stream=MagickTrue;
783   entry->thread_support=EncoderThreadSupport;
784   entry->description=ConstantString("Portable Document Format");
785   entry->module=ConstantString("PDF");
786   (void) RegisterMagickInfo(entry);
787   entry=SetMagickInfo("PDFA");
788   entry->decoder=(DecodeImageHandler *) ReadPDFImage;
789   entry->encoder=(EncodeImageHandler *) WritePDFImage;
790   entry->magick=(IsImageFormatHandler *) IsPDF;
791   entry->blob_support=MagickFalse;
792   entry->seekable_stream=MagickTrue;
793   entry->thread_support=EncoderThreadSupport;
794   entry->description=ConstantString("Portable Document Archive Format");
795   entry->module=ConstantString("PDF");
796   (void) RegisterMagickInfo(entry);
797   return(MagickImageCoderSignature);
798 }
799 \f
800 /*
801 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
802 %                                                                             %
803 %                                                                             %
804 %                                                                             %
805 %   U n r e g i s t e r P D F I m a g e                                       %
806 %                                                                             %
807 %                                                                             %
808 %                                                                             %
809 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
810 %
811 %  UnregisterPDFImage() removes format registrations made by the
812 %  PDF module from the list of supported formats.
813 %
814 %  The format of the UnregisterPDFImage method is:
815 %
816 %      UnregisterPDFImage(void)
817 %
818 */
819 ModuleExport void UnregisterPDFImage(void)
820 {
821   (void) UnregisterMagickInfo("AI");
822   (void) UnregisterMagickInfo("EPDF");
823   (void) UnregisterMagickInfo("PDF");
824   (void) UnregisterMagickInfo("PDFA");
825 }
826 \f
827 /*
828 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
829 %                                                                             %
830 %                                                                             %
831 %                                                                             %
832 %   W r i t e P D F I m a g e                                                 %
833 %                                                                             %
834 %                                                                             %
835 %                                                                             %
836 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
837 %
838 %  WritePDFImage() writes an image in the Portable Document image
839 %  format.
840 %
841 %  The format of the WritePDFImage method is:
842 %
843 %      MagickBooleanType WritePDFImage(const ImageInfo *image_info,
844 %        Image *image,ExceptionInfo *exception)
845 %
846 %  A description of each parameter follows.
847 %
848 %    o image_info: the image info.
849 %
850 %    o image:  The image.
851 %
852 %    o exception: return any errors or warnings in this structure.
853 %
854 */
855
856 static inline size_t MagickMax(const size_t x,const size_t y)
857 {
858   if (x > y)
859     return(x);
860   return(y);
861 }
862
863 static inline size_t MagickMin(const size_t x,const size_t y)
864 {
865   if (x < y)
866     return(x);
867   return(y);
868 }
869
870 static char *EscapeParenthesis(const char *text)
871 {
872   register char
873     *p;
874
875   register ssize_t
876     i;
877
878   size_t
879     escapes;
880
881   static char
882     buffer[MaxTextExtent];
883
884   escapes=0;
885   p=buffer;
886   for (i=0; i < (ssize_t) MagickMin(strlen(text),(MaxTextExtent-escapes-1)); i++)
887   {
888     if ((text[i] == '(') || (text[i] == ')'))
889       {
890         *p++='\\';
891         escapes++;
892       }
893     *p++=text[i];
894   }
895   *p='\0';
896   return(buffer);
897 }
898
899 static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,
900   Image *image,Image *inject_image,ExceptionInfo *exception)
901 {
902   Image
903     *group4_image;
904
905   ImageInfo
906     *write_info;
907
908   MagickBooleanType
909     status;
910
911   size_t
912     length;
913
914   unsigned char
915     *group4;
916
917   status=MagickTrue;
918   write_info=CloneImageInfo(image_info);
919   (void) CopyMagickString(write_info->filename,"GROUP4:",MaxTextExtent);
920   (void) CopyMagickString(write_info->magick,"GROUP4",MaxTextExtent);
921   group4_image=CloneImage(inject_image,0,0,MagickTrue,exception);
922   if (group4_image == (Image *) NULL)
923     return(MagickFalse);
924   group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,
925     exception);
926   group4_image=DestroyImage(group4_image);
927   if (group4 == (unsigned char *) NULL)
928     return(MagickFalse);
929   write_info=DestroyImageInfo(write_info);
930   if (WriteBlob(image,length,group4) != (ssize_t) length)
931     status=MagickFalse;
932   group4=(unsigned char *) RelinquishMagickMemory(group4);
933   return(status);
934 }
935
936 static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,
937   ExceptionInfo *exception)
938 {
939 #define CFormat  "/Filter [ /%s ]\n"
940 #define ObjectsPerImage  14
941
942   static const char
943     XMPProfile[]=
944     {
945       "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
946       "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n"
947       "   <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
948       "      <rdf:Description rdf:about=\"\"\n"
949       "            xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n"
950       "         <xap:ModifyDate>%s</xap:ModifyDate>\n"
951       "         <xap:CreateDate>%s</xap:CreateDate>\n"
952       "         <xap:MetadataDate>%s</xap:MetadataDate>\n"
953       "         <xap:CreatorTool>%s</xap:CreatorTool>\n"
954       "      </rdf:Description>\n"
955       "      <rdf:Description rdf:about=\"\"\n"
956       "            xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
957       "         <dc:format>application/pdf</dc:format>\n"
958       "         <dc:title>\n"
959       "           <rdf:Alt>\n"
960       "              <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n"
961       "           </rdf:Alt>\n"
962       "         </dc:title>\n"
963       "      </rdf:Description>\n"
964       "      <rdf:Description rdf:about=\"\"\n"
965       "            xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n"
966       "         <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n"
967       "         <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n"
968       "      </rdf:Description>\n"
969       "      <rdf:Description rdf:about=\"\"\n"
970       "            xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n"
971       "         <pdf:Producer>%s</pdf:Producer>\n"
972       "      </rdf:Description>\n"
973       "      <rdf:Description rdf:about=\"\"\n"
974       "            xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
975       "         <pdfaid:part>2</pdfaid:part>\n"
976       "         <pdfaid:conformance>B</pdfaid:conformance>\n"
977       "      </rdf:Description>\n"
978       "   </rdf:RDF>\n"
979       "</x:xmpmeta>\n"
980       "<?xpacket end=\"w\"?>\n"
981     },
982     XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };
983
984   char
985     basename[MaxTextExtent],
986     buffer[MaxTextExtent],
987     date[MaxTextExtent],
988     **labels,
989     page_geometry[MaxTextExtent];
990
991   CompressionType
992     compression;
993
994   const char
995     *value;
996
997   double
998     pointsize;
999
1000   GeometryInfo
1001     geometry_info;
1002
1003   Image
1004     *next,
1005     *tile_image;
1006
1007   MagickBooleanType
1008     status;
1009
1010   MagickOffsetType
1011     offset,
1012     scene,
1013     *xref;
1014
1015   MagickSizeType
1016     number_pixels;
1017
1018   MagickStatusType
1019     flags;
1020
1021   PointInfo
1022     delta,
1023     resolution,
1024     scale;
1025
1026   RectangleInfo
1027     geometry,
1028     media_info,
1029     page_info;
1030
1031   register const Quantum
1032     *p;
1033
1034   register unsigned char
1035     *q;
1036
1037   register ssize_t
1038     i,
1039     x;
1040
1041   size_t
1042     info_id,
1043     length,
1044     object,
1045     pages_id,
1046     root_id,
1047     text_size,
1048     version;
1049
1050   ssize_t
1051     count,
1052     y;
1053
1054   struct tm
1055     local_time;
1056
1057   time_t
1058     seconds;
1059
1060   unsigned char
1061     *pixels;
1062
1063   /*
1064     Open output image file.
1065   */
1066   assert(image_info != (const ImageInfo *) NULL);
1067   assert(image_info->signature == MagickSignature);
1068   assert(image != (Image *) NULL);
1069   assert(image->signature == MagickSignature);
1070   if (image->debug != MagickFalse)
1071     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1072   assert(exception != (ExceptionInfo *) NULL);
1073   assert(exception->signature == MagickSignature);
1074   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1075   if (status == MagickFalse)
1076     return(status);
1077   /*
1078     Allocate X ref memory.
1079   */
1080   xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));
1081   if (xref == (MagickOffsetType *) NULL)
1082     ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1083   (void) ResetMagickMemory(xref,0,2048UL*sizeof(*xref));
1084   /*
1085     Write Info object.
1086   */
1087   object=0;
1088   version=3;
1089   if (image_info->compression == JPEG2000Compression)
1090     version=(size_t) MagickMax(version,5);
1091   for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
1092     if (next->alpha_trait == BlendPixelTrait)
1093       version=(size_t) MagickMax(version,4);
1094   if (LocaleCompare(image_info->magick,"PDFA") == 0)
1095     version=(size_t) MagickMax(version,6);
1096   (void) FormatLocaleString(buffer,MaxTextExtent,"%%PDF-1.%.20g \n",(double)
1097     version);
1098   (void) WriteBlobString(image,buffer);
1099   if (LocaleCompare(image_info->magick,"PDFA") == 0)
1100     (void) WriteBlobString(image,"%âãÏÓ\n");
1101   /*
1102     Write Catalog object.
1103   */
1104   xref[object++]=TellBlob(image);
1105   root_id=object;
1106   (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1107     object);
1108   (void) WriteBlobString(image,buffer);
1109   (void) WriteBlobString(image,"<<\n");
1110   if (LocaleCompare(image_info->magick,"PDFA") != 0)
1111     (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double)
1112       object+1);
1113   else
1114     {
1115       (void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n",
1116         (double) object+1);
1117       (void) WriteBlobString(image,buffer);
1118       (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",
1119         (double) object+2);
1120     }
1121   (void) WriteBlobString(image,buffer);
1122   (void) WriteBlobString(image,"/Type /Catalog\n");
1123   (void) WriteBlobString(image,">>\n");
1124   (void) WriteBlobString(image,"endobj\n");
1125   GetPathComponent(image->filename,BasePath,basename);
1126   if (LocaleCompare(image_info->magick,"PDFA") == 0)
1127     {
1128       char
1129         create_date[MaxTextExtent],
1130         modify_date[MaxTextExtent],
1131         timestamp[MaxTextExtent],
1132         xmp_profile[MaxTextExtent];
1133
1134       size_t
1135         version;
1136
1137       /*
1138         Write XMP object.
1139       */
1140       xref[object++]=TellBlob(image);
1141       (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1142         object);
1143       (void) WriteBlobString(image,buffer);
1144       (void) WriteBlobString(image,"<<\n");
1145       (void) WriteBlobString(image,"/Subtype /XML\n");
1146       *modify_date='\0';
1147       value=GetImageProperty(image,"date:modify",exception);
1148       if (value != (const char *) NULL)
1149         (void) CopyMagickString(modify_date,value,MaxTextExtent);
1150       *create_date='\0';
1151       value=GetImageProperty(image,"date:create",exception);
1152       if (value != (const char *) NULL)
1153         (void) CopyMagickString(create_date,value,MaxTextExtent);
1154       (void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp);
1155       i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile,
1156         XMPProfileMagick,modify_date,create_date,timestamp,
1157         GetMagickVersion(&version),EscapeParenthesis(basename),
1158         GetMagickVersion(&version));
1159       (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g\n",(double)
1160         i);
1161       (void) WriteBlobString(image,buffer);
1162       (void) WriteBlobString(image,"/Type /Metadata\n");
1163       (void) WriteBlobString(image,">>\nstream\n");
1164       (void) WriteBlobString(image,xmp_profile);
1165       (void) WriteBlobString(image,"\nendstream\n");
1166       (void) WriteBlobString(image,"endobj\n");
1167     }
1168   /*
1169     Write Pages object.
1170   */
1171   xref[object++]=TellBlob(image);
1172   pages_id=object;
1173   (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1174     object);
1175   (void) WriteBlobString(image,buffer);
1176   (void) WriteBlobString(image,"<<\n");
1177   (void) WriteBlobString(image,"/Type /Pages\n");
1178   (void) FormatLocaleString(buffer,MaxTextExtent,"/Kids [ %.20g 0 R ",(double)
1179     object+1);
1180   (void) WriteBlobString(image,buffer);
1181   count=(ssize_t) (pages_id+ObjectsPerImage+1);
1182   if (image_info->adjoin != MagickFalse)
1183     {
1184       Image
1185         *kid_image;
1186
1187       /*
1188         Predict page object id's.
1189       */
1190       kid_image=image;
1191       for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)
1192       {
1193         (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 R ",(double)
1194           count);
1195         (void) WriteBlobString(image,buffer);
1196         kid_image=GetNextImageInList(kid_image);
1197       }
1198       xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,
1199         sizeof(*xref));
1200       if (xref == (MagickOffsetType *) NULL)
1201         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1202     }
1203   (void) WriteBlobString(image,"]\n");
1204   (void) FormatLocaleString(buffer,MaxTextExtent,"/Count %.20g\n",(double)
1205     ((count-pages_id)/ObjectsPerImage));
1206   (void) WriteBlobString(image,buffer);
1207   (void) WriteBlobString(image,">>\n");
1208   (void) WriteBlobString(image,"endobj\n");
1209   scene=0;
1210   do
1211   {
1212     compression=image->compression;
1213     if (image_info->compression != UndefinedCompression)
1214       compression=image_info->compression;
1215     switch (compression)
1216     {
1217       case FaxCompression:
1218       case Group4Compression:
1219       {
1220         if ((IsImageMonochrome(image,exception) == MagickFalse) ||
1221             (image->alpha_trait == BlendPixelTrait))
1222           compression=RLECompression;
1223         break;
1224       }
1225 #if !defined(MAGICKCORE_JPEG_DELEGATE)
1226       case JPEGCompression:
1227       {
1228         compression=RLECompression;
1229         (void) ThrowMagickException(exception,GetMagickModule(),
1230           MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)",
1231           image->filename);
1232         break;
1233       }
1234 #endif
1235 #if !defined(MAGICKCORE_JP2_DELEGATE)
1236       case JPEG2000Compression:
1237       {
1238         compression=RLECompression;
1239         (void) ThrowMagickException(exception,GetMagickModule(),
1240           MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)",
1241           image->filename);
1242         break;
1243       }
1244 #endif
1245 #if !defined(MAGICKCORE_ZLIB_DELEGATE)
1246       case ZipCompression:
1247       {
1248         compression=RLECompression;
1249         (void) ThrowMagickException(exception,GetMagickModule(),
1250           MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)",
1251           image->filename);
1252         break;
1253       }
1254 #endif
1255       case LZWCompression:
1256       {
1257         if (LocaleCompare(image_info->magick,"PDFA") == 0)
1258           compression=RLECompression;  /* LZW compression is forbidden */
1259         break;
1260       }
1261       case NoCompression:
1262       {
1263         if (LocaleCompare(image_info->magick,"PDFA") == 0)
1264           compression=RLECompression; /* ASCII 85 compression is forbidden */
1265         break;
1266       }
1267       default:
1268         break;
1269     }
1270     if (compression == JPEG2000Compression)
1271       {
1272         if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
1273           (void) TransformImageColorspace(image,sRGBColorspace,exception);
1274       }
1275     /*
1276       Scale relative to dots-per-inch.
1277     */
1278     delta.x=DefaultResolution;
1279     delta.y=DefaultResolution;
1280     resolution.x=image->resolution.x;
1281     resolution.y=image->resolution.y;
1282     if ((resolution.x == 0.0) || (resolution.y == 0.0))
1283       {
1284         flags=ParseGeometry(PSDensityGeometry,&geometry_info);
1285         resolution.x=geometry_info.rho;
1286         resolution.y=geometry_info.sigma;
1287         if ((flags & SigmaValue) == 0)
1288           resolution.y=resolution.x;
1289       }
1290     if (image_info->density != (char *) NULL)
1291       {
1292         flags=ParseGeometry(image_info->density,&geometry_info);
1293         resolution.x=geometry_info.rho;
1294         resolution.y=geometry_info.sigma;
1295         if ((flags & SigmaValue) == 0)
1296           resolution.y=resolution.x;
1297       }
1298     if (image->units == PixelsPerCentimeterResolution)
1299       {
1300         resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);
1301         resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);
1302       }
1303     SetGeometry(image,&geometry);
1304     (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g",(double)
1305       image->columns,(double) image->rows);
1306     if (image_info->page != (char *) NULL)
1307       (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent);
1308     else
1309       if ((image->page.width != 0) && (image->page.height != 0))
1310         (void) FormatLocaleString(page_geometry,MaxTextExtent,
1311           "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double)
1312           image->page.height,(double) image->page.x,(double) image->page.y);
1313       else
1314         if ((image->gravity != UndefinedGravity) &&
1315             (LocaleCompare(image_info->magick,"PDF") == 0))
1316           (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent);
1317     (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent);
1318     (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,
1319       &geometry.width,&geometry.height);
1320     scale.x=(double) (geometry.width*delta.x)/resolution.x;
1321     geometry.width=(size_t) floor(scale.x+0.5);
1322     scale.y=(double) (geometry.height*delta.y)/resolution.y;
1323     geometry.height=(size_t) floor(scale.y+0.5);
1324     (void) ParseAbsoluteGeometry(page_geometry,&media_info);
1325     (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);
1326     if (image->gravity != UndefinedGravity)
1327       {
1328         geometry.x=(-page_info.x);
1329         geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);
1330       }
1331     pointsize=12.0;
1332     if (image_info->pointsize != 0.0)
1333       pointsize=image_info->pointsize;
1334     text_size=0;
1335     value=GetImageProperty(image,"label",exception);
1336     if (value != (const char *) NULL)
1337       text_size=(size_t) (MultilineCensus(value)*pointsize+12);
1338     (void) text_size;
1339     /*
1340       Write Page object.
1341     */
1342     xref[object++]=TellBlob(image);
1343     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1344       object);
1345     (void) WriteBlobString(image,buffer);
1346     (void) WriteBlobString(image,"<<\n");
1347     (void) WriteBlobString(image,"/Type /Page\n");
1348     (void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n",
1349       (double) pages_id);
1350     (void) WriteBlobString(image,buffer);
1351     (void) WriteBlobString(image,"/Resources <<\n");
1352     labels=(char **) NULL;
1353     value=GetImageProperty(image,"label",exception);
1354     if (value != (const char *) NULL)
1355       labels=StringToList(value);
1356     if (labels != (char **) NULL)
1357       {
1358         (void) FormatLocaleString(buffer,MaxTextExtent,
1359           "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double)
1360           object+4);
1361         (void) WriteBlobString(image,buffer);
1362       }
1363     (void) FormatLocaleString(buffer,MaxTextExtent,
1364       "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double)
1365       object+5);
1366     (void) WriteBlobString(image,buffer);
1367     (void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n",
1368       (double) object+3);
1369     (void) WriteBlobString(image,buffer);
1370     (void) FormatLocaleString(buffer,MaxTextExtent,
1371       "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
1372       72.0*media_info.height/resolution.y);
1373     (void) WriteBlobString(image,buffer);
1374     (void) FormatLocaleString(buffer,MaxTextExtent,
1375       "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x,
1376       72.0*media_info.height/resolution.y);
1377     (void) WriteBlobString(image,buffer);
1378     (void) FormatLocaleString(buffer,MaxTextExtent,"/Contents %.20g 0 R\n",
1379       (double) object+1);
1380     (void) WriteBlobString(image,buffer);
1381     (void) FormatLocaleString(buffer,MaxTextExtent,"/Thumb %.20g 0 R\n",(double)
1382       object+8);
1383     (void) WriteBlobString(image,buffer);
1384     (void) WriteBlobString(image,">>\n");
1385     (void) WriteBlobString(image,"endobj\n");
1386     /*
1387       Write Contents object.
1388     */
1389     xref[object++]=TellBlob(image);
1390     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1391       object);
1392     (void) WriteBlobString(image,buffer);
1393     (void) WriteBlobString(image,"<<\n");
1394     (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
1395       (double) object+1);
1396     (void) WriteBlobString(image,buffer);
1397     (void) WriteBlobString(image,">>\n");
1398     (void) WriteBlobString(image,"stream\n");
1399     offset=TellBlob(image);
1400     (void) WriteBlobString(image,"q\n");
1401     if (labels != (char **) NULL)
1402       for (i=0; labels[i] != (char *) NULL; i++)
1403       {
1404         (void) WriteBlobString(image,"BT\n");
1405         (void) FormatLocaleString(buffer,MaxTextExtent,"/F%.20g %g Tf\n",
1406           (double) image->scene,pointsize);
1407         (void) WriteBlobString(image,buffer);
1408         (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n",
1409           (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+
1410           12));
1411         (void) WriteBlobString(image,buffer);
1412         (void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]);
1413         (void) WriteBlobString(image,buffer);
1414         (void) WriteBlobString(image,"ET\n");
1415         labels[i]=DestroyString(labels[i]);
1416       }
1417     (void) FormatLocaleString(buffer,MaxTextExtent,"%g 0 0 %g %.20g %.20g cm\n",
1418       scale.x,scale.y,(double) geometry.x,(double) geometry.y);
1419     (void) WriteBlobString(image,buffer);
1420     (void) FormatLocaleString(buffer,MaxTextExtent,"/Im%.20g Do\n",(double)
1421       image->scene);
1422     (void) WriteBlobString(image,buffer);
1423     (void) WriteBlobString(image,"Q\n");
1424     offset=TellBlob(image)-offset;
1425     (void) WriteBlobString(image,"\nendstream\n");
1426     (void) WriteBlobString(image,"endobj\n");
1427     /*
1428       Write Length object.
1429     */
1430     xref[object++]=TellBlob(image);
1431     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1432       object);
1433     (void) WriteBlobString(image,buffer);
1434     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
1435     (void) WriteBlobString(image,buffer);
1436     (void) WriteBlobString(image,"endobj\n");
1437     /*
1438       Write Procset object.
1439     */
1440     xref[object++]=TellBlob(image);
1441     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1442       object);
1443     (void) WriteBlobString(image,buffer);
1444     if ((image->storage_class == DirectClass) || (image->colors > 256))
1445       (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent);
1446     else
1447       if ((compression == FaxCompression) || (compression == Group4Compression))
1448         (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent);
1449       else
1450         (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent);
1451     (void) WriteBlobString(image,buffer);
1452     (void) WriteBlobString(image," ]\n");
1453     (void) WriteBlobString(image,"endobj\n");
1454     /*
1455       Write Font object.
1456     */
1457     xref[object++]=TellBlob(image);
1458     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1459       object);
1460     (void) WriteBlobString(image,buffer);
1461     (void) WriteBlobString(image,"<<\n");
1462     if (labels != (char **) NULL)
1463       {
1464         (void) WriteBlobString(image,"/Type /Font\n");
1465         (void) WriteBlobString(image,"/Subtype /Type1\n");
1466         (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /F%.20g\n",
1467           (double) image->scene);
1468         (void) WriteBlobString(image,buffer);
1469         (void) WriteBlobString(image,"/BaseFont /Helvetica\n");
1470         (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n");
1471         labels=(char **) RelinquishMagickMemory(labels);
1472       }
1473     (void) WriteBlobString(image,">>\n");
1474     (void) WriteBlobString(image,"endobj\n");
1475     /*
1476       Write XObject object.
1477     */
1478     xref[object++]=TellBlob(image);
1479     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1480       object);
1481     (void) WriteBlobString(image,buffer);
1482     (void) WriteBlobString(image,"<<\n");
1483     (void) WriteBlobString(image,"/Type /XObject\n");
1484     (void) WriteBlobString(image,"/Subtype /Image\n");
1485     (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Im%.20g\n",(double)
1486       image->scene);
1487     (void) WriteBlobString(image,buffer);
1488     switch (compression)
1489     {
1490       case NoCompression:
1491       {
1492         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode");
1493         break;
1494       }
1495       case JPEGCompression:
1496       {
1497         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode");
1498         if (image->colorspace != CMYKColorspace)
1499           break;
1500         (void) WriteBlobString(image,buffer);
1501         (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
1502           MaxTextExtent);
1503         break;
1504       }
1505       case JPEG2000Compression:
1506       {
1507         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode");
1508         if (image->colorspace != CMYKColorspace)
1509           break;
1510         (void) WriteBlobString(image,buffer);
1511         (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
1512           MaxTextExtent);
1513         break;
1514       }
1515       case LZWCompression:
1516       {
1517         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
1518         break;
1519       }
1520       case ZipCompression:
1521       {
1522         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode");
1523         break;
1524       }
1525       case FaxCompression:
1526       case Group4Compression:
1527       {
1528         (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
1529           MaxTextExtent);
1530         (void) WriteBlobString(image,buffer);
1531         (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << "
1532           "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
1533           (double) image->columns,(double) image->rows);
1534         break;
1535       }
1536       default:
1537       {
1538         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
1539           "RunLengthDecode");
1540         break;
1541       }
1542     }
1543     (void) WriteBlobString(image,buffer);
1544     (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
1545       image->columns);
1546     (void) WriteBlobString(image,buffer);
1547     (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double)
1548       image->rows);
1549     (void) WriteBlobString(image,buffer);
1550     (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n",
1551       (double) object+2);
1552     (void) WriteBlobString(image,buffer);
1553     (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
1554       (compression == FaxCompression) || (compression == Group4Compression) ?
1555       1 : 8);
1556     (void) WriteBlobString(image,buffer);
1557     if (image->alpha_trait == BlendPixelTrait)
1558       {
1559         (void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n",
1560           (double) object+7);
1561         (void) WriteBlobString(image,buffer);
1562       }
1563     (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
1564       (double) object+1);
1565     (void) WriteBlobString(image,buffer);
1566     (void) WriteBlobString(image,">>\n");
1567     (void) WriteBlobString(image,"stream\n");
1568     offset=TellBlob(image);
1569     number_pixels=(MagickSizeType) image->columns*image->rows;
1570     if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))
1571       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1572     if ((compression == FaxCompression) || (compression == Group4Compression) ||
1573         ((image_info->type != TrueColorType) &&
1574          (IsImageGray(image,exception) != MagickFalse)))
1575       {
1576         switch (compression)
1577         {
1578           case FaxCompression:
1579           case Group4Compression:
1580           {
1581             if (LocaleCompare(CCITTParam,"0") == 0)
1582               {
1583                 (void) HuffmanEncodeImage(image_info,image,image,exception);
1584                 break;
1585               }
1586             (void) Huffman2DEncodeImage(image_info,image,image,exception);
1587             break;
1588           }
1589           case JPEGCompression:
1590           {
1591             status=InjectImageBlob(image_info,image,image,"jpeg",exception);
1592             if (status == MagickFalse)
1593               {
1594                 (void) CloseBlob(image);
1595                 return(MagickFalse);
1596               }
1597             break;
1598           }
1599           case JPEG2000Compression:
1600           {
1601             status=InjectImageBlob(image_info,image,image,"jp2",exception);
1602             if (status == MagickFalse)
1603               {
1604                 (void) CloseBlob(image);
1605                 return(MagickFalse);
1606               }
1607             break;
1608           }
1609           case RLECompression:
1610           default:
1611           {
1612             /*
1613               Allocate pixel array.
1614             */
1615             length=(size_t) number_pixels;
1616             pixels=(unsigned char *) AcquireQuantumMemory(length,
1617               sizeof(*pixels));
1618             if (pixels == (unsigned char *) NULL)
1619               ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1620             /*
1621               Dump Runlength encoded pixels.
1622             */
1623             q=pixels;
1624             for (y=0; y < (ssize_t) image->rows; y++)
1625             {
1626               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1627               if (p == (const Quantum *) NULL)
1628                 break;
1629               for (x=0; x < (ssize_t) image->columns; x++)
1630               {
1631                 *q++=ScaleQuantumToChar(GetPixelIntensity(image,p));
1632                 p+=GetPixelChannels(image);
1633               }
1634               if (image->previous == (Image *) NULL)
1635                 {
1636                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
1637                     y,image->rows);
1638                   if (status == MagickFalse)
1639                     break;
1640                 }
1641             }
1642 #if defined(MAGICKCORE_ZLIB_DELEGATE)
1643             if (compression == ZipCompression)
1644               status=ZLIBEncodeImage(image,length,pixels,exception);
1645             else
1646 #endif
1647               if (compression == LZWCompression)
1648                 status=LZWEncodeImage(image,length,pixels,exception);
1649               else
1650                 status=PackbitsEncodeImage(image,length,pixels,exception);
1651             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1652             if (status == MagickFalse)
1653               {
1654                 (void) CloseBlob(image);
1655                 return(MagickFalse);
1656               }
1657             break;
1658           }
1659           case NoCompression:
1660           {
1661             /*
1662               Dump uncompressed PseudoColor packets.
1663             */
1664             Ascii85Initialize(image);
1665             for (y=0; y < (ssize_t) image->rows; y++)
1666             {
1667               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1668               if (p == (const Quantum *) NULL)
1669                 break;
1670               for (x=0; x < (ssize_t) image->columns; x++)
1671               {
1672                 Ascii85Encode(image,ScaleQuantumToChar(
1673                   GetPixelIntensity(image,p)));
1674                 p+=GetPixelChannels(image);
1675               }
1676               if (image->previous == (Image *) NULL)
1677                 {
1678                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
1679                     y,image->rows);
1680                   if (status == MagickFalse)
1681                     break;
1682                 }
1683             }
1684             Ascii85Flush(image);
1685             break;
1686           }
1687         }
1688       }
1689     else
1690       if ((image->storage_class == DirectClass) || (image->colors > 256) ||
1691           (compression == JPEGCompression) ||
1692           (compression == JPEG2000Compression))
1693         switch (compression)
1694         {
1695           case JPEGCompression:
1696           {
1697             status=InjectImageBlob(image_info,image,image,"jpeg",exception);
1698             if (status == MagickFalse)
1699               {
1700                 (void) CloseBlob(image);
1701                 return(MagickFalse);
1702               }
1703             break;
1704           }
1705           case JPEG2000Compression:
1706           {
1707             status=InjectImageBlob(image_info,image,image,"jp2",exception);
1708             if (status == MagickFalse)
1709               {
1710                 (void) CloseBlob(image);
1711                 return(MagickFalse);
1712               }
1713             break;
1714           }
1715           case RLECompression:
1716           default:
1717           {
1718             /*
1719               Allocate pixel array.
1720             */
1721             length=(size_t) number_pixels;
1722             pixels=(unsigned char *) AcquireQuantumMemory(length,
1723               4*sizeof(*pixels));
1724             length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;
1725             if (pixels == (unsigned char *) NULL)
1726               ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1727             /*
1728               Dump runoffset encoded pixels.
1729             */
1730             q=pixels;
1731             for (y=0; y < (ssize_t) image->rows; y++)
1732             {
1733               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1734               if (p == (const Quantum *) NULL)
1735                 break;
1736               for (x=0; x < (ssize_t) image->columns; x++)
1737               {
1738                 *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1739                 *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1740                 *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1741                 if (image->colorspace == CMYKColorspace)
1742                   *q++=ScaleQuantumToChar(GetPixelBlack(image,p));
1743                 p+=GetPixelChannels(image);
1744               }
1745               if (image->previous == (Image *) NULL)
1746                 {
1747                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
1748                     y,image->rows);
1749                   if (status == MagickFalse)
1750                     break;
1751                 }
1752             }
1753 #if defined(MAGICKCORE_ZLIB_DELEGATE)
1754             if (compression == ZipCompression)
1755               status=ZLIBEncodeImage(image,length,pixels,exception);
1756             else
1757 #endif
1758               if (compression == LZWCompression)
1759                 status=LZWEncodeImage(image,length,pixels,exception);
1760               else
1761                 status=PackbitsEncodeImage(image,length,pixels,exception);
1762             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1763             if (status == MagickFalse)
1764               {
1765                 (void) CloseBlob(image);
1766                 return(MagickFalse);
1767               }
1768             break;
1769           }
1770           case NoCompression:
1771           {
1772             /*
1773               Dump uncompressed DirectColor packets.
1774             */
1775             Ascii85Initialize(image);
1776             for (y=0; y < (ssize_t) image->rows; y++)
1777             {
1778               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1779               if (p == (const Quantum *) NULL)
1780                 break;
1781               for (x=0; x < (ssize_t) image->columns; x++)
1782               {
1783                 Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));
1784                 Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));
1785                 Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));
1786                 if (image->colorspace == CMYKColorspace)
1787                   Ascii85Encode(image,ScaleQuantumToChar(
1788                     GetPixelBlack(image,p)));
1789                 p+=GetPixelChannels(image);
1790               }
1791               if (image->previous == (Image *) NULL)
1792                 {
1793                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
1794                     y,image->rows);
1795                   if (status == MagickFalse)
1796                     break;
1797                 }
1798             }
1799             Ascii85Flush(image);
1800             break;
1801           }
1802         }
1803       else
1804         {
1805           /*
1806             Dump number of colors and colormap.
1807           */
1808           switch (compression)
1809           {
1810             case RLECompression:
1811             default:
1812             {
1813               /*
1814                 Allocate pixel array.
1815               */
1816               length=(size_t) number_pixels;
1817               pixels=(unsigned char *) AcquireQuantumMemory(length,
1818                 sizeof(*pixels));
1819               if (pixels == (unsigned char *) NULL)
1820                 ThrowWriterException(ResourceLimitError,
1821                   "MemoryAllocationFailed");
1822               /*
1823                 Dump Runlength encoded pixels.
1824               */
1825               q=pixels;
1826               for (y=0; y < (ssize_t) image->rows; y++)
1827               {
1828                 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1829                 if (p == (const Quantum *) NULL)
1830                   break;
1831                 for (x=0; x < (ssize_t) image->columns; x++)
1832                 {
1833                   *q++=(unsigned char) GetPixelIndex(image,p);
1834                   p+=GetPixelChannels(image);
1835                 }
1836                 if (image->previous == (Image *) NULL)
1837                   {
1838                     status=SetImageProgress(image,SaveImageTag,
1839                       (MagickOffsetType) y,image->rows);
1840                     if (status == MagickFalse)
1841                       break;
1842                   }
1843               }
1844 #if defined(MAGICKCORE_ZLIB_DELEGATE)
1845               if (compression == ZipCompression)
1846                 status=ZLIBEncodeImage(image,length,pixels,exception);
1847               else
1848 #endif
1849                 if (compression == LZWCompression)
1850                   status=LZWEncodeImage(image,length,pixels,exception);
1851                 else
1852                   status=PackbitsEncodeImage(image,length,pixels,exception);
1853               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
1854               if (status == MagickFalse)
1855                 {
1856                   (void) CloseBlob(image);
1857                   return(MagickFalse);
1858                 }
1859               break;
1860             }
1861             case NoCompression:
1862             {
1863               /*
1864                 Dump uncompressed PseudoColor packets.
1865               */
1866               Ascii85Initialize(image);
1867               for (y=0; y < (ssize_t) image->rows; y++)
1868               {
1869                 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1870                 if (p == (const Quantum *) NULL)
1871                   break;
1872                 for (x=0; x < (ssize_t) image->columns; x++)
1873                 {
1874                   Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));
1875                   p+=GetPixelChannels(image);
1876                 }
1877                 if (image->previous == (Image *) NULL)
1878                   {
1879                     status=SetImageProgress(image,SaveImageTag,
1880                       (MagickOffsetType) y,image->rows);
1881                     if (status == MagickFalse)
1882                       break;
1883                   }
1884               }
1885               Ascii85Flush(image);
1886               break;
1887             }
1888           }
1889         }
1890     offset=TellBlob(image)-offset;
1891     (void) WriteBlobString(image,"\nendstream\n");
1892     (void) WriteBlobString(image,"endobj\n");
1893     /*
1894       Write Length object.
1895     */
1896     xref[object++]=TellBlob(image);
1897     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1898       object);
1899     (void) WriteBlobString(image,buffer);
1900     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
1901     (void) WriteBlobString(image,buffer);
1902     (void) WriteBlobString(image,"endobj\n");
1903     /*
1904       Write Colorspace object.
1905     */
1906     xref[object++]=TellBlob(image);
1907     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1908       object);
1909     (void) WriteBlobString(image,buffer);
1910     if (image->colorspace == CMYKColorspace)
1911       (void) CopyMagickString(buffer,"/DeviceCMYK\n",MaxTextExtent);
1912     else
1913       if ((compression == FaxCompression) ||
1914           (compression == Group4Compression) ||
1915           ((image_info->type != TrueColorType) &&
1916            (IsImageGray(image,exception) != MagickFalse)))
1917           (void) CopyMagickString(buffer,"/DeviceGray\n",MaxTextExtent);
1918       else
1919         if ((image->storage_class == DirectClass) || (image->colors > 256) ||
1920             (compression == JPEGCompression) ||
1921             (compression == JPEG2000Compression))
1922           (void) CopyMagickString(buffer,"/DeviceRGB\n",MaxTextExtent);
1923         else
1924           (void) FormatLocaleString(buffer,MaxTextExtent,
1925             "[ /Indexed /DeviceRGB %.20g %.20g 0 R ]\n",(double) image->colors-
1926             1,(double) object+3);
1927     (void) WriteBlobString(image,buffer);
1928     (void) WriteBlobString(image,"endobj\n");
1929     /*
1930       Write Thumb object.
1931     */
1932     SetGeometry(image,&geometry);
1933     (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y,
1934       &geometry.width,&geometry.height);
1935     tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);
1936     if (tile_image == (Image *) NULL)
1937       return(MagickFalse);
1938     xref[object++]=TellBlob(image);
1939     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
1940       object);
1941     (void) WriteBlobString(image,buffer);
1942     (void) WriteBlobString(image,"<<\n");
1943     switch (compression)
1944     {
1945       case NoCompression:
1946       {
1947         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode");
1948         break;
1949       }
1950       case JPEGCompression:
1951       {
1952         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode");
1953         if (image->colorspace != CMYKColorspace)
1954           break;
1955         (void) WriteBlobString(image,buffer);
1956         (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
1957           MaxTextExtent);
1958         break;
1959       }
1960       case JPEG2000Compression:
1961       {
1962         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode");
1963         if (image->colorspace != CMYKColorspace)
1964           break;
1965         (void) WriteBlobString(image,buffer);
1966         (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n",
1967           MaxTextExtent);
1968         break;
1969       }
1970       case LZWCompression:
1971       {
1972         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
1973         break;
1974       }
1975       case ZipCompression:
1976       {
1977         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode");
1978         break;
1979       }
1980       case FaxCompression:
1981       case Group4Compression:
1982       {
1983         (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n",
1984           MaxTextExtent);
1985         (void) WriteBlobString(image,buffer);
1986         (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << "
1987           "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam,
1988           (double) tile_image->columns,(double) tile_image->rows);
1989         break;
1990       }
1991       default:
1992       {
1993         (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
1994           "RunLengthDecode");
1995         break;
1996       }
1997     }
1998     (void) WriteBlobString(image,buffer);
1999     (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
2000       tile_image->columns);
2001     (void) WriteBlobString(image,buffer);
2002     (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double)
2003       tile_image->rows);
2004     (void) WriteBlobString(image,buffer);
2005     (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n",
2006       (double) object-1);
2007     (void) WriteBlobString(image,buffer);
2008     (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
2009       (compression == FaxCompression) || (compression == Group4Compression) ?
2010       1 : 8);
2011     (void) WriteBlobString(image,buffer);
2012     (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
2013       (double) object+1);
2014     (void) WriteBlobString(image,buffer);
2015     (void) WriteBlobString(image,">>\n");
2016     (void) WriteBlobString(image,"stream\n");
2017     offset=TellBlob(image);
2018     number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;
2019     if ((compression == FaxCompression) ||
2020         (compression == Group4Compression) ||
2021         ((image_info->type != TrueColorType) &&
2022          (IsImageGray(tile_image,exception) != MagickFalse)))
2023       {
2024         switch (compression)
2025         {
2026           case FaxCompression:
2027           case Group4Compression:
2028           {
2029             if (LocaleCompare(CCITTParam,"0") == 0)
2030               {
2031                 (void) HuffmanEncodeImage(image_info,image,tile_image,
2032                   exception);
2033                 break;
2034               }
2035             (void) Huffman2DEncodeImage(image_info,image,tile_image,exception);
2036             break;
2037           }
2038           case JPEGCompression:
2039           {
2040             status=InjectImageBlob(image_info,image,tile_image,"jpeg",
2041               exception);
2042             if (status == MagickFalse)
2043               {
2044                 (void) CloseBlob(image);
2045                 return(MagickFalse);
2046               }
2047             break;
2048           }
2049           case JPEG2000Compression:
2050           {
2051             status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
2052             if (status == MagickFalse)
2053               {
2054                 (void) CloseBlob(image);
2055                 return(MagickFalse);
2056               }
2057             break;
2058           }
2059           case RLECompression:
2060           default:
2061           {
2062             /*
2063               Allocate pixel array.
2064             */
2065             length=(size_t) number_pixels;
2066             pixels=(unsigned char *) AcquireQuantumMemory(length,
2067               sizeof(*pixels));
2068             if (pixels == (unsigned char *) NULL)
2069               {
2070                 tile_image=DestroyImage(tile_image);
2071                 ThrowWriterException(ResourceLimitError,
2072                   "MemoryAllocationFailed");
2073               }
2074             /*
2075               Dump Runlength encoded pixels.
2076             */
2077             q=pixels;
2078             for (y=0; y < (ssize_t) tile_image->rows; y++)
2079             {
2080               p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
2081                 exception);
2082               if (p == (const Quantum *) NULL)
2083                 break;
2084               for (x=0; x < (ssize_t) tile_image->columns; x++)
2085               {
2086                 *q++=ScaleQuantumToChar(GetPixelIntensity(tile_image,p));
2087                 p+=GetPixelChannels(tile_image);
2088               }
2089             }
2090 #if defined(MAGICKCORE_ZLIB_DELEGATE)
2091             if (compression == ZipCompression)
2092               status=ZLIBEncodeImage(image,length,pixels,exception);
2093             else
2094 #endif
2095               if (compression == LZWCompression)
2096                 status=LZWEncodeImage(image,length,pixels,exception);
2097               else
2098                 status=PackbitsEncodeImage(image,length,pixels,exception);
2099             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
2100             if (status == MagickFalse)
2101               {
2102                 (void) CloseBlob(image);
2103                 return(MagickFalse);
2104               }
2105             break;
2106           }
2107           case NoCompression:
2108           {
2109             /*
2110               Dump uncompressed PseudoColor packets.
2111             */
2112             Ascii85Initialize(image);
2113             for (y=0; y < (ssize_t) tile_image->rows; y++)
2114             {
2115               p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
2116                 exception);
2117               if (p == (const Quantum *) NULL)
2118                 break;
2119               for (x=0; x < (ssize_t) tile_image->columns; x++)
2120               {
2121                 Ascii85Encode(image,
2122                   ScaleQuantumToChar(GetPixelIntensity(tile_image,p)));
2123                 p+=GetPixelChannels(tile_image);
2124               }
2125             }
2126             Ascii85Flush(image);
2127             break;
2128           }
2129         }
2130       }
2131     else
2132       if ((tile_image->storage_class == DirectClass) ||
2133           (tile_image->colors > 256) || (compression == JPEGCompression) ||
2134           (compression == JPEG2000Compression))
2135         switch (compression)
2136         {
2137           case JPEGCompression:
2138           {
2139             status=InjectImageBlob(image_info,image,tile_image,"jpeg",
2140               exception);
2141             if (status == MagickFalse)
2142               {
2143                 (void) CloseBlob(image);
2144                 return(MagickFalse);
2145               }
2146             break;
2147           }
2148           case JPEG2000Compression:
2149           {
2150             status=InjectImageBlob(image_info,image,tile_image,"jp2",exception);
2151             if (status == MagickFalse)
2152               {
2153                 (void) CloseBlob(image);
2154                 return(MagickFalse);
2155               }
2156             break;
2157           }
2158           case RLECompression:
2159           default:
2160           {
2161             /*
2162               Allocate pixel array.
2163             */
2164             length=(size_t) number_pixels;
2165             pixels=(unsigned char *) AcquireQuantumMemory(length,4*
2166               sizeof(*pixels));
2167             length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;
2168             if (pixels == (unsigned char *) NULL)
2169               {
2170                 tile_image=DestroyImage(tile_image);
2171                 ThrowWriterException(ResourceLimitError,
2172                   "MemoryAllocationFailed");
2173               }
2174             /*
2175               Dump runoffset encoded pixels.
2176             */
2177             q=pixels;
2178             for (y=0; y < (ssize_t) tile_image->rows; y++)
2179             {
2180               p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
2181                 exception);
2182               if (p == (const Quantum *) NULL)
2183                 break;
2184               for (x=0; x < (ssize_t) tile_image->columns; x++)
2185               {
2186                 *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));
2187                 *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));
2188                 *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));
2189                 if (image->colorspace == CMYKColorspace)
2190                   *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));
2191                 p+=GetPixelChannels(tile_image);
2192               }
2193             }
2194 #if defined(MAGICKCORE_ZLIB_DELEGATE)
2195             if (compression == ZipCompression)
2196               status=ZLIBEncodeImage(image,length,pixels,exception);
2197             else
2198 #endif
2199               if (compression == LZWCompression)
2200                 status=LZWEncodeImage(image,length,pixels,exception);
2201               else
2202                 status=PackbitsEncodeImage(image,length,pixels,exception);
2203             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
2204             if (status == MagickFalse)
2205               {
2206                 (void) CloseBlob(image);
2207                 return(MagickFalse);
2208               }
2209             break;
2210           }
2211           case NoCompression:
2212           {
2213             /*
2214               Dump uncompressed DirectColor packets.
2215             */
2216             Ascii85Initialize(image);
2217             for (y=0; y < (ssize_t) tile_image->rows; y++)
2218             {
2219               p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
2220                 exception);
2221               if (p == (const Quantum *) NULL)
2222                 break;
2223               for (x=0; x < (ssize_t) tile_image->columns; x++)
2224               {
2225                 Ascii85Encode(image,ScaleQuantumToChar(
2226                   GetPixelRed(tile_image,p)));
2227                 Ascii85Encode(image,ScaleQuantumToChar(
2228                   GetPixelGreen(tile_image,p)));
2229                 Ascii85Encode(image,ScaleQuantumToChar(
2230                   GetPixelBlue(tile_image,p)));
2231                 if (image->colorspace == CMYKColorspace)
2232                   Ascii85Encode(image,ScaleQuantumToChar(
2233                     GetPixelBlack(tile_image,p)));
2234                 p+=GetPixelChannels(tile_image);
2235               }
2236             }
2237             Ascii85Flush(image);
2238             break;
2239           }
2240         }
2241       else
2242         {
2243           /*
2244             Dump number of colors and colormap.
2245           */
2246           switch (compression)
2247           {
2248             case RLECompression:
2249             default:
2250             {
2251               /*
2252                 Allocate pixel array.
2253               */
2254               length=(size_t) number_pixels;
2255               pixels=(unsigned char *) AcquireQuantumMemory(length,
2256                 sizeof(*pixels));
2257               if (pixels == (unsigned char *) NULL)
2258                 {
2259                   tile_image=DestroyImage(tile_image);
2260                   ThrowWriterException(ResourceLimitError,
2261                     "MemoryAllocationFailed");
2262                 }
2263               /*
2264                 Dump Runlength encoded pixels.
2265               */
2266               q=pixels;
2267               for (y=0; y < (ssize_t) tile_image->rows; y++)
2268               {
2269                 p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
2270                   exception);
2271                 if (p == (const Quantum *) NULL)
2272                   break;
2273                 for (x=0; x < (ssize_t) tile_image->columns; x++)
2274                 {
2275                   *q++=(unsigned char) GetPixelIndex(tile_image,p);
2276                   p+=GetPixelChannels(tile_image);
2277                 }
2278               }
2279 #if defined(MAGICKCORE_ZLIB_DELEGATE)
2280               if (compression == ZipCompression)
2281                 status=ZLIBEncodeImage(image,length,pixels,exception);
2282               else
2283 #endif
2284                 if (compression == LZWCompression)
2285                   status=LZWEncodeImage(image,length,pixels,exception);
2286                 else
2287                   status=PackbitsEncodeImage(image,length,pixels,exception);
2288               pixels=(unsigned char *) RelinquishMagickMemory(pixels);
2289               if (status == MagickFalse)
2290                 {
2291                   (void) CloseBlob(image);
2292                   return(MagickFalse);
2293                 }
2294               break;
2295             }
2296             case NoCompression:
2297             {
2298               /*
2299                 Dump uncompressed PseudoColor packets.
2300               */
2301               Ascii85Initialize(image);
2302               for (y=0; y < (ssize_t) tile_image->rows; y++)
2303               {
2304                 p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,
2305                   exception);
2306                 if (p == (const Quantum *) NULL)
2307                   break;
2308                 for (x=0; x < (ssize_t) tile_image->columns; x++)
2309                 {
2310                   Ascii85Encode(image,(unsigned char)
2311                     GetPixelIndex(tile_image,p));
2312                   p+=GetPixelChannels(image);
2313                 }
2314               }
2315               Ascii85Flush(image);
2316               break;
2317             }
2318           }
2319         }
2320     tile_image=DestroyImage(tile_image);
2321     offset=TellBlob(image)-offset;
2322     (void) WriteBlobString(image,"\nendstream\n");
2323     (void) WriteBlobString(image,"endobj\n");
2324     /*
2325       Write Length object.
2326     */
2327     xref[object++]=TellBlob(image);
2328     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
2329       object);
2330     (void) WriteBlobString(image,buffer);
2331     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
2332     (void) WriteBlobString(image,buffer);
2333     (void) WriteBlobString(image,"endobj\n");
2334     xref[object++]=TellBlob(image);
2335     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
2336       object);
2337     (void) WriteBlobString(image,buffer);
2338     if ((image->storage_class != DirectClass) && (image->colors <= 256) &&
2339         (compression != FaxCompression) && (compression != Group4Compression))
2340       {
2341         /*
2342           Write Colormap object.
2343         */
2344         (void) WriteBlobString(image,"<<\n");
2345         if (compression == NoCompression)
2346           (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n");
2347         (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
2348           (double) object+1);
2349         (void) WriteBlobString(image,buffer);
2350         (void) WriteBlobString(image,">>\n");
2351         (void) WriteBlobString(image,"stream\n");
2352         offset=TellBlob(image);
2353         if (compression == NoCompression)
2354           Ascii85Initialize(image);
2355         for (i=0; i < (ssize_t) image->colors; i++)
2356         {
2357           if (compression == NoCompression)
2358             {
2359               Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].red));
2360               Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green));
2361               Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue));
2362               continue;
2363             }
2364           (void) WriteBlobByte(image,
2365             ScaleQuantumToChar(image->colormap[i].red));
2366           (void) WriteBlobByte(image,
2367             ScaleQuantumToChar(image->colormap[i].green));
2368           (void) WriteBlobByte(image,
2369             ScaleQuantumToChar(image->colormap[i].blue));
2370         }
2371         if (compression == NoCompression)
2372           Ascii85Flush(image);
2373        offset=TellBlob(image)-offset;
2374        (void) WriteBlobString(image,"\nendstream\n");
2375       }
2376     (void) WriteBlobString(image,"endobj\n");
2377     /*
2378       Write Length object.
2379     */
2380     xref[object++]=TellBlob(image);
2381     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
2382       object);
2383     (void) WriteBlobString(image,buffer);
2384     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double)
2385       offset);
2386     (void) WriteBlobString(image,buffer);
2387     (void) WriteBlobString(image,"endobj\n");
2388     /*
2389       Write softmask object.
2390     */
2391     xref[object++]=TellBlob(image);
2392     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
2393       object);
2394     (void) WriteBlobString(image,buffer);
2395     (void) WriteBlobString(image,"<<\n");
2396     if (image->alpha_trait != BlendPixelTrait)
2397       (void) WriteBlobString(image,">>\n");
2398     else
2399       {
2400         (void) WriteBlobString(image,"/Type /XObject\n");
2401         (void) WriteBlobString(image,"/Subtype /Image\n");
2402         (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n",
2403           (double) image->scene);
2404         (void) WriteBlobString(image,buffer);
2405         switch (compression)
2406         {
2407           case NoCompression:
2408           {
2409             (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
2410               "ASCII85Decode");
2411             break;
2412           }
2413           case LZWCompression:
2414           {
2415             (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode");
2416             break;
2417           }
2418           case ZipCompression:
2419           {
2420             (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
2421               "FlateDecode");
2422             break;
2423           }
2424           default:
2425           {
2426             (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,
2427               "RunLengthDecode");
2428             break;
2429           }
2430         }
2431         (void) WriteBlobString(image,buffer);
2432         (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double)
2433           image->columns);
2434         (void) WriteBlobString(image,buffer);
2435         (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",
2436           (double) image->rows);
2437         (void) WriteBlobString(image,buffer);
2438         (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n");
2439         (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n",
2440           (compression == FaxCompression) || (compression == Group4Compression)
2441           ? 1 : 8);
2442         (void) WriteBlobString(image,buffer);
2443         (void) FormatLocaleString(buffer,MaxTextExtent,"/Length %.20g 0 R\n",
2444           (double) object+1);
2445         (void) WriteBlobString(image,buffer);
2446         (void) WriteBlobString(image,">>\n");
2447         (void) WriteBlobString(image,"stream\n");
2448         offset=TellBlob(image);
2449         number_pixels=(MagickSizeType) image->columns*image->rows;
2450         switch (compression)
2451         {
2452           case RLECompression:
2453           default:
2454           {
2455             /*
2456               Allocate pixel array.
2457             */
2458             length=(size_t) number_pixels;
2459             pixels=(unsigned char *) AcquireQuantumMemory(length,
2460               sizeof(*pixels));
2461             if (pixels == (unsigned char *) NULL)
2462               {
2463                 image=DestroyImage(image);
2464                 ThrowWriterException(ResourceLimitError,
2465                   "MemoryAllocationFailed");
2466               }
2467             /*
2468               Dump Runlength encoded pixels.
2469             */
2470             q=pixels;
2471             for (y=0; y < (ssize_t) image->rows; y++)
2472             {
2473               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
2474               if (p == (const Quantum *) NULL)
2475                 break;
2476               for (x=0; x < (ssize_t) image->columns; x++)
2477               {
2478                 *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
2479                 p+=GetPixelChannels(image);
2480               }
2481             }
2482 #if defined(MAGICKCORE_ZLIB_DELEGATE)
2483             if (compression == ZipCompression)
2484               status=ZLIBEncodeImage(image,length,pixels,exception);
2485             else
2486 #endif
2487               if (compression == LZWCompression)
2488                 status=LZWEncodeImage(image,length,pixels,exception);
2489               else
2490                 status=PackbitsEncodeImage(image,length,pixels,exception);
2491             pixels=(unsigned char *) RelinquishMagickMemory(pixels);
2492             if (status == MagickFalse)
2493               {
2494                 (void) CloseBlob(image);
2495                 return(MagickFalse);
2496               }
2497             break;
2498           }
2499           case NoCompression:
2500           {
2501             /*
2502               Dump uncompressed PseudoColor packets.
2503             */
2504             Ascii85Initialize(image);
2505             for (y=0; y < (ssize_t) image->rows; y++)
2506             {
2507               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
2508               if (p == (const Quantum *) NULL)
2509                 break;
2510               for (x=0; x < (ssize_t) image->columns; x++)
2511               {
2512                 Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));
2513                 p+=GetPixelChannels(image);
2514               }
2515             }
2516             Ascii85Flush(image);
2517             break;
2518           }
2519         }
2520         offset=TellBlob(image)-offset;
2521         (void) WriteBlobString(image,"\nendstream\n");
2522       }
2523     (void) WriteBlobString(image,"endobj\n");
2524     /*
2525       Write Length object.
2526     */
2527     xref[object++]=TellBlob(image);
2528     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
2529       object);
2530     (void) WriteBlobString(image,buffer);
2531     (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
2532     (void) WriteBlobString(image,buffer);
2533     (void) WriteBlobString(image,"endobj\n");
2534     if (GetNextImageInList(image) == (Image *) NULL)
2535       break;
2536     image=SyncNextImageInList(image);
2537     status=SetImageProgress(image,SaveImagesTag,scene++,
2538       GetImageListLength(image));
2539     if (status == MagickFalse)
2540       break;
2541   } while (image_info->adjoin != MagickFalse);
2542   /*
2543     Write Metadata object.
2544   */
2545   xref[object++]=TellBlob(image);
2546   info_id=object;
2547   (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double)
2548     object);
2549   (void) WriteBlobString(image,buffer);
2550   (void) WriteBlobString(image,"<<\n");
2551   (void) FormatLocaleString(buffer,MaxTextExtent,"/Title (%s)\n",
2552     EscapeParenthesis(basename));
2553   (void) WriteBlobString(image,buffer);
2554   seconds=time((time_t *) NULL);
2555 #if defined(MAGICKCORE_HAVE_LOCALTIME_R)
2556   (void) localtime_r(&seconds,&local_time);
2557 #else
2558   (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));
2559 #endif
2560   (void) FormatLocaleString(date,MaxTextExtent,"D:%04d%02d%02d%02d%02d%02d",
2561     local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,
2562     local_time.tm_hour,local_time.tm_min,local_time.tm_sec);
2563   (void) FormatLocaleString(buffer,MaxTextExtent,"/CreationDate (%s)\n",date);
2564   (void) WriteBlobString(image,buffer);
2565   (void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date);
2566   (void) WriteBlobString(image,buffer);
2567   (void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",
2568     EscapeParenthesis(GetMagickVersion((size_t *) NULL)));
2569   (void) WriteBlobString(image,buffer);
2570   (void) WriteBlobString(image,">>\n");
2571   (void) WriteBlobString(image,"endobj\n");
2572   /*
2573     Write Xref object.
2574   */
2575   offset=TellBlob(image)-xref[0]+
2576    (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10;
2577   (void) WriteBlobString(image,"xref\n");
2578   (void) FormatLocaleString(buffer,MaxTextExtent,"0 %.20g\n",(double)
2579     object+1);
2580   (void) WriteBlobString(image,buffer);
2581   (void) WriteBlobString(image,"0000000000 65535 f \n");
2582   for (i=0; i < (ssize_t) object; i++)
2583   {
2584     (void) FormatLocaleString(buffer,MaxTextExtent,"%010lu 00000 n \n",
2585       (unsigned long) xref[i]);
2586     (void) WriteBlobString(image,buffer);
2587   }
2588   (void) WriteBlobString(image,"trailer\n");
2589   (void) WriteBlobString(image,"<<\n");
2590   (void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double)
2591     object+1);
2592   (void) WriteBlobString(image,buffer);
2593   (void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double)
2594     info_id);
2595   (void) WriteBlobString(image,buffer);
2596   (void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double)
2597     root_id);
2598   (void) WriteBlobString(image,buffer);
2599   (void) SignatureImage(image,exception);
2600   (void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n",
2601     GetImageProperty(image,"signature",exception),
2602     GetImageProperty(image,"signature",exception));
2603   (void) WriteBlobString(image,buffer);
2604   (void) WriteBlobString(image,">>\n");
2605   (void) WriteBlobString(image,"startxref\n");
2606   (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset);
2607   (void) WriteBlobString(image,buffer);
2608   (void) WriteBlobString(image,"%%EOF\n");
2609   xref=(MagickOffsetType *) RelinquishMagickMemory(xref);
2610   (void) CloseBlob(image);
2611   return(MagickTrue);
2612 }