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