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