/// <summary>
 /// Sometimes, tags are desired to be connected with the content that resides not in the page's content stream,
 /// but rather in the some appearance stream or in the form xObject stream.
 /// </summary>
 /// <remarks>
 /// Sometimes, tags are desired to be connected with the content that resides not in the page's content stream,
 /// but rather in the some appearance stream or in the form xObject stream. In that case, to have a valid tag structure,
 /// one shall set not only the page, on which the content will be rendered, but also the content stream in which
 /// the tagged content will reside.
 /// <br /><br />
 /// NOTE: It's important to set a
 /// <see langword="null"/>
 /// for this value, when tagging of this stream content is finished.
 /// </remarks>
 /// <param name="contentStream">
 /// the content stream which content will be tagged with this instance of
 /// <c>TagTreePointer</c>
 /// or
 /// <see langword="null"/>
 /// if content stream tagging is finished.
 /// </param>
 public virtual iText.Kernel.Pdf.Tagutils.TagTreePointer SetContentStreamForTagging(PdfStream contentStream
                                                                                    )
 {
     this.contentStream = contentStream;
     return(this);
 }
Пример #2
0
 /// <summary>Embed a file to a PdfDocument.</summary>
 /// <param name="doc"/>
 /// <param name="stream"/>
 /// <param name="fileDisplay"/>
 /// <param name="afRelationshipValue"/>
 private static iText.Kernel.Pdf.Filespec.PdfFileSpec CreateEmbeddedFileSpec(PdfDocument doc, PdfStream stream
                                                                             , String description, String fileDisplay, PdfName afRelationshipValue)
 {
     return(CreateEmbeddedFileSpec(doc, stream, description, fileDisplay, null, afRelationshipValue));
 }
Пример #3
0
    /// <summary>
    /// Creates the keys for a JPEG image.
    /// </summary>
    void InitializeJpeg()
    {
      // PDF support JPEG, so there's not much to be done
      MemoryStream memory = new MemoryStream();
      image.gdiImage.Save(memory, ImageFormat.Jpeg);
      //PixelFormat pf = image.gdiImage.PixelFormat;
      //pf.GetType();
      
      int streamLength = (int)memory.Length;
      byte[] imageBits = new byte[streamLength];
      memory.Seek(0, SeekOrigin.Begin);
      memory.Read(imageBits, 0, streamLength);
      memory.Close();

      Stream = new PdfStream(imageBits, this);

      Elements[Keys.Length]           = new PdfInteger(streamLength);
      Elements[Keys.Filter]           = new PdfName("/DCTDecode");
      Elements[Keys.Width]            = new PdfInteger(image.Width);
      Elements[Keys.Height]           = new PdfInteger(image.Height);
      Elements[Keys.BitsPerComponent] = new PdfInteger(8);
      Elements[Keys.ColorSpace]       = new PdfName("/DeviceRGB");

      //Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]");  // Invert colors? Why??
      //Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");     // CMYK
    }
Пример #4
0
 public Type4(PdfStream pdfObject)
     : base(pdfObject)
 {
 }
 /// <summary>Creates a new Sound annotation.</summary>
 /// <remarks>
 /// Creates a new Sound annotation.
 /// There is a problem playing *.wav files via internal player in Acrobat.
 /// The first byte of the audio stream data should be deleted, then wav file will be played correctly.
 /// Otherwise it will be broken. Other supporting file types don't have such problem.
 /// Sound annotations are deprecated in PDF 2.0.
 /// </remarks>
 /// <param name="rect">the rectangle that specifies annotation position and bounds on page</param>
 /// <param name="sound">
 /// the
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// with sound
 /// </param>
 public PdfSoundAnnotation(Rectangle rect, PdfStream sound)
     : base(rect)
 {
     Put(PdfName.Sound, sound);
 }
Пример #6
0
 public void HandleXObject(PdfContentStreamProcessor processor, PdfStream xobjectStream, PdfIndirectReference refi) {
     PdfDictionary colorSpaceDic = processor.resources.GetAsDict(PdfName.COLORSPACE);
     ImageRenderInfo renderInfo = ImageRenderInfo.CreateForXObject(processor.Gs().ctm, refi, colorSpaceDic);
     processor.renderListener.RenderImage(renderInfo);
 }
Пример #7
0
        private void CreateTrueColorMemoryBitmap(int components, int bits, bool hasAlpha)
        {
            int pdfVersion = Owner.Version;
            FlateDecode fd = new FlateDecode();
            ImageDataBitmap idb = (ImageDataBitmap)_image._importedImage.ImageData;
            ImageInformation ii = _image._importedImage.Information;
            bool hasMask = idb.AlphaMaskLength > 0 || idb.BitmapMaskLength > 0;
            bool hasAlphaMask = idb.AlphaMaskLength > 0;

            if (hasMask)
            {
                // monochrome mask is either sufficient or
                // provided for compatibility with older reader versions
                byte[] maskDataCompressed = fd.Encode(idb.BitmapMask, _document.Options.FlateEncodeMode);
                PdfDictionary pdfMask = new PdfDictionary(_document);
                pdfMask.Elements.SetName(Keys.Type, "/XObject");
                pdfMask.Elements.SetName(Keys.Subtype, "/Image");

                Owner._irefTable.Add(pdfMask);
                pdfMask.Stream = new PdfStream(maskDataCompressed, pdfMask);
                pdfMask.Elements[PdfStream.Keys.Length] = new PdfInteger(maskDataCompressed.Length);
                pdfMask.Elements[PdfStream.Keys.Filter] = new PdfName("/FlateDecode");
                pdfMask.Elements[Keys.Width] = new PdfInteger((int)ii.Width);
                pdfMask.Elements[Keys.Height] = new PdfInteger((int)ii.Height);
                pdfMask.Elements[Keys.BitsPerComponent] = new PdfInteger(1);
                pdfMask.Elements[Keys.ImageMask] = new PdfBoolean(true);
                Elements[Keys.Mask] = pdfMask.Reference;
            }
            if (hasMask && hasAlphaMask && pdfVersion >= 14)
            {
                // The image provides an alpha mask (requires Arcrobat 5.0 or higher)
                byte[] alphaMaskCompressed = fd.Encode(idb.AlphaMask, _document.Options.FlateEncodeMode);
                PdfDictionary smask = new PdfDictionary(_document);
                smask.Elements.SetName(Keys.Type, "/XObject");
                smask.Elements.SetName(Keys.Subtype, "/Image");

                Owner._irefTable.Add(smask);
                smask.Stream = new PdfStream(alphaMaskCompressed, smask);
                smask.Elements[PdfStream.Keys.Length] = new PdfInteger(alphaMaskCompressed.Length);
                smask.Elements[PdfStream.Keys.Filter] = new PdfName("/FlateDecode");
                smask.Elements[Keys.Width] = new PdfInteger((int)ii.Width);
                smask.Elements[Keys.Height] = new PdfInteger((int)ii.Height);
                smask.Elements[Keys.BitsPerComponent] = new PdfInteger(8);
                smask.Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
                Elements[Keys.SMask] = smask.Reference;
            }

            byte[] imageDataCompressed = fd.Encode(idb.Data, _document.Options.FlateEncodeMode);

            Stream = new PdfStream(imageDataCompressed, this);
            Elements[PdfStream.Keys.Length] = new PdfInteger(imageDataCompressed.Length);
            Elements[PdfStream.Keys.Filter] = new PdfName("/FlateDecode");
            Elements[Keys.Width] = new PdfInteger((int)ii.Width);
            Elements[Keys.Height] = new PdfInteger((int)ii.Height);
            Elements[Keys.BitsPerComponent] = new PdfInteger(8);
            // TODO: CMYK
            Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
            if (_image.Interpolate)
                Elements[Keys.Interpolate] = PdfBoolean.True;
        }
Пример #8
0
    /* BITMAPINFOHEADER struct and byte offsets:
        typedef struct tagBITMAPINFOHEADER{
          DWORD  biSize;           // 14
          LONG   biWidth;          // 18
          LONG   biHeight;         // 22
          WORD   biPlanes;         // 26
          WORD   biBitCount;       // 28
          DWORD  biCompression;    // 30
          DWORD  biSizeImage;      // 34
          LONG   biXPelsPerMeter;  // 38
          LONG   biYPelsPerMeter;  // 42
          DWORD  biClrUsed;        // 46
          DWORD  biClrImportant;   // 50
        } BITMAPINFOHEADER, *PBITMAPINFOHEADER; 
    */

    private void ReadIndexedMemoryBitmap(int bits/*, ref bool hasAlpha*/)
    {
#if DEBUG_
      image.image.Save("$$$.bmp", ImageFormat.Bmp);
#endif
      int pdfVersion = Owner.Version;
      int firstMaskColor = -1, lastMaskColor = -1;
      bool segmentedColorMask = false;

      MemoryStream memory = new MemoryStream();
#if GDI
      image.gdiImage.Save(memory, ImageFormat.Bmp);
#endif
#if WPF
#if !SILVERLIGHT
      // WPFTHHO: StL: keine Ahnung ob das so stimmt.
      BmpBitmapEncoder encoder = new BmpBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(image.wpfImage));
      encoder.Save(memory);
#else
      // AGHACK
#endif
#endif
      int streamLength = (int)memory.Length;
      Debug.Assert(streamLength > 0, "Bitmap image encoding failed.");
      if (streamLength > 0)
      {
        byte[] imageBits = new byte[streamLength];
        memory.Seek(0, SeekOrigin.Begin);
        memory.Read(imageBits, 0, streamLength);
        memory.Close();

        int height = image.PixelHeight;
        int width = image.PixelWidth;

        if (ReadWord(imageBits, 0) != 0x4d42 || // "BM"
          ReadDWord(imageBits, 2) != streamLength ||
          ReadDWord(imageBits, 14) != 40 || // sizeof BITMAPINFOHEADER
#if WPF
          // TODOWPF: bug with height and width??? With which files???
          ReadDWord(imageBits, 18) != width ||
          ReadDWord(imageBits, 22) != height)
#else
          ReadDWord(imageBits, 18) != width ||
          ReadDWord(imageBits, 22) != height)
#endif
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format");
        }
#if WPF
        // TODOWPF: bug with height and width
        width = ReadDWord(imageBits, 18);
        height = ReadDWord(imageBits, 22);
#endif
        int fileBits = ReadWord(imageBits, 28);
        if (fileBits != bits)
        {
          if (fileBits == 1 || fileBits == 4 || fileBits == 8)
            bits = fileBits;
        }

        if (ReadWord(imageBits, 26) != 1 ||
            ReadWord(imageBits, 28) != bits ||
            ReadDWord(imageBits, 30) != 0)
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #2");
        }

        int bytesFileOffset = ReadDWord(imageBits, 10);
        int bytesColorPaletteOffset = 0x36; // GDI+ always returns Windows bitmaps: sizeof BITMAPFILEHEADER + sizeof BITMAPINFOHEADER
        int paletteColors = ReadDWord(imageBits, 46);
        if ((bytesFileOffset - bytesColorPaletteOffset) / 4 != paletteColors)
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #3");
        }

        MonochromeMask mask = new MonochromeMask(width, height);

        bool isGray = bits == 8 && (paletteColors == 256 || paletteColors == 0);
        int isBitonal = 0; // 0: false; >0: true; <0: true (inverted)
        byte[] paletteData = new byte[3 * paletteColors];
        for (int color = 0; color < paletteColors; ++color)
        {
          paletteData[3 * color] = imageBits[bytesColorPaletteOffset + 4 * color + 2];
          paletteData[3 * color + 1] = imageBits[bytesColorPaletteOffset + 4 * color + 1];
          paletteData[3 * color + 2] = imageBits[bytesColorPaletteOffset + 4 * color + 0];
          if (isGray)
            isGray = paletteData[3 * color] == paletteData[3 * color + 1] &&
              paletteData[3 * color] == paletteData[3 * color + 2];

          if (imageBits[bytesColorPaletteOffset + 4 * color + 3] < 128)
          {
            // We treat this as transparency:
            if (firstMaskColor == -1)
              firstMaskColor = color;
            if (lastMaskColor == -1 || lastMaskColor == color - 1)
              lastMaskColor = color;
            if (lastMaskColor != color)
              segmentedColorMask = true;
          }
          //else
          //{
          //  // We treat this as opacity:
          //}
        }

        if (bits == 1)
        {
          if (paletteColors == 0)
            isBitonal = 1;
          if (paletteColors == 2)
          {
            if (paletteData[0] == 0 &&
              paletteData[1] == 0 &&
              paletteData[2] == 0 &&
              paletteData[3] == 255 &&
              paletteData[4] == 255 &&
              paletteData[5] == 255)
              isBitonal = 1; // Black on white
            if (paletteData[5] == 0 &&
              paletteData[4] == 0 &&
              paletteData[3] == 0 &&
              paletteData[2] == 255 &&
              paletteData[1] == 255 &&
              paletteData[0] == 255)
              isBitonal = -1; // White on black
          }
        }

        // NYI: (no sample found where this was required) 
        // if (segmentedColorMask = true)
        // { ... }

        FlateDecode fd = new FlateDecode();
        PdfDictionary colorPalette = null;
        if (isBitonal == 0 && !isGray)
        {
          colorPalette = new PdfDictionary(this.document);
          byte[] packedPaletteData = paletteData.Length >= 48 ? fd.Encode(paletteData) : null; // don't compress small palettes
          if (packedPaletteData != null && packedPaletteData.Length + 20 < paletteData.Length) // +20: compensate for the overhead (estimated value)
          {
            // Create compressed color palette:
            colorPalette.CreateStream(packedPaletteData);
            colorPalette.Elements[Keys.Length] = new PdfInteger(packedPaletteData.Length);
            colorPalette.Elements[Keys.Filter] = new PdfName("/FlateDecode");
          }
          else
          {
            // Create uncompressed color palette:
            colorPalette.CreateStream(paletteData);
            colorPalette.Elements[Keys.Length] = new PdfInteger(paletteData.Length);
          }
          Owner.irefTable.Add(colorPalette);
        }

        bool isFaxEncoding = false;
        byte[] imageData = new byte[((width * bits + 7) / 8) * height];
        byte[] imageDataFax = null;
        int k = 0;


        if (bits == 1)
        {
          // TODO: flag/option?
          // We try Group 3 1D and Group 4 (2D) encoding here and keep the smaller byte array.
          //byte[] temp = new byte[imageData.Length];
          //int ccittSize = DoFaxEncoding(ref temp, imageBits, (uint)bytesFileOffset, (uint)width, (uint)height);

          // It seems that Group 3 2D encoding never beats both other encodings, therefore we don't call it here.
          //byte[] temp2D = new byte[imageData.Length];
          //uint dpiY = (uint)image.VerticalResolution;
          //uint kTmp = 0;
          //int ccittSize2D = DoFaxEncoding2D((uint)bytesFileOffset, ref temp2D, imageBits, (uint)width, (uint)height, dpiY, out kTmp);
          //k = (int) kTmp;

          byte[] tempG4 = new byte[imageData.Length];
          int ccittSizeG4 = DoFaxEncodingGroup4(ref tempG4, imageBits, (uint)bytesFileOffset, (uint)width, (uint)height);

          isFaxEncoding = /*ccittSize > 0 ||*/ ccittSizeG4 > 0;
          if (isFaxEncoding)
          {
            //if (ccittSize == 0)
            //  ccittSize = 0x7fffffff;
            if (ccittSizeG4 == 0)
              ccittSizeG4 = 0x7fffffff;
            //if (ccittSize <= ccittSizeG4)
            //{
            //  Array.Resize(ref temp, ccittSize);
            //  imageDataFax = temp;
            //  k = 0;
            //}
            //else
            {
              Array.Resize(ref tempG4, ccittSizeG4);
              imageDataFax = tempG4;
              k = -1;
            }
          }
        }

        //if (!isFaxEncoding)
        {
          int bytesOffsetRead = 0;
          if (bits == 8 || bits == 4 || bits == 1)
          {
            int bytesPerLine = (width * bits + 7) / 8;
            for (int y = 0; y < height; ++y)
            {
              mask.StartLine(y);
              int bytesOffsetWrite = (height - 1 - y) * ((width * bits + 7) / 8);
              for (int x = 0; x < bytesPerLine; ++x)
              {
                if (isGray)
                {
                  // Lookup the gray value from the palette:
                  imageData[bytesOffsetWrite] = paletteData[3 * imageBits[bytesFileOffset + bytesOffsetRead]];
                }
                else
                {
                  // Store the palette index:
                  imageData[bytesOffsetWrite] = imageBits[bytesFileOffset + bytesOffsetRead];
                }
                if (firstMaskColor != -1)
                {
                  int n = imageBits[bytesFileOffset + bytesOffsetRead];
                  if (bits == 8)
                  {
                    // TODO???: segmentedColorMask == true => bad mask NYI
                    mask.AddPel((n >= firstMaskColor) && (n <= lastMaskColor));
                  }
                  else if (bits == 4)
                  {
                    // TODO???: segmentedColorMask == true => bad mask NYI
                    int n1 = (n & 0xf0) / 16;
                    int n2 = (n & 0x0f);
                    mask.AddPel((n1 >= firstMaskColor) && (n1 <= lastMaskColor));
                    mask.AddPel((n2 >= firstMaskColor) && (n2 <= lastMaskColor));
                  }
                  else if (bits == 1)
                  {
                    // TODO???: segmentedColorMask == true => bad mask NYI
                    for (int bit = 1; bit <= 8; ++bit)
                    {
                      int n1 = (n & 0x80) / 128;
                      mask.AddPel((n1 >= firstMaskColor) && (n1 <= lastMaskColor));
                      n *= 2;
                    }
                  }
                }
                bytesOffsetRead += 1;
                bytesOffsetWrite += 1;
              }
              bytesOffsetRead = 4 * ((bytesOffsetRead + 3) / 4); // Align to 32 bit boundary
            }
          }
          else
          {
            throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #3");
          }
        }

        if (firstMaskColor != -1 &&
          lastMaskColor != -1)
        {
          // Color mask requires Reader 4.0 or higher:
          if (!segmentedColorMask && pdfVersion >= 13)
          {
            PdfArray array = new PdfArray(document);
            array.Elements.Add(new PdfInteger(firstMaskColor));
            array.Elements.Add(new PdfInteger(lastMaskColor));
            Elements[Keys.Mask] = array;
          }
          else
          {
            // Monochrome mask
            byte[] maskDataCompressed = fd.Encode(mask.MaskData);
            PdfDictionary pdfMask = new PdfDictionary(document);
            pdfMask.Elements.SetName(Keys.Type, "/XObject");
            pdfMask.Elements.SetName(Keys.Subtype, "/Image");

            this.Owner.irefTable.Add(pdfMask);
            pdfMask.Stream = new PdfStream(maskDataCompressed, pdfMask);
            pdfMask.Elements[Keys.Length] = new PdfInteger(maskDataCompressed.Length);
            pdfMask.Elements[Keys.Filter] = new PdfName("/FlateDecode");
            pdfMask.Elements[Keys.Width] = new PdfInteger(width);
            pdfMask.Elements[Keys.Height] = new PdfInteger(height);
            pdfMask.Elements[Keys.BitsPerComponent] = new PdfInteger(1);
            pdfMask.Elements[Keys.ImageMask] = new PdfBoolean(true);
            Elements[Keys.Mask] = pdfMask.Reference;
          }
        }

        byte[] imageDataCompressed = fd.Encode(imageData);
        byte[] imageDataFaxCompressed = isFaxEncoding ? fd.Encode(imageDataFax) : null;

        bool usesCcittEncoding = false;
        if (isFaxEncoding &&
          (imageDataFax.Length < imageDataCompressed.Length ||
          imageDataFaxCompressed.Length < imageDataCompressed.Length))
        {
          // /CCITTFaxDecode creates the smaller file (with or without /FlateDecode):
          usesCcittEncoding = true;

          if (imageDataFax.Length < imageDataCompressed.Length)
          {
            Stream = new PdfStream(imageDataFax, this);
            Elements[Keys.Length] = new PdfInteger(imageDataFax.Length);
            Elements[Keys.Filter] = new PdfName("/CCITTFaxDecode");
            //PdfArray array2 = new PdfArray(this.document);
            PdfDictionary dictionary = new PdfDictionary();
            if (k != 0)
              dictionary.Elements.Add("/K", new PdfInteger(k));
            if (isBitonal < 0)
              dictionary.Elements.Add("/BlackIs1", new PdfBoolean(true));
            dictionary.Elements.Add("/EndOfBlock", new PdfBoolean(false));
            dictionary.Elements.Add("/Columns", new PdfInteger(width));
            dictionary.Elements.Add("/Rows", new PdfInteger(height));
            //array2.Elements.Add(dictionary);
            Elements[Keys.DecodeParms] = dictionary; // array2;
          }
          else
          {
            Stream = new PdfStream(imageDataFaxCompressed, this);
            Elements[Keys.Length] = new PdfInteger(imageDataFaxCompressed.Length);
            PdfArray arrayFilters = new PdfArray(document);
            arrayFilters.Elements.Add(new PdfName("/FlateDecode"));
            arrayFilters.Elements.Add(new PdfName("/CCITTFaxDecode"));
            Elements[Keys.Filter] = arrayFilters;
            PdfArray arrayDecodeParms = new PdfArray(document);

            PdfDictionary dictFlateDecodeParms = new PdfDictionary();
            //dictFlateDecodeParms.Elements.Add("/Columns", new PdfInteger(1));

            PdfDictionary dictCcittFaxDecodeParms = new PdfDictionary();
            if (k != 0)
              dictCcittFaxDecodeParms.Elements.Add("/K", new PdfInteger(k));
            if (isBitonal < 0)
              dictCcittFaxDecodeParms.Elements.Add("/BlackIs1", new PdfBoolean(true));
            dictCcittFaxDecodeParms.Elements.Add("/EndOfBlock", new PdfBoolean(false));
            dictCcittFaxDecodeParms.Elements.Add("/Columns", new PdfInteger(width));
            dictCcittFaxDecodeParms.Elements.Add("/Rows", new PdfInteger(height));

            arrayDecodeParms.Elements.Add(dictFlateDecodeParms); // How to add the "null object"?
            arrayDecodeParms.Elements.Add(dictCcittFaxDecodeParms);
            Elements[Keys.DecodeParms] = arrayDecodeParms;
          }
        }
        else
        {
          // /FlateDecode creates the smaller file (or no monochrome bitmap):
          Stream = new PdfStream(imageDataCompressed, this);
          Elements[Keys.Length] = new PdfInteger(imageDataCompressed.Length);
          Elements[Keys.Filter] = new PdfName("/FlateDecode");
        }

        Elements[Keys.Width] = new PdfInteger(width);
        Elements[Keys.Height] = new PdfInteger(height);
        Elements[Keys.BitsPerComponent] = new PdfInteger(bits);
        // TODO: CMYK

        // CCITT encoding: we need color palette for isBitonal == 0
        // FlateDecode: we need color palette for isBitonal <= 0 unless we have grayscales
        if ((usesCcittEncoding && isBitonal == 0) ||
          (!usesCcittEncoding && isBitonal <= 0  && !isGray))
        {
          PdfArray arrayColorSpace = new PdfArray(document);
          arrayColorSpace.Elements.Add(new PdfName("/Indexed"));
          arrayColorSpace.Elements.Add(new PdfName("/DeviceRGB"));
          arrayColorSpace.Elements.Add(new PdfInteger(paletteColors - 1));
          // ReSharper disable PossibleNullReferenceException
          arrayColorSpace.Elements.Add(colorPalette.Reference);
          // ReSharper restore PossibleNullReferenceException
          Elements[Keys.ColorSpace] = arrayColorSpace;
        }
        else
        {
          Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
        }
        if (image.Interpolate)
          Elements[Keys.Interpolate] = PdfBoolean.True;
      }
    }
Пример #9
0
        /// <summary>
        /// Creates the keys for a JPEG image.
        /// </summary>
        void InitializeJpeg()
        {
            // PDF supports JPEG, so there's not much to be done.
            MemoryStream memory = null;
            // Close the MemoryStream if we create it.
            bool ownMemory = false;

            byte[] imageBits = null;
            int streamLength = 0;

#if CORE || GDI || WPF
            if (_image._importedImage != null)
            {
                ImageDataDct idd = (ImageDataDct)_image._importedImage.ImageData;
                imageBits = idd.Data;
                streamLength = idd.Length;
            }
#endif

#if CORE || GDI
            if (_image._importedImage == null)
            {
                if (!_image._path.StartsWith("*"))
                {
                    // Image does not come from a stream, so we have the path to the file - just use the path.
                    // If the image was modified in memory, those changes will be lost and the original image, as it was read from the file, will be added to the PDF.
                    using (FileStream sourceFile = File.OpenRead(_image._path))
                    {
                        int count;
                        byte[] buffer = new byte[8192];
                        memory = new MemoryStream((int)sourceFile.Length);
                        ownMemory = true;
                        do
                        {
                            count = sourceFile.Read(buffer, 0, buffer.Length);
                            // memory.Write(buffer, 0, buffer.Length);
                            memory.Write(buffer, 0, count);
                        } while (count > 0);
                    }
                }
                else
                {
                    memory = new MemoryStream();
                    ownMemory = true;
                    // If we have a stream, copy data from the stream.
                    if (_image._stream != null && _image._stream.CanSeek)
                    {
                        Stream stream = _image._stream;
                        stream.Seek(0, SeekOrigin.Begin);
                        byte[] buffer = new byte[32 * 1024]; // 32K buffer.
                        int bytesRead;
                        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            memory.Write(buffer, 0, bytesRead);
                        }
                    }
                    else
                    {
#if CORE_WITH_GDI
                        // No stream, no filename, get image data.
                        // Save the image to a memory stream.
                        _image._gdiImage.Save(memory, ImageFormat.Jpeg);
#endif
                    }
                }

                if ((int)memory.Length == 0)
                {
                    Debug.Assert(false, "Internal error? JPEG image, but file not found!");
                }
            }
#endif
#if WPF
            // AGHACK
            //string filename = XImage.GetImageFilename(image._wpfImage);
            //if (XImage.ReadJpegFile(filename, -1, ref imageBits))
            //{
            //  streamLength = imageBits.Length;
            //}
            //else
            //  imageBits = null;
#if !SILVERLIGHT
            memory = _image.Memory;
#else
            memory = new MemoryStream();
            ownMemory = true;
#endif
#endif
#if NETFX_CORE
            memory = new MemoryStream();
            ownMemory = true;
#endif
            // THHO4THHO Use ImageImporterJPEG here to avoid redundant code.

            if (imageBits == null)
            {
                streamLength = (int)memory.Length;
                imageBits = new byte[streamLength];
                memory.Seek(0, SeekOrigin.Begin);
                memory.Read(imageBits, 0, streamLength);
                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                if (ownMemory)
                {
#if UWP || true
                    memory.Dispose();
#else
                memory.Close();
#endif
                }
            }

            bool tryFlateDecode = _document.Options.UseFlateDecoderForJpegImages == PdfUseFlateDecoderForJpegImages.Automatic;
            bool useFlateDecode = _document.Options.UseFlateDecoderForJpegImages == PdfUseFlateDecoderForJpegImages.Always;

            FlateDecode fd = new FlateDecode();
            byte[] imageDataCompressed = (useFlateDecode || tryFlateDecode) ? fd.Encode(imageBits, _document.Options.FlateEncodeMode) : null;
            if (useFlateDecode || tryFlateDecode && imageDataCompressed.Length < imageBits.Length)
            {
                Stream = new PdfStream(imageDataCompressed, this);
                Elements[PdfStream.Keys.Length] = new PdfInteger(imageDataCompressed.Length);
                PdfArray arrayFilters = new PdfArray(_document);
                arrayFilters.Elements.Add(new PdfName("/FlateDecode"));
                arrayFilters.Elements.Add(new PdfName("/DCTDecode"));
                Elements[PdfStream.Keys.Filter] = arrayFilters;
            }
            else
            {
                Stream = new PdfStream(imageBits, this);
                Elements[PdfStream.Keys.Length] = new PdfInteger(streamLength);
                Elements[PdfStream.Keys.Filter] = new PdfName("/DCTDecode");
            }
            if (_image.Interpolate)
                Elements[Keys.Interpolate] = PdfBoolean.True;
            Elements[Keys.Width] = new PdfInteger(_image.PixelWidth);
            Elements[Keys.Height] = new PdfInteger(_image.PixelHeight);
            Elements[Keys.BitsPerComponent] = new PdfInteger(8);

#if CORE || GDI || WPF
            if (_image._importedImage != null)
            {
                if (_image._importedImage.Information.ImageFormat == ImageInformation.ImageFormats.JPEGCMYK ||
                    _image._importedImage.Information.ImageFormat == ImageInformation.ImageFormats.JPEGRGBW)
                {
                    // TODO: Test with CMYK JPEG files (so far I only found ImageFlags.ColorSpaceYcck JPEG files ...)
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
                    if (_image._importedImage.Information.ImageFormat == ImageInformation.ImageFormats.JPEGRGBW)
                        Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]"); // Invert colors from RGBW to CMYK.
                }
                else if (_image._importedImage.Information.ImageFormat == ImageInformation.ImageFormats.JPEGGRAY)
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
                }
                else
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
                }
            }
#endif
#if CORE_WITH_GDI
            if (_image._importedImage == null)
            {
                if ((_image._gdiImage.Flags & ((int)ImageFlags.ColorSpaceCmyk | (int)ImageFlags.ColorSpaceYcck)) != 0)
                {
                    // TODO: Test with CMYK JPEG files (so far I only found ImageFlags.ColorSpaceYcck JPEG files ...)
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
                    if ((_image._gdiImage.Flags & (int)ImageFlags.ColorSpaceYcck) != 0)
                        Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]"); // Invert colors? Why??
                }
                else if ((_image._gdiImage.Flags & (int)ImageFlags.ColorSpaceGray) != 0)
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
                }
                else
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
                }
            }
#endif
#if GDI
            if (_image._importedImage == null)
            {
                if ((_image._gdiImage.Flags & ((int)ImageFlags.ColorSpaceCmyk | (int)ImageFlags.ColorSpaceYcck)) != 0)
                {
                    // TODO: Test with CMYK JPEG files (so far I only found ImageFlags.ColorSpaceYcck JPEG files ...)
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
                    if ((_image._gdiImage.Flags & (int)ImageFlags.ColorSpaceYcck) != 0)
                        Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]"); // Invert colors? Why??
                }
                else if ((_image._gdiImage.Flags & (int)ImageFlags.ColorSpaceGray) != 0)
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
                }
                else
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
                }
            }
#endif
#if WPF
            // TODOSILVERLIGHT
#if !SILVERLIGHT
            string pixelFormat = _image._wpfImage.Format.ToString();
#else
            string pixelFormat = "xxx";
#endif
            bool isCmyk = _image.IsCmyk;
            bool isGrey = pixelFormat == "Gray8";
            if (isCmyk)
            {
                // TODO: Test with CMYK JPEG files (so far I only found ImageFlags.ColorSpaceYcck JPEG files ...)
                Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
                Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]");  // Invert colors? Why??
            }
            else if (isGrey)
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
            }
            else
            {
                Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
            }
#endif
        }
Пример #10
0
        private void CreateIndexedMemoryBitmap(int bits)
        {
            ImageDataBitmap idb = (ImageDataBitmap)_image._importedImage.ImageData;
            ImageInformation ii = _image._importedImage.Information;

            int pdfVersion = Owner.Version;
            int firstMaskColor = -1, lastMaskColor = -1;
            bool segmentedColorMask = idb.SegmentedColorMask;

            {

                FlateDecode fd = new FlateDecode();
                if (firstMaskColor != -1 &&
                  lastMaskColor != -1)
                {
                    // Color mask requires Reader 4.0 or higher:
                    //if (!segmentedColorMask && pdfVersion >= 13)
                    if (!segmentedColorMask && pdfVersion >= 13 && !idb.IsGray)
                    {
                        PdfArray array = new PdfArray(_document);
                        array.Elements.Add(new PdfInteger(firstMaskColor));
                        array.Elements.Add(new PdfInteger(lastMaskColor));
                        Elements[Keys.Mask] = array;
                    }
                    else
                    {
                        // Monochrome mask
                        byte[] maskDataCompressed = fd.Encode(idb.BitmapMask, _document.Options.FlateEncodeMode);
                        PdfDictionary pdfMask = new PdfDictionary(_document);
                        pdfMask.Elements.SetName(Keys.Type, "/XObject");
                        pdfMask.Elements.SetName(Keys.Subtype, "/Image");

                        Owner._irefTable.Add(pdfMask);
                        pdfMask.Stream = new PdfStream(maskDataCompressed, pdfMask);
                        pdfMask.Elements[PdfStream.Keys.Length] = new PdfInteger(maskDataCompressed.Length);
                        pdfMask.Elements[PdfStream.Keys.Filter] = new PdfName("/FlateDecode");
                        pdfMask.Elements[Keys.Width] = new PdfInteger((int)ii.Width);
                        pdfMask.Elements[Keys.Height] = new PdfInteger((int)ii.Height);
                        pdfMask.Elements[Keys.BitsPerComponent] = new PdfInteger(1);
                        pdfMask.Elements[Keys.ImageMask] = new PdfBoolean(true);
                        Elements[Keys.Mask] = pdfMask.Reference;
                    }
                }

                byte[] imageDataCompressed = fd.Encode(idb.Data, _document.Options.FlateEncodeMode);
                byte[] imageDataFaxCompressed = idb.DataFax != null ? fd.Encode(idb.DataFax, _document.Options.FlateEncodeMode) : null;

                bool usesCcittEncoding = false;
                if (idb.DataFax != null &&
                  (idb.LengthFax < imageDataCompressed.Length ||
                  imageDataFaxCompressed.Length < imageDataCompressed.Length))
                {
                    // /CCITTFaxDecode creates the smaller file (with or without /FlateDecode):
                    usesCcittEncoding = true;

                    if (idb.LengthFax < imageDataCompressed.Length)
                    {
                        Stream = new PdfStream(idb.DataFax, this);
                        Elements[PdfStream.Keys.Length] = new PdfInteger(idb.LengthFax);
                        Elements[PdfStream.Keys.Filter] = new PdfName("/CCITTFaxDecode");
                        //PdfArray array2 = new PdfArray(_document);
                        PdfDictionary dictionary = new PdfDictionary();
                        if (idb.K != 0)
                            dictionary.Elements.Add("/K", new PdfInteger(idb.K));
                        if (idb.IsBitonal < 0)
                            dictionary.Elements.Add("/BlackIs1", new PdfBoolean(true));
                        dictionary.Elements.Add("/EndOfBlock", new PdfBoolean(false));
                        dictionary.Elements.Add("/Columns", new PdfInteger((int)ii.Width));
                        dictionary.Elements.Add("/Rows", new PdfInteger((int)ii.Height));
                        //array2.Elements.Add(dictionary);
                        Elements[PdfStream.Keys.DecodeParms] = dictionary; // array2;
                    }
                    else
                    {
                        Stream = new PdfStream(imageDataFaxCompressed, this);
                        Elements[PdfStream.Keys.Length] = new PdfInteger(imageDataFaxCompressed.Length);
                        PdfArray arrayFilters = new PdfArray(_document);
                        arrayFilters.Elements.Add(new PdfName("/FlateDecode"));
                        arrayFilters.Elements.Add(new PdfName("/CCITTFaxDecode"));
                        Elements[PdfStream.Keys.Filter] = arrayFilters;
                        PdfArray arrayDecodeParms = new PdfArray(_document);

                        PdfDictionary dictFlateDecodeParms = new PdfDictionary();
                        //dictFlateDecodeParms.Elements.Add("/Columns", new PdfInteger(1));

                        PdfDictionary dictCcittFaxDecodeParms = new PdfDictionary();
                        if (idb.K != 0)
                            dictCcittFaxDecodeParms.Elements.Add("/K", new PdfInteger(idb.K));
                        if (idb.IsBitonal < 0)
                            dictCcittFaxDecodeParms.Elements.Add("/BlackIs1", new PdfBoolean(true));
                        dictCcittFaxDecodeParms.Elements.Add("/EndOfBlock", new PdfBoolean(false));
                        dictCcittFaxDecodeParms.Elements.Add("/Columns", new PdfInteger((int)ii.Width));
                        dictCcittFaxDecodeParms.Elements.Add("/Rows", new PdfInteger((int)ii.Height));

                        arrayDecodeParms.Elements.Add(dictFlateDecodeParms); // How to add the "null object"?
                        arrayDecodeParms.Elements.Add(dictCcittFaxDecodeParms);
                        Elements[PdfStream.Keys.DecodeParms] = arrayDecodeParms;
                    }
                }
                else
                {
                    // /FlateDecode creates the smaller file (or no monochrome bitmap):
                    Stream = new PdfStream(imageDataCompressed, this);
                    Elements[PdfStream.Keys.Length] = new PdfInteger(imageDataCompressed.Length);
                    Elements[PdfStream.Keys.Filter] = new PdfName("/FlateDecode");
                }

                Elements[Keys.Width] = new PdfInteger((int)ii.Width);
                Elements[Keys.Height] = new PdfInteger((int)ii.Height);
                Elements[Keys.BitsPerComponent] = new PdfInteger(bits);
                // TODO: CMYK

                // CCITT encoding: we need color palette for isBitonal == 0
                // FlateDecode: we need color palette for isBitonal <= 0 unless we have grayscales
                if ((usesCcittEncoding && idb.IsBitonal == 0) ||
                  (!usesCcittEncoding && idb.IsBitonal <= 0 && !idb.IsGray))
                {
                    PdfDictionary colorPalette = null;
                    colorPalette = new PdfDictionary(_document);
                    byte[] packedPaletteData = idb.PaletteDataLength >= 48 ? fd.Encode(idb.PaletteData, _document.Options.FlateEncodeMode) : null; // don't compress small palettes
                    if (packedPaletteData != null && packedPaletteData.Length + 20 < idb.PaletteDataLength) // +20: compensate for the overhead (estimated value)
                    {
                        // Create compressed color palette:
                        colorPalette.CreateStream(packedPaletteData);
                        colorPalette.Elements[PdfStream.Keys.Length] = new PdfInteger(packedPaletteData.Length);
                        colorPalette.Elements[PdfStream.Keys.Filter] = new PdfName("/FlateDecode");
                    }
                    else
                    {
                        // Create uncompressed color palette:
                        colorPalette.CreateStream(idb.PaletteData);
                        colorPalette.Elements[PdfStream.Keys.Length] = new PdfInteger(idb.PaletteDataLength);
                    }
                    Owner._irefTable.Add(colorPalette);

                    PdfArray arrayColorSpace = new PdfArray(_document);
                    arrayColorSpace.Elements.Add(new PdfName("/Indexed"));
                    arrayColorSpace.Elements.Add(new PdfName("/DeviceRGB"));
                    arrayColorSpace.Elements.Add(new PdfInteger((int)ii.ColorsUsed - 1));
                    arrayColorSpace.Elements.Add(colorPalette.Reference);
                    Elements[Keys.ColorSpace] = arrayColorSpace;
                }
                else
                {
                    Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
                }
                if (_image.Interpolate)
                    Elements[Keys.Interpolate] = PdfBoolean.True;
            }
        }
Пример #11
0
        private void ReadTrueColorMemoryBitmapAg(int components, int bits, bool hasAlpha)
        {
            int pdfVersion = Owner.Version;
            MemoryStream memory = new MemoryStream();

            WriteableBitmap bitmap = null;
            if (_image._wpfImage is WriteableBitmap)
                bitmap = (WriteableBitmap)_image._wpfImage;
            else if (_image._wpfImage is BitmapImage)
                bitmap = new WriteableBitmap(_image._wpfImage);

            if (bitmap != null)
            {
                int height = _image.PixelHeight;
                int width = _image.PixelWidth;

                int logicalComponents = components;
                if (components == 4)
                    logicalComponents = 3;

                byte[] imageData = new byte[components * width * height];

                bool hasMask = false;
                bool hasAlphaMask = false;
                byte[] alphaMask = hasAlpha ? new byte[width * height] : null;
                MonochromeMask mask = hasAlpha ? new MonochromeMask(width, height) : null;

                int nOffsetRead = 0;
                if (logicalComponents == 3)
                {
                    for (int y = 0; y < height; ++y)
                    {
                        int nOffsetWrite = 3 * y * width; // 3*(height - 1 - y)*width;
                        int nOffsetWriteAlpha = 0;
                        if (hasAlpha)
                        {
                            mask.StartLine(y);
                            nOffsetWriteAlpha = y * width; // (height - 1 - y) * width;
                        }

                        for (int x = 0; x < width; ++x)
                        {
                            uint pixel = (uint)bitmap.Pixels[nOffsetRead];
                            imageData[nOffsetWrite] = (byte)(pixel >> 16);
                            imageData[nOffsetWrite + 1] = (byte)(pixel >> 8);
                            imageData[nOffsetWrite + 2] = (byte)(pixel);
                            if (hasAlpha)
                            {
                                byte pel = (byte)(pixel >> 24);
                                mask.AddPel(pel);
                                alphaMask[nOffsetWriteAlpha] = pel;
                                if (!hasMask || !hasAlphaMask)
                                {
                                    if (pel != 255)
                                    {
                                        hasMask = true;
                                        if (pel != 0)
                                            hasAlphaMask = true;
                                    }
                                }
                                ++nOffsetWriteAlpha;
                            }
                            //nOffsetRead += hasAlpha ? 4 : components;
                            ++nOffsetRead;
                            nOffsetWrite += 3;
                        }
                        //nOffsetRead = 4*((nOffsetRead + 3)/4); // Align to 32 bit boundary
                    }
                }
                else if (components == 1)
                {
                    // Grayscale
                    throw new NotImplementedException("Image format not supported (grayscales).");
                }

                FlateDecode fd = new FlateDecode();
                if (hasMask)
                {
                    // monochrome mask is either sufficient or
                    // provided for compatibility with older reader versions
                    byte[] maskDataCompressed = fd.Encode(mask.MaskData, _document.Options.FlateEncodeMode);
                    PdfDictionary pdfMask = new PdfDictionary(_document);
                    pdfMask.Elements.SetName(Keys.Type, "/XObject");
                    pdfMask.Elements.SetName(Keys.Subtype, "/Image");

                    Owner._irefTable.Add(pdfMask);
                    pdfMask.Stream = new PdfStream(maskDataCompressed, pdfMask);
                    pdfMask.Elements[Keys.Length] = new PdfInteger(maskDataCompressed.Length);
                    pdfMask.Elements[Keys.Filter] = new PdfName("/FlateDecode");
                    pdfMask.Elements[Keys.Width] = new PdfInteger(width);
                    pdfMask.Elements[Keys.Height] = new PdfInteger(height);
                    pdfMask.Elements[Keys.BitsPerComponent] = new PdfInteger(1);
                    pdfMask.Elements[Keys.ImageMask] = new PdfBoolean(true);
                    Elements[Keys.Mask] = pdfMask.Reference;
                }
                if (hasMask && hasAlphaMask && pdfVersion >= 14)
                {
                    // The image provides an alpha mask (requires Arcrobat 5.0 or higher)
                    byte[] alphaMaskCompressed = fd.Encode(alphaMask, _document.Options.FlateEncodeMode);
                    PdfDictionary smask = new PdfDictionary(_document);
                    smask.Elements.SetName(Keys.Type, "/XObject");
                    smask.Elements.SetName(Keys.Subtype, "/Image");

                    Owner._irefTable.Add(smask);
                    smask.Stream = new PdfStream(alphaMaskCompressed, smask);
                    smask.Elements[Keys.Length] = new PdfInteger(alphaMaskCompressed.Length);
                    smask.Elements[Keys.Filter] = new PdfName("/FlateDecode");
                    smask.Elements[Keys.Width] = new PdfInteger(width);
                    smask.Elements[Keys.Height] = new PdfInteger(height);
                    smask.Elements[Keys.BitsPerComponent] = new PdfInteger(8);
                    smask.Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
                    Elements[Keys.SMask] = smask.Reference;
                }

                byte[] imageDataCompressed = fd.Encode(imageData, _document.Options.FlateEncodeMode);

                Stream = new PdfStream(imageDataCompressed, this);
                Elements[Keys.Length] = new PdfInteger(imageDataCompressed.Length);
                Elements[Keys.Filter] = new PdfName("/FlateDecode");
                Elements[Keys.Width] = new PdfInteger(width);
                Elements[Keys.Height] = new PdfInteger(height);
                Elements[Keys.BitsPerComponent] = new PdfInteger(8);
                // TODO: CMYK
                Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
                if (_image.Interpolate)
                    Elements[Keys.Interpolate] = PdfBoolean.True;
            }
        }
Пример #12
0
    /* BITMAPINFOHEADER struct and byte offsets:
        typedef struct tagBITMAPINFOHEADER{
          DWORD  biSize;           // 14
          LONG   biWidth;          // 18
          LONG   biHeight;         // 22
          WORD   biPlanes;         // 26
          WORD   biBitCount;       // 28
          DWORD  biCompression;    // 30
          DWORD  biSizeImage;      // 34
          LONG   biXPelsPerMeter;  // 38
          LONG   biYPelsPerMeter;  // 42
          DWORD  biClrUsed;        // 46
          DWORD  biClrImportant;   // 50
        } BITMAPINFOHEADER, *PBITMAPINFOHEADER; 
    */

    private void ReadIndexedMemoryBitmap(int bits, ref bool hasAlpha)
    {
#if DEBUG_
      image.image.Save("$$$.bmp", ImageFormat.Bmp);
#endif
      int pdfVersion = this.Owner.Version;
      int firstMaskColor = -1, lastMaskColor = -1;
      bool segmentedColorMask = false;

      MemoryStream memory = new MemoryStream();
#if GDI
      image.gdiImage.Save(memory, ImageFormat.Bmp);
#endif
#if WPF
      // WPFTHHO: StL: keine Ahnung ob das so stimmt.
      BmpBitmapEncoder encoder = new BmpBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(this.image.wpfImage));
      encoder.Save(memory);
#endif
      int streamLength = (int)memory.Length;
      Debug.Assert(streamLength > 0, "Bitmap image encoding failed.");
      if (streamLength > 0)
      {
        byte[] imageBits = new byte[streamLength];
        memory.Seek(0, SeekOrigin.Begin);
        memory.Read(imageBits, 0, streamLength);
        memory.Close();

        int height = this.image.PixelHeight;
        int width = this.image.PixelWidth;

        if (ReadWord(imageBits, 0) != 0x4d42 || // "BM"
          ReadDWord(imageBits, 2) != streamLength ||
          ReadDWord(imageBits, 14) != 40 || // sizeof BITMAPINFOHEADER
#if WPF
          // TODOWPF: bug with height and width
          false)
#else
          ReadDWord(imageBits, 18) != width ||
          ReadDWord(imageBits, 22) != height)
#endif
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format");
        }
#if WPF
        // TODOWPF: bug with height and width
        width = ReadDWord(imageBits, 18);
        height = ReadDWord(imageBits, 22);
#endif
        if (ReadWord(imageBits, 26) != 1 ||
            ReadWord(imageBits, 28) != bits ||
            ReadDWord(imageBits, 30) != 0)
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #2");
        }

        int bytesFileOffset = ReadDWord(imageBits, 10);
        int bytesColorPaletteOffset = 0x36; // GDI+ always returns Windows bitmaps: sizeof BITMAPFILEHEADER + sizeof BITMAPINFOHEADER
        int paletteColors = ReadDWord(imageBits, 46);
        if ((bytesFileOffset - bytesColorPaletteOffset) / 4 != paletteColors)
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #3");
        }

        MonochromeMask mask = new MonochromeMask(width, height);

        byte[] paletteData = new byte[3 * paletteColors];
        for (int color = 0; color < paletteColors; ++color)
        {
          paletteData[3 * color] = imageBits[bytesColorPaletteOffset + 4 * color + 2];
          paletteData[3 * color + 1] = imageBits[bytesColorPaletteOffset + 4 * color + 1];
          paletteData[3 * color + 2] = imageBits[bytesColorPaletteOffset + 4 * color + 0];
          if (imageBits[bytesColorPaletteOffset + 4 * color + 3] < 128)
          {
            // We treat this as transparency:
            if (firstMaskColor == -1)
              firstMaskColor = color;
            if (lastMaskColor == -1 || lastMaskColor == color - 1)
              lastMaskColor = color;
            if (lastMaskColor != color)
              segmentedColorMask = true;
          }
          else
          {
            // We treat this as opacity:
          }
        }

        // NYI: (no sample found where this was required) 
        // if (segmentedColorMask = true)
        // { ... }

        FlateDecode fd = new FlateDecode();
        PdfDictionary colorPalette = new PdfDictionary(this.document);
        // TODO: decide at run-time if compression makes sense
#if false
        // Create uncompressed color palette:
        colorPalette.CreateStream(paletteData);
        colorPalette.Elements[Keys.Length] = new PdfInteger(paletteData.Length);
#else
        // Create compressed color palette:
        byte[] packedPaletteData = fd.Encode(paletteData);
        colorPalette.CreateStream(packedPaletteData);
        colorPalette.Elements[Keys.Length] = new PdfInteger(packedPaletteData.Length);
        colorPalette.Elements[Keys.Filter] = new PdfName("/FlateDecode");
#endif
        this.Owner.irefTable.Add(colorPalette);

        byte[] imageData = new byte[1 * width * height];

        int bytesOffsetRead = 0;
        if (bits == 8 || bits == 4 || bits == 1)
        {
          int bytesPerLine = (width * bits + 7) / 8;
          for (int y = 0; y < height; ++y)
          {
            mask.StartLine(y);
            int bytesOffsetWrite = (height - 1 - y) * ((width * bits + 7) / 8);
            for (int x = 0; x < bytesPerLine; ++x)
            {
              imageData[bytesOffsetWrite] = imageBits[bytesFileOffset + bytesOffsetRead];
              if (firstMaskColor != -1)
              {
                int n = imageBits[bytesFileOffset + bytesOffsetRead];
                if (bits == 8)
                {
                  // TODO???: segmentedColorMask == true => falsche Maske NYI
                  mask.AddPel((n >= firstMaskColor) && (n <= lastMaskColor));
                }
                else if (bits == 4)
                {
                  // TODO???: segmentedColorMask == true => falsche Maske NYI
                  int n1 = (n & 0xf0) / 16;
                  int n2 = (n & 0x0f);
                  mask.AddPel((n1 >= firstMaskColor) && (n1 <= lastMaskColor));
                  mask.AddPel((n2 >= firstMaskColor) && (n2 <= lastMaskColor));
                }
                else if (bits == 1)
                {
                  // TODO???: segmentedColorMask == true => bad mask NYI
                  for (int bit = 1; bit <= 8; ++bit)
                  {
                    int n1 = (n & 0x80) / 128;
                    mask.AddPel((n1 >= firstMaskColor) && (n1 <= lastMaskColor));
                    n *= 2;
                  }
                }
              }
              bytesOffsetRead += 1;
              bytesOffsetWrite += 1;
            }
            bytesOffsetRead = 4 * ((bytesOffsetRead + 3) / 4); // Align to 32 bit boundary
          }
        }
        else
        {
          throw new NotImplementedException("ReadIndexedMemoryBitmap: unsupported format #3");
        }

        if (firstMaskColor != -1 &&
          lastMaskColor != -1)
        {
          // Color mask requires Reader 4.0 or higher:
          if (!segmentedColorMask && pdfVersion >= 13)
          {
            PdfArray array = new PdfArray(this.document);
            array.Elements.Add(new PdfInteger(firstMaskColor));
            array.Elements.Add(new PdfInteger(lastMaskColor));
            Elements[Keys.Mask] = array;
          }
          else
          {
            // Monochrome mask
            byte[] maskDataCompressed = fd.Encode(mask.MaskData);
            PdfDictionary pdfMask = new PdfDictionary(this.document);
            pdfMask.Elements.SetName(Keys.Type, "/XObject");
            pdfMask.Elements.SetName(Keys.Subtype, "/Image");

            this.Owner.irefTable.Add(pdfMask);
            pdfMask.Stream = new PdfStream(maskDataCompressed, pdfMask);
            pdfMask.Elements[Keys.Length] = new PdfInteger(maskDataCompressed.Length);
            pdfMask.Elements[Keys.Filter] = new PdfName("/FlateDecode");
            pdfMask.Elements[Keys.Width] = new PdfInteger(width);
            pdfMask.Elements[Keys.Height] = new PdfInteger(height);
            pdfMask.Elements[Keys.BitsPerComponent] = new PdfInteger(1);
            pdfMask.Elements[Keys.ImageMask] = new PdfBoolean(true);
            Elements[Keys.Mask] = pdfMask.Reference;
          }
        }

        byte[] imageDataCompressed = fd.Encode(imageData);

        Stream = new PdfStream(imageDataCompressed, this);
        Elements[Keys.Length] = new PdfInteger(imageDataCompressed.Length);
        Elements[Keys.Filter] = new PdfName("/FlateDecode");
        Elements[Keys.Width] = new PdfInteger(width);
        Elements[Keys.Height] = new PdfInteger(height);
        Elements[Keys.BitsPerComponent] = new PdfInteger(bits);
        PdfArray array2 = new PdfArray(this.document);
        array2.Elements.Add(new PdfName("/Indexed"));
        // TODO: CMYK
        array2.Elements.Add(new PdfName("/DeviceRGB"));
        array2.Elements.Add(new PdfInteger(paletteColors - 1));
        array2.Elements.Add(colorPalette.Reference);
        Elements[Keys.ColorSpace] = array2;
      }
    }
Пример #13
0
    /// <summary>
    /// Creates the keys for a JPEG image.
    /// </summary>
    void InitializeJpeg()
    {
      // PDF support JPEG, so there's not much to be done
      MemoryStream memory = new MemoryStream();
#if GDI
      image.gdiImage.Save(memory, ImageFormat.Jpeg);
#endif
#if WPF
      JpegBitmapEncoder encoder = new JpegBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(this.image.wpfImage));
      encoder.Save(memory);
#endif
      int streamLength = (int)memory.Length;
      byte[] imageBits = new byte[streamLength];
      memory.Seek(0, SeekOrigin.Begin);
      memory.Read(imageBits, 0, streamLength);
      memory.Close();

      Stream = new PdfStream(imageBits, this);

      Elements[Keys.Length] = new PdfInteger(streamLength);
      Elements[Keys.Filter] = new PdfName("/DCTDecode");
      Elements[Keys.Width] = new PdfInteger(image.PixelWidth);
      Elements[Keys.Height] = new PdfInteger(image.PixelHeight);
      Elements[Keys.BitsPerComponent] = new PdfInteger(8);
#if GDI
      if ((image.gdiImage.Flags & ((int)ImageFlags.ColorSpaceCmyk | (int)ImageFlags.ColorSpaceYcck)) != 0)
      {
        // TODO: Test with CMYK JPEG files
        // THHO: I only found ImageFlags.ColorSpaceYcck JPEG files ...
        Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
        if ((image.gdiImage.Flags & (int)ImageFlags.ColorSpaceYcck) != 0)
          Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]");  // Invert colors? Why??
      }
      else if ((image.gdiImage.Flags & (int)ImageFlags.ColorSpaceGray) != 0)
      {
        Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
      }
      else
      {
        Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
      }
#endif
#if WPF
      // TODOWPF
      // WPFTHHO
#endif
    }
Пример #14
0
 /**
  * <summary>Gets the character map extracted from the given data.</summary>
  * <param name="stream">Character map data.</param>
  */
 public static IDictionary <ByteArray, int> Get(
     PdfStream stream
     )
 {
     return(Get(stream.Body));
 }
Пример #15
0
 public PdfImageXObject(PdfStream pdfObject)
     : base(pdfObject)
 {
 }
Пример #16
0
    /// <summary>
    /// Creates the keys for a JPEG image.
    /// </summary>
    void InitializeJpeg()
    {
      // PDF support JPEG, so there's not much to be done
      MemoryStream memory;
      byte[] imageBits = null;
      int streamLength = 0;
#if GDI
      memory = new MemoryStream();
      image.gdiImage.Save(memory, ImageFormat.Jpeg);
      if ((int)memory.Length == 0)
      {
        Debug.Assert(false, "Internal error? JPEG image, but file not found!");
      }
#endif
#if WPF && !SILVERLIGHT
      // AGHACK
      //string filename = XImage.GetImageFilename(image.wpfImage);
      //if (XImage.ReadJpegFile(filename, -1, ref imageBits))
      //{
      //  streamLength = imageBits.Length;
      //}
      //else
      //  imageBits = null;
      memory = image.Memory;
#endif
      if (imageBits == null)
      {
        streamLength = (int)memory.Length;
        imageBits = new byte[streamLength];
        memory.Seek(0, SeekOrigin.Begin);
        memory.Read(imageBits, 0, streamLength);
        memory.Close();
      }

      FlateDecode fd = new FlateDecode();
      byte[] imageDataCompressed = fd.Encode(imageBits);
      if (imageDataCompressed.Length < imageBits.Length)
      {
        Stream = new PdfStream(imageDataCompressed, this);
        Elements[Keys.Length] = new PdfInteger(imageDataCompressed.Length);
        PdfArray arrayFilters = new PdfArray(document);
        arrayFilters.Elements.Add(new PdfName("/FlateDecode"));
        arrayFilters.Elements.Add(new PdfName("/DCTDecode"));
        Elements[Keys.Filter] = arrayFilters;
      }
      else
      {
        Stream = new PdfStream(imageBits, this);
        Elements[Keys.Length] = new PdfInteger(streamLength);
        Elements[Keys.Filter] = new PdfName("/DCTDecode");
      }
      Elements[Keys.Width] = new PdfInteger(image.PixelWidth);
      Elements[Keys.Height] = new PdfInteger(image.PixelHeight);
      Elements[Keys.BitsPerComponent] = new PdfInteger(8);
#if GDI
      if ((image.gdiImage.Flags & ((int)ImageFlags.ColorSpaceCmyk | (int)ImageFlags.ColorSpaceYcck)) != 0)
      {
        // TODO: Test with CMYK JPEG files
        // THHO: I only found ImageFlags.ColorSpaceYcck JPEG files ...
        Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
        if ((image.gdiImage.Flags & (int)ImageFlags.ColorSpaceYcck) != 0)
          Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]");  // Invert colors? Why??
      }
      else if ((image.gdiImage.Flags & (int)ImageFlags.ColorSpaceGray) != 0)
      {
        Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
      }
      else
      {
        Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
      }
#endif
#if WPF
      // TODOWPF
      // WPFTHHO
#if !SILVERLIGHT
      string pixelFormat = image.wpfImage.Format.ToString();
#else
      string pixelFormat = "xxx";
#endif
      bool isCmyk = image.IsCmyk;
      bool isGrey = pixelFormat == "Gray8";
      if (isCmyk)
      {
        // TODO: Test with CMYK JPEG files
        // THHO: I only found ImageFlags.ColorSpaceYcck JPEG files ...
        Elements[Keys.ColorSpace] = new PdfName("/DeviceCMYK");
        Elements["/Decode"] = new PdfLiteral("[1 0 1 0 1 0 1 0]");  // Invert colors? Why??
      }
      else if (isGrey)
      {
        Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
      }
      else
      {
        Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
      }
#endif
    }
Пример #17
0
 /// <summary>
 /// Creates new instance from the
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// object.
 /// This stream should have PatternType equals to 1.
 /// </summary>
 /// <param name="pdfObject">
 /// the
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// that represents Tiling Pattern.
 /// </param>
 public Tiling(PdfStream pdfObject)
     : base(pdfObject)
 {
 }
Пример #18
0
        private static PdfStream CreatePdfStream(ImageData image, iText.Kernel.Pdf.Xobject.PdfImageXObject imageMask
                                                 )
        {
            PdfStream stream;

            if (image.GetOriginalType() == ImageType.RAW)
            {
                RawImageHelper.UpdateImageAttributes((RawImageData)image, null);
            }
            stream = new PdfStream(image.GetData());
            String filter = image.GetFilter();

            if (filter != null && filter.Equals("JPXDecode") && image.GetColorSpace() <= 0)
            {
                stream.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
                image.SetBpc(0);
            }
            stream.Put(PdfName.Type, PdfName.XObject);
            stream.Put(PdfName.Subtype, PdfName.Image);
            PdfDictionary decodeParms = CreateDictionaryFromMap(stream, image.GetDecodeParms());

            if (decodeParms != null)
            {
                stream.Put(PdfName.DecodeParms, decodeParms);
            }
            PdfName colorSpace;

            switch (image.GetColorSpace())
            {
            case 1: {
                colorSpace = PdfName.DeviceGray;
                break;
            }

            case 3: {
                colorSpace = PdfName.DeviceRGB;
                break;
            }

            default: {
                colorSpace = PdfName.DeviceCMYK;
                break;
            }
            }
            stream.Put(PdfName.ColorSpace, colorSpace);
            if (image.GetBpc() != 0)
            {
                stream.Put(PdfName.BitsPerComponent, new PdfNumber(image.GetBpc()));
            }
            if (image.GetFilter() != null)
            {
                stream.Put(PdfName.Filter, new PdfName(image.GetFilter()));
            }
            //TODO: return to this later
            //        if (image.getLayer() != null)
            //            put(PdfName.OC, image.getLayer().getRef());
            if (image.GetColorSpace() == -1)
            {
                stream.Remove(PdfName.ColorSpace);
            }
            PdfDictionary additional = CreateDictionaryFromMap(stream, image.GetImageAttributes());

            if (additional != null)
            {
                stream.PutAll(additional);
            }
            IccProfile iccProfile = image.GetProfile();

            if (iccProfile != null)
            {
                PdfStream iccProfileStream   = PdfCieBasedCs.IccBased.GetIccProfileStream(iccProfile);
                PdfArray  iccBasedColorSpace = new PdfArray();
                iccBasedColorSpace.Add(PdfName.ICCBased);
                iccBasedColorSpace.Add(iccProfileStream);
                PdfObject colorSpaceObject          = stream.Get(PdfName.ColorSpace);
                bool      iccProfileShouldBeApplied = true;
                if (colorSpaceObject != null)
                {
                    PdfColorSpace cs = PdfColorSpace.MakeColorSpace(colorSpaceObject);
                    if (cs == null)
                    {
                        LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_INCORRECT_OR_UNSUPPORTED_COLOR_SPACE_OVERRIDDEN_BY_ICC_PROFILE
                                                                                                     );
                    }
                    else
                    {
                        if (cs is PdfSpecialCs.Indexed)
                        {
                            PdfColorSpace baseCs = ((PdfSpecialCs.Indexed)cs).GetBaseCs();
                            if (baseCs == null)
                            {
                                LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_INCORRECT_OR_UNSUPPORTED_BASE_COLOR_SPACE_IN_INDEXED_COLOR_SPACE_OVERRIDDEN_BY_ICC_PROFILE
                                                                                                             );
                            }
                            else
                            {
                                if (baseCs.GetNumberOfComponents() != iccProfile.GetNumComponents())
                                {
                                    LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_ICC_PROFILE_WITH_INCOMPATIBLE_NUMBER_OF_COLOR_COMPONENTS_COMPARED_TO_BASE_COLOR_SPACE_IN_INDEXED_COLOR_SPACE
                                                                                                                 );
                                    iccProfileShouldBeApplied = false;
                                }
                                else
                                {
                                    iccProfileStream.Put(PdfName.Alternate, baseCs.GetPdfObject());
                                }
                            }
                            if (iccProfileShouldBeApplied)
                            {
                                ((PdfArray)colorSpaceObject).Set(1, iccBasedColorSpace);
                                iccProfileShouldBeApplied = false;
                            }
                        }
                        else
                        {
                            if (cs.GetNumberOfComponents() != iccProfile.GetNumComponents())
                            {
                                LogManager.GetLogger(typeof(iText.Kernel.Pdf.Xobject.PdfImageXObject)).Error(iText.IO.LogMessageConstant.IMAGE_HAS_ICC_PROFILE_WITH_INCOMPATIBLE_NUMBER_OF_COLOR_COMPONENTS_COMPARED_TO_COLOR_SPACE
                                                                                                             );
                                iccProfileShouldBeApplied = false;
                            }
                            else
                            {
                                iccProfileStream.Put(PdfName.Alternate, colorSpaceObject);
                            }
                        }
                    }
                }
                if (iccProfileShouldBeApplied)
                {
                    stream.Put(PdfName.ColorSpace, iccBasedColorSpace);
                }
            }
            if (image.IsMask() && (image.GetBpc() == 1 || image.GetBpc() > 0xff))
            {
                stream.Put(PdfName.ImageMask, PdfBoolean.TRUE);
            }
            if (imageMask != null)
            {
                if (imageMask.softMask)
                {
                    stream.Put(PdfName.SMask, imageMask.GetPdfObject());
                }
                else
                {
                    if (imageMask.mask)
                    {
                        stream.Put(PdfName.Mask, imageMask.GetPdfObject());
                    }
                }
            }
            ImageData mask = image.GetImageMask();

            if (mask != null)
            {
                if (mask.IsSoftMask())
                {
                    stream.Put(PdfName.SMask, new iText.Kernel.Pdf.Xobject.PdfImageXObject(image.GetImageMask()).GetPdfObject(
                                   ));
                }
                else
                {
                    if (mask.IsMask())
                    {
                        stream.Put(PdfName.Mask, new iText.Kernel.Pdf.Xobject.PdfImageXObject(image.GetImageMask()).GetPdfObject()
                                   );
                    }
                }
            }
            if (image.GetDecode() != null)
            {
                stream.Put(PdfName.Decode, new PdfArray(image.GetDecode()));
            }
            if (image.IsMask() && image.IsInverted())
            {
                stream.Put(PdfName.Decode, new PdfArray(new float[] { 1, 0 }));
            }
            if (image.IsInterpolation())
            {
                stream.Put(PdfName.Interpolate, PdfBoolean.TRUE);
            }
            // deal with transparency
            int[] transparency = image.GetTransparency();
            if (transparency != null && !image.IsMask() && imageMask == null)
            {
                PdfArray t = new PdfArray();
                foreach (int transparencyItem in transparency)
                {
                    t.Add(new PdfNumber(transparencyItem));
                }
                stream.Put(PdfName.Mask, t);
            }
            stream.Put(PdfName.Width, new PdfNumber(image.GetWidth()));
            stream.Put(PdfName.Height, new PdfNumber(image.GetHeight()));
            return(stream);
        }
Пример #19
0
 public ContentStream(PdfStream stream)
 {
     _stream = stream;
 }
Пример #20
0
        private PdfObject CleverPdfDictionaryClone(PdfDictionary dict) {
            PdfDictionary newDict;
            if (dict.IsStream()) {
                newDict = new PdfStream(emptyByteArray);
                newDict.Remove(PdfName.LENGTH);
            }
            else
                newDict = new PdfDictionary();

            foreach (PdfName key in dict.Keys)
                if (keysForCheck.Contains(key))
                    newDict.Put(key, dict.Get(key));

            return newDict;
        }
Пример #21
0
 public static iText.Kernel.Pdf.Action.PdfAction CreateSound(PdfStream sound)
 {
     return(new iText.Kernel.Pdf.Action.PdfAction().Put(PdfName.S, PdfName.Sound).Put(PdfName.Sound, sound));
 }
Пример #22
0
    /// <summary>
    /// Creates the stream of this dictionary and initializes it with the specified byte array.
    /// The function must not be called if the dictionary already has a strem.
    /// </summary>
    public PdfStream CreateStream(byte[] value)
    {
      if (this.stream != null)
        throw new InvalidOperationException("The dictionary already has a stream.");

      this.stream = new PdfStream(value, this);
      // Always set the length
      Elements[PdfStream.Keys.Length] = new PdfInteger(this.stream.Length);
      return this.stream;
    }
Пример #23
0
        public static void ExtractImagesFromPDF(string sourcePdf, string outputPath, int index)
        {
            // NOTE:  This will only get the first image it finds per page.
            PdfReader pdf = new PdfReader(sourcePdf);
            RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

            try
            {
                for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
                {
                    PdfDictionary pg  = pdf.GetPageN(pageNumber);
                    PdfDictionary res =
                        (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
                    PdfDictionary xobj =
                        (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                    if (xobj != null)
                    {
                        foreach (PdfName name in xobj.Keys)
                        {
                            PdfObject obj = xobj.Get(name);
                            if (obj.IsIndirect())
                            {
                                PdfDictionary tg   = (PdfDictionary)PdfReader.GetPdfObject(obj);
                                PdfName       type =
                                    (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
                                if (PdfName.IMAGE.Equals(type))
                                {
                                    int       XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                    PdfObject pdfObj    = pdf.GetPdfObject(XrefIndex);
                                    PdfStream pdfStrem  = (PdfStream)pdfObj;
                                    byte[]    bytes     = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                                    if ((bytes != null))
                                    {
                                        using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes))
                                        {
                                            memStream.Position = 0;
                                            System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
                                            // must save the file while stream is open.
                                            if (!Directory.Exists(outputPath))
                                            {
                                                Directory.CreateDirectory(outputPath);
                                            }

                                            //string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber));
                                            string            _pageNumber = pageNumber.ToString().PadLeft(3, '0');
                                            string            path        = Path.Combine(outputPath, index + "_" + _pageNumber + ".jpg");
                                            EncoderParameters parms       = new EncoderParameters(1);
                                            parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
                                            // GetImageEncoder is found below this method
                                            ImageCodecInfo jpegEncoder = GetImageEncoder("JPEG");
                                            img.Save(path, jpegEncoder, parms);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch
            {
                // throw;
            }
            finally
            {
                pdf.Close();
            }
        }
Пример #24
0
        protected override void LoadEncoding(
            )
        {
            OpenFontParser parser;

            {
                PdfDictionary descriptor = Descriptor;
                if (descriptor.ContainsKey(PdfName.FontFile2)) // Embedded TrueType font file (without 'glyf' table).
                {
                    PdfStream fontFileStream = (PdfStream)descriptor.Resolve(PdfName.FontFile2);
                    parser = new OpenFontParser(fontFileStream.Body);
                }
                else if (descriptor.ContainsKey(PdfName.FontFile3))
                {
                    PdfStream fontFileStream  = (PdfStream)descriptor.Resolve(PdfName.FontFile3);
                    PdfName   fontFileSubtype = (PdfName)fontFileStream.Header[PdfName.Subtype];
                    if (fontFileSubtype.Equals(PdfName.OpenType)) // Embedded OpenFont/TrueType font file (with 'glyf' table).
                    {
                        parser = new OpenFontParser(fontFileStream.Body);
                    }
                    else // Unknown.
                    {
                        throw new NotSupportedException("Unknown embedded font file format: " + fontFileSubtype);
                    }
                }
                else
                {
                    parser = null;
                }
            }
            if (parser != null) // Embedded font file.
            {
                // Glyph indexes.
                glyphIndexes = parser.GlyphIndexes;
                if (codes != null &&
                    parser.Metrics.IsCustomEncoding)
                {
                    /*
                     * NOTE: In case of symbolic font,
                     * glyph indices are natively mapped to character codes,
                     * so they must be remapped to Unicode whenever possible
                     * (i.e. when ToUnicode stream is available).
                     */
                    Dictionary <int, int> unicodeGlyphIndexes = new Dictionary <int, int>();
                    foreach (KeyValuePair <int, int> glyphIndexEntry in glyphIndexes)
                    {
                        int code;
                        if (!codes.TryGetValue(new ByteArray(new byte[] { (byte)(int)glyphIndexEntry.Key }), out code))
                        {
                            continue;
                        }

                        unicodeGlyphIndexes[code] = glyphIndexEntry.Value;
                    }
                    glyphIndexes = unicodeGlyphIndexes;
                }
            }

            PdfDataObject encodingObject = BaseDataObject.Resolve(PdfName.Encoding);
            FlagsEnum     flags          = Flags;

            if ((flags & FlagsEnum.Symbolic) != 0 ||
                ((flags & FlagsEnum.Nonsymbolic) == 0 && encodingObject == null)) // Symbolic.
            {
                symbolic = true;

                if (glyphIndexes == null)
                {
                    /*
                     * NOTE: In case no font file is available, we have to synthesize its metrics
                     * from existing entries.
                     */
                    glyphIndexes = new Dictionary <int, int>();
                    PdfArray glyphWidthObjects = (PdfArray)BaseDataObject.Resolve(PdfName.Widths);
                    if (glyphWidthObjects != null)
                    {
                        int code = ((PdfInteger)BaseDataObject[PdfName.FirstChar]).RawValue;
                        foreach (PdfDirectObject glyphWidthObject in glyphWidthObjects)
                        {
                            if (((PdfInteger)glyphWidthObject).RawValue > 0)
                            {
                                glyphIndexes[code] = code;
                            }

                            code++;
                        }
                    }
                }

                if (this.codes == null)
                {
                    Dictionary <ByteArray, int> codes = new Dictionary <ByteArray, int>();
                    foreach (KeyValuePair <int, int> glyphIndexEntry in glyphIndexes)
                    {
                        if (glyphIndexEntry.Value > 0)
                        {
                            int    glyphCharCode = glyphIndexEntry.Key;
                            byte[] charCode      = new byte[] { (byte)glyphCharCode };
                            codes[new ByteArray(charCode)] = glyphCharCode;
                        }
                    }
                    this.codes = new BiDictionary <ByteArray, int>(codes);
                }
            }
            else // Nonsymbolic.
            {
                symbolic = false;

                if (this.codes == null)
                {
                    Dictionary <ByteArray, int> codes;
                    if (encodingObject == null) // Default encoding.
                    {
                        codes = Encoding.Get(PdfName.StandardEncoding).GetCodes();
                    }
                    else if (encodingObject is PdfName) // Predefined encoding.
                    {
                        codes = Encoding.Get((PdfName)encodingObject).GetCodes();
                    }
                    else // Custom encoding.
                    {
                        PdfDictionary encodingDictionary = (PdfDictionary)encodingObject;

                        // 1. Base encoding.
                        PdfName baseEncodingName = (PdfName)encodingDictionary[PdfName.BaseEncoding];
                        if (baseEncodingName == null) // Default base encoding.
                        {
                            codes = Encoding.Get(PdfName.StandardEncoding).GetCodes();
                        }
                        else // Predefined base encoding.
                        {
                            codes = Encoding.Get(baseEncodingName).GetCodes();
                        }

                        // 2. Differences.
                        LoadEncodingDifferences(encodingDictionary, codes);
                    }
                    this.codes = new BiDictionary <ByteArray, int>(codes);
                }

                if (glyphIndexes == null)
                {
                    /*
                     * NOTE: In case no font file is available, we have to synthesize its metrics
                     * from existing entries.
                     */
                    glyphIndexes = new Dictionary <int, int>();
                    PdfArray glyphWidthObjects = (PdfArray)BaseDataObject.Resolve(PdfName.Widths);
                    if (glyphWidthObjects != null)
                    {
                        ByteArray charCode = new ByteArray(
                            new byte[]
                            { (byte)(int)((PdfInteger)BaseDataObject[PdfName.FirstChar]).RawValue }
                            );
                        foreach (PdfDirectObject glyphWidthObject in glyphWidthObjects)
                        {
                            if (((PdfInteger)glyphWidthObject).RawValue > 0)
                            {
                                int code;
                                if (codes.TryGetValue(charCode, out code))
                                {
                                    glyphIndexes[code] = (int)charCode.Data[0];
                                }
                            }
                            charCode.Data[0]++;
                        }
                    }
                }
            }
        }
Пример #25
0
 /// <summary>Sets state of this object according to the color space</summary>
 /// <param name="csObj">the colorspace to use</param>
 /// <param name="allowIndexed">whether indexed color spaces will be resolved (used for recursive call)</param>
 private void FindColorspace(PdfObject csObj, bool allowIndexed)
 {
     if (PdfName.DeviceGray.Equals(csObj) || (csObj == null && bpc == 1))
     {
         // handle imagemasks
         stride       = (width * bpc + 7) / 8;
         pngColorType = 0;
     }
     else
     {
         if (PdfName.DeviceRGB.Equals(csObj))
         {
             if (bpc == 8 || bpc == 16)
             {
                 stride       = (width * bpc * 3 + 7) / 8;
                 pngColorType = 2;
             }
         }
         else
         {
             if (csObj is PdfArray)
             {
                 PdfArray  ca   = (PdfArray)csObj;
                 PdfObject tyca = ca.Get(0);
                 if (PdfName.CalGray.Equals(tyca))
                 {
                     stride       = (width * bpc + 7) / 8;
                     pngColorType = 0;
                 }
                 else
                 {
                     if (PdfName.CalRGB.Equals(tyca))
                     {
                         if (bpc == 8 || bpc == 16)
                         {
                             stride       = (width * bpc * 3 + 7) / 8;
                             pngColorType = 2;
                         }
                     }
                     else
                     {
                         if (PdfName.ICCBased.Equals(tyca))
                         {
                             PdfStream pr = (PdfStream)ca.Get(1);
                             int       n  = pr.GetAsNumber(PdfName.N).IntValue();
                             if (n == 1)
                             {
                                 stride       = (width * bpc + 7) / 8;
                                 pngColorType = 0;
                                 icc          = pr.GetBytes();
                             }
                             else
                             {
                                 if (n == 3)
                                 {
                                     stride       = (width * bpc * 3 + 7) / 8;
                                     pngColorType = 2;
                                     icc          = pr.GetBytes();
                                 }
                             }
                         }
                         else
                         {
                             if (allowIndexed && PdfName.Indexed.Equals(tyca))
                             {
                                 FindColorspace(ca.Get(1), false);
                                 if (pngColorType == 2)
                                 {
                                     PdfObject id2 = ca.Get(3);
                                     if (id2 is PdfString)
                                     {
                                         palette = ((PdfString)id2).GetValueBytes();
                                     }
                                     else
                                     {
                                         if (id2 is PdfStream)
                                         {
                                             palette = ((PdfStream)id2).GetBytes();
                                         }
                                     }
                                     stride       = (width * bpc + 7) / 8;
                                     pngColorType = 3;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Пример #26
0
        private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs
                               )
        {
            PdfCatalog catalog = document.GetCatalog();

            if (document.GetPdfVersion().CompareTo(PdfVersion.PDF_2_0) < 0)
            {
                catalog.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            }
            foreach (PdfName vkey in validated.Keys)
            {
                PdfArray      ocsp = new PdfArray();
                PdfArray      crl  = new PdfArray();
                PdfArray      cert = new PdfArray();
                PdfDictionary vri  = new PdfDictionary();
                foreach (byte[] b in validated.Get(vkey).crls)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
                    ps.MakeIndirect(document);
                    crl.Add(ps);
                    crls.Add(ps);
                    crls.SetModified();
                }
                foreach (byte[] b in validated.Get(vkey).ocsps)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
                    ocsp.Add(ps);
                    ocsps.Add(ps);
                    ocsps.SetModified();
                }
                foreach (byte[] b in validated.Get(vkey).certs)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.SetCompressionLevel(CompressionConstants.DEFAULT_COMPRESSION);
                    ps.MakeIndirect(document);
                    cert.Add(ps);
                    certs.Add(ps);
                    certs.SetModified();
                }
                if (ocsp.Size() > 0)
                {
                    ocsp.MakeIndirect(document);
                    vri.Put(PdfName.OCSP, ocsp);
                }
                if (crl.Size() > 0)
                {
                    crl.MakeIndirect(document);
                    vri.Put(PdfName.CRL, crl);
                }
                if (cert.Size() > 0)
                {
                    cert.MakeIndirect(document);
                    vri.Put(PdfName.Cert, cert);
                }
                vri.MakeIndirect(document);
                vrim.Put(vkey, vri);
            }
            vrim.MakeIndirect(document);
            vrim.SetModified();
            dss.Put(PdfName.VRI, vrim);
            if (ocsps.Size() > 0)
            {
                ocsps.MakeIndirect(document);
                dss.Put(PdfName.OCSPs, ocsps);
            }
            if (crls.Size() > 0)
            {
                crls.MakeIndirect(document);
                dss.Put(PdfName.CRLs, crls);
            }
            if (certs.Size() > 0)
            {
                certs.MakeIndirect(document);
                dss.Put(PdfName.Certs, certs);
            }
            dss.MakeIndirect(document);
            dss.SetModified();
            catalog.Put(PdfName.DSS, dss);
        }
Пример #27
0
        public virtual byte[] DecodeTiffAndPngBytes(byte[] imageBytes)
        {
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    throw new iText.IO.IOException(iText.IO.IOException.ColorDepthIsNotSupported).SetMessageParams(bpc);
                }
                if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.Get(0);
                    if (!PdfName.ICCBased.Equals(tyca))
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.ColorSpaceIsNotSupported).SetMessageParams(tyca.ToString
                                                                                                                           ());
                    }
                    PdfStream pr = (PdfStream)ca.Get(1);
                    int       n  = pr.GetAsNumber(PdfName.N).IntValue();
                    if (n != 4)
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.NValueIsNotSupported).SetMessageParams(n);
                    }
                    icc = pr.GetBytes();
                }
                else
                {
                    if (!PdfName.DeviceCMYK.Equals(colorspace))
                    {
                        throw new iText.IO.IOException(iText.IO.IOException.ColorSpaceIsNotSupported).SetMessageParams(colorspace.
                                                                                                                       ToString());
                    }
                }
                stride = 4 * width;
                TiffWriter wr = new TiffWriter();
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[] { 8, 8, 8, 8 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED
                                                      ));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, (int)width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, (int)height));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING
                                                      ));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, (int)height));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[] { 300, 1 }));
                wr.AddField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
                wr.AddField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, iText.Kernel.Version.GetInstance().GetVersion
                                                          ()));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, imageBytes, (int)height, 4, stride);
                byte[] buf = comp.ToArray();
                wr.AddField(new TiffWriter.FieldImage(buf));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.Length));
                if (icc != null)
                {
                    wr.AddField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
                }
                wr.WriteFile(ms);
                imageBytes = ms.ToArray();
                return(imageBytes);
            }
            else
            {
                PngWriter png = new PngWriter(ms);
                if (decode != null)
                {
                    if (pngBitDepth == 1)
                    {
                        // if the decode array is 1,0, then we need to invert the image
                        if (decode.GetAsNumber(0).IntValue() == 1 && decode.GetAsNumber(1).IntValue() == 0)
                        {
                            int len = imageBytes.Length;
                            for (int t = 0; t < len; ++t)
                            {
                                imageBytes[t] ^= 0xff;
                            }
                        }
                    }
                }
                // if the decode array is 0,1, do nothing.  It's possible that the array could be 0,0 or 1,1 - but that would be silly, so we'll just ignore that case
                // todo: add decode transformation for other depths
                png.WriteHeader(width, height, pngBitDepth, pngColorType);
                if (icc != null)
                {
                    png.WriteIccProfile(icc);
                }
                if (palette != null)
                {
                    png.WritePalette(palette);
                }
                png.WriteData(imageBytes, stride);
                png.WriteEnd();
                imageBytes = ms.ToArray();
                return(imageBytes);
            }
        }
Пример #28
0
        /// <summary>Embed a file to a PdfDocument.</summary>
        /// <param name="doc"/>
        /// <param name="stream"/>
        /// <param name="description"/>
        /// <param name="fileDisplay"/>
        /// <param name="mimeType"/>
        /// <param name="afRelationshipValue"/>
        private static iText.Kernel.Pdf.Filespec.PdfFileSpec CreateEmbeddedFileSpec(PdfDocument doc, PdfStream stream
                                                                                    , String description, String fileDisplay, PdfName mimeType, PdfName afRelationshipValue)
        {
            PdfDictionary dict = new PdfDictionary();

            stream.Put(PdfName.Type, PdfName.EmbeddedFile);
            if (afRelationshipValue != null)
            {
                dict.Put(PdfName.AFRelationship, afRelationshipValue);
            }
            else
            {
                dict.Put(PdfName.AFRelationship, PdfName.Unspecified);
            }
            if (mimeType != null)
            {
                stream.Put(PdfName.Subtype, mimeType);
            }
            else
            {
                stream.Put(PdfName.Subtype, PdfName.ApplicationOctetStream);
            }
            if (description != null)
            {
                dict.Put(PdfName.Desc, new PdfString(description));
            }
            dict.Put(PdfName.Type, PdfName.Filespec);
            dict.Put(PdfName.F, new PdfString(fileDisplay));
            dict.Put(PdfName.UF, new PdfString(fileDisplay, PdfEncodings.UNICODE_BIG));
            PdfDictionary ef = new PdfDictionary();

            ef.Put(PdfName.F, stream);
            ef.Put(PdfName.UF, stream);
            dict.Put(PdfName.EF, ef);
            return((iText.Kernel.Pdf.Filespec.PdfFileSpec) new iText.Kernel.Pdf.Filespec.PdfFileSpec(dict).MakeIndirect
                       (doc));
        }
        /// <summary>Constructs appearance (top-level) for a signature.</summary>
        /// <remarks>
        /// Constructs appearance (top-level) for a signature.
        /// <p>
        /// Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A>
        /// for further details.
        /// </remarks>
        /// <returns>a top-level signature appearance</returns>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual PdfFormXObject GetAppearance()
        {
            PdfCanvas canvas;

            if (IsInvisible())
            {
                PdfFormXObject appearance = new PdfFormXObject(new Rectangle(0, 0));
                appearance.MakeIndirect(document);
                return(appearance);
            }
            if (n0 == null && !reuseAppearance)
            {
                CreateBlankN0();
            }
            if (n2 == null)
            {
                n2 = new PdfFormXObject(rect);
                n2.MakeIndirect(document);
                canvas = new PdfCanvas(n2, document);
                int rotation = document.GetPage(page).GetRotation();
                if (rotation == 90)
                {
                    canvas.ConcatMatrix(0, 1, -1, 0, rect.GetWidth(), 0);
                }
                else
                {
                    if (rotation == 180)
                    {
                        canvas.ConcatMatrix(-1, 0, 0, -1, rect.GetWidth(), rect.GetHeight());
                    }
                    else
                    {
                        if (rotation == 270)
                        {
                            canvas.ConcatMatrix(0, -1, 1, 0, 0, rect.GetHeight());
                        }
                    }
                }
                Rectangle rotatedRect = RotateRectangle(this.rect, document.GetPage(page).GetRotation());
                String    text;
                if (layer2Text == null)
                {
                    StringBuilder buf = new StringBuilder();
                    buf.Append("Digitally signed by ");
                    String name = null;
                    CertificateInfo.X500Name x500name = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate);
                    if (x500name != null)
                    {
                        name = x500name.GetField("CN");
                        if (name == null)
                        {
                            name = x500name.GetField("E");
                        }
                    }
                    if (name == null)
                    {
                        name = "";
                    }
                    buf.Append(name).Append('\n');
                    buf.Append("Date: ").Append(SignUtils.DateToString(signDate));
                    if (reason != null)
                    {
                        buf.Append('\n').Append(reasonCaption).Append(reason);
                    }
                    if (location != null)
                    {
                        buf.Append('\n').Append(locationCaption).Append(location);
                    }
                    text = buf.ToString();
                }
                else
                {
                    text = layer2Text;
                }
                if (image != null)
                {
                    if (imageScale == 0)
                    {
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, rotatedRect.GetWidth(), 0, 0, rotatedRect.GetHeight(), 0, 0);
                    }
                    else
                    {
                        float usableScale = imageScale;
                        if (imageScale < 0)
                        {
                            usableScale = Math.Min(rotatedRect.GetWidth() / image.GetWidth(), rotatedRect.GetHeight() / image.GetHeight
                                                       ());
                        }
                        float w = image.GetWidth() * usableScale;
                        float h = image.GetHeight() * usableScale;
                        float x = (rotatedRect.GetWidth() - w) / 2;
                        float y = (rotatedRect.GetHeight() - h) / 2;
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, w, 0, 0, h, x, y);
                    }
                }
                PdfFont font;
                if (layer2Font == null)
                {
                    font = PdfFontFactory.CreateFont();
                }
                else
                {
                    font = layer2Font;
                }
                Rectangle dataRect      = null;
                Rectangle signatureRect = null;
                if (renderingMode == PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION || renderingMode == PdfSignatureAppearance.RenderingMode
                    .GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null)
                {
                    if (rotatedRect.GetHeight() > rotatedRect.GetWidth())
                    {
                        signatureRect = new Rectangle(MARGIN, rotatedRect.GetHeight() / 2, rotatedRect.GetWidth() - 2 * MARGIN, rotatedRect
                                                      .GetHeight() / 2);
                        dataRect = new Rectangle(MARGIN, MARGIN, rotatedRect.GetWidth() - 2 * MARGIN, rotatedRect.GetHeight() / 2
                                                 - 2 * MARGIN);
                    }
                    else
                    {
                        // origin is the bottom-left
                        signatureRect = new Rectangle(MARGIN, MARGIN, rotatedRect.GetWidth() / 2 - 2 * MARGIN, rotatedRect.GetHeight
                                                          () - 2 * MARGIN);
                        dataRect = new Rectangle(rotatedRect.GetWidth() / 2 + MARGIN / 2, MARGIN, rotatedRect.GetWidth() / 2 - MARGIN
                                                 , rotatedRect.GetHeight() - 2 * MARGIN);
                    }
                }
                else
                {
                    if (renderingMode == PdfSignatureAppearance.RenderingMode.GRAPHIC)
                    {
                        if (signatureGraphic == null)
                        {
                            throw new InvalidOperationException("A signature image must be present when rendering mode is graphic. Use setSignatureGraphic()"
                                                                );
                        }
                        signatureRect = new Rectangle(MARGIN, MARGIN, rotatedRect.GetWidth() - 2 * MARGIN, rotatedRect.GetHeight()
                                                      - 2 * MARGIN);
                    }
                    else
                    {
                        // take all space available
                        dataRect = new Rectangle(MARGIN, MARGIN, rotatedRect.GetWidth() - 2 * MARGIN, rotatedRect.GetHeight() * (1
                                                                                                                                 - TOP_SECTION) - 2 * MARGIN);
                    }
                }
                switch (renderingMode)
                {
                case PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION: {
                    String signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("CN");
                    if (signedBy == null)
                    {
                        signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("E");
                    }
                    if (signedBy == null)
                    {
                        signedBy = "";
                    }
                    AddTextToCanvas(signedBy, font, signatureRect);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION: {
                    if (signatureGraphic == null)
                    {
                        throw new InvalidOperationException("A signature image must be present when rendering mode is graphic and description. Use setSignatureGraphic()"
                                                            );
                    }
                    float imgWidth = signatureGraphic.GetWidth();
                    if (imgWidth == 0)
                    {
                        imgWidth = signatureRect.GetWidth();
                    }
                    float imgHeight = signatureGraphic.GetHeight();
                    if (imgHeight == 0)
                    {
                        imgHeight = signatureRect.GetHeight();
                    }
                    float multiplierH = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier  = Math.Min(multiplierH, multiplierW);
                    imgWidth  *= multiplier;
                    imgHeight *= multiplier;
                    float x = signatureRect.GetRight() - imgWidth;
                    float y = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth, 0, 0, imgHeight, x, y);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC: {
                    float imgWidth_1 = signatureGraphic.GetWidth();
                    if (imgWidth_1 == 0)
                    {
                        imgWidth_1 = signatureRect.GetWidth();
                    }
                    float imgHeight_1 = signatureGraphic.GetHeight();
                    if (imgHeight_1 == 0)
                    {
                        imgHeight_1 = signatureRect.GetHeight();
                    }
                    float multiplierH_1 = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW_1 = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier_1  = Math.Min(multiplierH_1, multiplierW_1);
                    imgWidth_1  *= multiplier_1;
                    imgHeight_1 *= multiplier_1;
                    float x_1 = signatureRect.GetLeft() + (signatureRect.GetWidth() - imgWidth_1) / 2;
                    float y_1 = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight_1) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth_1, 0, 0, imgHeight_1, x_1, y_1);
                    break;
                }
                }
                if (renderingMode != PdfSignatureAppearance.RenderingMode.GRAPHIC)
                {
                    AddTextToCanvas(text, font, dataRect);
                }
            }
            Rectangle rotated = new Rectangle(rect);

            if (topLayer == null)
            {
                topLayer = new PdfFormXObject(rotated);
                topLayer.MakeIndirect(document);
                if (reuseAppearance)
                {
                    PdfAcroForm    acroForm = PdfAcroForm.GetAcroForm(document, true);
                    PdfFormField   field    = acroForm.GetField(fieldName);
                    PdfStream      stream   = field.GetWidgets()[0].GetAppearanceDictionary().GetAsStream(PdfName.N);
                    PdfFormXObject xobj     = new PdfFormXObject(stream);
                    if (stream != null)
                    {
                        topLayer.GetResources().AddForm(xobj, new PdfName("n0"));
                        PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                        canvas1.AddXObject(xobj, 1, 0, 0, 1, 0, 0);
                    }
                    else
                    {
                        reuseAppearance = false;
                        if (n0 == null)
                        {
                            CreateBlankN0();
                        }
                    }
                }
                if (!reuseAppearance)
                {
                    topLayer.GetResources().AddForm(n0, new PdfName("n0"));
                    PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                    canvas1.AddXObject(n0, 1, 0, 0, 1, 0, 0);
                }
                topLayer.GetResources().AddForm(n2, new PdfName("n2"));
                PdfCanvas canvas1_1 = new PdfCanvas(topLayer, document);
                canvas1_1.AddXObject(n2, 1, 0, 0, 1, 0, 0);
            }
            PdfFormXObject napp = new PdfFormXObject(rotated);

            napp.MakeIndirect(document);
            napp.GetResources().AddForm(topLayer, new PdfName("FRM"));
            canvas = new PdfCanvas(napp, document);
            canvas.AddXObject(topLayer, 0, 0);
            return(napp);
        }
Пример #30
0
        /// <summary>PDF 2.0.</summary>
        /// <remarks>PDF 2.0. Gets a stream object defining the thumbnail image for the file specification.</remarks>
        /// <returns>image used as a thumbnail, or <c>null</c> if it is not set</returns>
        public virtual PdfImageXObject GetThumbnailImage()
        {
            PdfStream thumbnailStream = ((PdfDictionary)GetPdfObject()).GetAsStream(PdfName.Thumb);

            return(thumbnailStream != null ? new PdfImageXObject(thumbnailStream) : null);
        }
Пример #31
0
 virtual public void HandleXObject(PdfContentStreamProcessor processor, PdfStream xobjectStream, PdfIndirectReference refi)
 {
     // ignore XObject subtype
 }
Пример #32
0
        public override void CheckIsoConformance(Object obj, IsoKey key, PdfResources resources, PdfStream contentStream
                                                 )
        {
            CanvasGraphicsState gState;
            PdfDictionary       currentColorSpaces = null;

            if (resources != null)
            {
                currentColorSpaces = resources.GetPdfObject().GetAsDictionary(PdfName.ColorSpace);
            }
            switch (key)
            {
            case IsoKey.CANVAS_STACK: {
                checker.CheckCanvasStack((char)obj);
                break;
            }

            case IsoKey.PDF_OBJECT: {
                checker.CheckPdfObject((PdfObject)obj);
                break;
            }

            case IsoKey.RENDERING_INTENT: {
                checker.CheckRenderingIntent((PdfName)obj);
                break;
            }

            case IsoKey.INLINE_IMAGE: {
                checker.CheckInlineImage((PdfStream)obj, currentColorSpaces);
                break;
            }

            case IsoKey.EXTENDED_GRAPHICS_STATE: {
                gState = (CanvasGraphicsState)obj;
                checker.CheckExtGState(gState, contentStream);
                break;
            }

            case IsoKey.FILL_COLOR: {
                gState = (CanvasGraphicsState)obj;
                checker.CheckColor(gState.GetFillColor(), currentColorSpaces, true, contentStream);
                break;
            }

            case IsoKey.PAGE: {
                checker.CheckSinglePage((PdfPage)obj);
                break;
            }

            case IsoKey.STROKE_COLOR: {
                gState = (CanvasGraphicsState)obj;
                checker.CheckColor(gState.GetStrokeColor(), currentColorSpaces, false, contentStream);
                break;
            }

            case IsoKey.TAG_STRUCTURE_ELEMENT: {
                checker.CheckTagStructureElement((PdfObject)obj);
                break;
            }

            case IsoKey.FONT_GLYPHS: {
                checker.CheckFontGlyphs(((CanvasGraphicsState)obj).GetFont(), contentStream);
                break;
            }
            }
        }
        public virtual void Invoke(PdfContentStreamProcessor pdfContentStreamProcessor, PdfLiteral oper, List <PdfObject> operands)
        {
            String         operatorStr   = oper.ToString();
            PdfContentByte canvas        = cleanUpStrategy.Context.Canvas;
            PRStream       xFormStream   = null;
            bool           disableOutput = pathConstructionOperators.Contains(operatorStr) || pathPaintingOperators.Contains(operatorStr) || clippingPathOperators.Contains(operatorStr);
            GraphicsState  gs            = pdfContentStreamProcessor.Gs();

            // key - number of a string in the TJ operator, value - number following the string; the first number without string (if it's presented) is stored under 0.
            // BE AWARE: zero-length strings are ignored!!!
            IDictionary <int, float> structuredTJoperands = null;

            if ("Do" == operatorStr)
            {
                if (operands.Count == 2 && operands[0].IsName())
                {
                    PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT);

                    if (xObjResources != null)
                    {
                        PdfStream xObj = xObjResources.GetAsStream((PdfName)operands[0]);

                        if (xObj is PRStream && xObj.GetAsName(PdfName.SUBTYPE) != null &&
                            xObj.GetAsName(PdfName.SUBTYPE).CompareTo(PdfName.FORM) == 0)
                        {
                            xFormStream = (PRStream)xObj;
                            cleanUpStrategy.RegisterNewContext(xObj.GetAsDict(PdfName.RESOURCES), null);
                        }
                    }
                }
            }

            originalContentOperator.Invoke(pdfContentStreamProcessor, oper, operands);
            IList <PdfCleanUpContentChunk> chunks = cleanUpStrategy.Chunks;

            if (xFormStream != null)
            {
                xFormStream.SetData(cleanUpStrategy.Context.Canvas.ToPdf(cleanUpStrategy.Context.Canvas.PdfWriter));
                cleanUpStrategy.PopContext();
                canvas = cleanUpStrategy.Context.Canvas;
            }

            if ("Do" == operatorStr)
            {
                if (chunks.Count > 0 && chunks[0] is PdfCleanUpContentChunk.Image)
                {
                    PdfCleanUpContentChunk.Image chunk = (PdfCleanUpContentChunk.Image)chunks[0];

                    if (chunk.Visible)
                    {
                        PdfDictionary xObjResources = cleanUpStrategy.Context.Resources.GetAsDict(PdfName.XOBJECT);
                        PRStream      imageStream   = (PRStream)xObjResources.GetAsStream((PdfName)operands[0]);
                        UpdateImageStream(imageStream, chunk.NewImageData);
                    }
                    else
                    {
                        disableOutput = true;
                    }
                }
            }
            else if (textShowingOperators.Contains(operatorStr) && !AllChunksAreVisible(cleanUpStrategy.Chunks))
            {
                disableOutput = true;

                if ("'" == operatorStr)
                {
                    canvas.InternalBuffer.Append(TStar);
                }
                else if ("\"" == operatorStr)
                {
                    operands[0].ToPdf(canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(Tw);

                    operands[1].ToPdf(canvas.PdfWriter, canvas.InternalBuffer);
                    canvas.InternalBuffer.Append(TcTStar);
                }
                else if ("TJ" == operatorStr)
                {
                    structuredTJoperands = StructureTJarray((PdfArray)operands[0]);
                }

                WriteTextChunks(structuredTJoperands, chunks, canvas, gs.CharacterSpacing, gs.WordSpacing,
                                gs.FontSize, gs.HorizontalScaling);
            }
            else if (pathPaintingOperators.Contains(operatorStr))
            {
                WritePath(operatorStr, canvas, gs.ColorSpaceStroke);
            }
            else if (strokeColorOperators.Contains(operatorStr))
            {
                // Replace current color with the new one.
                cleanUpStrategy.Context.PopStrokeColor();
                cleanUpStrategy.Context.PushStrokeColor(operands);
            }
            else if ("q" == operatorStr)
            {
                cleanUpStrategy.Context.PushStrokeColor(cleanUpStrategy.Context.PeekStrokeColor());
            }
            else if ("Q" == operatorStr)
            {
                cleanUpStrategy.Context.PopStrokeColor();
            }

            if (!disableOutput)
            {
                WriteOperands(canvas, operands);
            }

            cleanUpStrategy.ClearChunks();
        }
Пример #34
0
    /// <summary>
    /// Reads images that are returned from GDI+ without color palette.
    /// </summary>
    /// <param name="components">4 (32bpp RGB), 3 (24bpp RGB, 32bpp ARGB)</param>
    /// <param name="bits">8</param>
    /// <param name="hasAlpha">true (ARGB), false (RGB)</param>
    private void ReadTrueColorMemoryBitmap(int components, int bits, bool hasAlpha)
    {
#if DEBUG_
      image.image.Save("$$$.bmp", ImageFormat.Bmp);
#endif
      int pdfVersion = Owner.Version;
      MemoryStream memory = new MemoryStream();
#if GDI
      image.gdiImage.Save(memory, ImageFormat.Bmp);
#endif
#if WPF
#if !SILVERLIGHT
      // WPFTHHO: Bitte prüfen
      BmpBitmapEncoder encoder = new BmpBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(image.wpfImage));
      encoder.Save(memory);
#else
      // AGHACK
#endif
#endif
      int streamLength = (int)memory.Length;
      Debug.Assert(streamLength > 0, "Bitmap image encoding failed.");
      if (streamLength > 0)
      {
        byte[] imageBits = new byte[streamLength];
        memory.Seek(0, SeekOrigin.Begin);
        memory.Read(imageBits, 0, streamLength);
        memory.Close();

        int height = image.PixelHeight;
        int width = image.PixelWidth;

        // TODO: we could define structures for
        //   BITMAPFILEHEADER
        //   { BITMAPINFO }
        //   BITMAPINFOHEADER
        // to avoid ReadWord and ReadDWord ... (but w/o pointers this doesn't help much)

        if (ReadWord(imageBits, 0) != 0x4d42 || // "BM"
            ReadDWord(imageBits, 2) != streamLength ||
            ReadDWord(imageBits, 14) != 40 || // sizeof BITMAPINFOHEADER
            ReadDWord(imageBits, 18) != width ||
            ReadDWord(imageBits, 22) != height)
        {
          throw new NotImplementedException("ReadTrueColorMemoryBitmap: unsupported format");
        }
        if (ReadWord(imageBits, 26) != 1 ||
          (!hasAlpha && ReadWord(imageBits, 28) != components * bits ||
           hasAlpha && ReadWord(imageBits, 28) != (components + 1) * bits) ||
          ReadDWord(imageBits, 30) != 0)
        {
          throw new NotImplementedException("ReadTrueColorMemoryBitmap: unsupported format #2");
        }

        int nFileOffset = ReadDWord(imageBits, 10);
        int logicalComponents = components;
        if (components == 4)
          logicalComponents = 3;

        byte[] imageData = new byte[components * width * height];

        bool hasMask = false;
        bool hasAlphaMask = false;
        byte[] alphaMask = hasAlpha ? new byte[width * height] : null;
        MonochromeMask mask = hasAlpha ?
          new MonochromeMask(width, height) : null;

        int nOffsetRead = 0;
        if (logicalComponents == 3)
        {
          for (int y = 0; y < height; ++y)
          {
            int nOffsetWrite = 3 * (height - 1 - y) * width;
            int nOffsetWriteAlpha = 0;
            if (hasAlpha)
            {
              mask.StartLine(y);
              nOffsetWriteAlpha = (height - 1 - y) * width;
            }

            for (int x = 0; x < width; ++x)
            {
              imageData[nOffsetWrite] = imageBits[nFileOffset + nOffsetRead + 2];
              imageData[nOffsetWrite + 1] = imageBits[nFileOffset + nOffsetRead + 1];
              imageData[nOffsetWrite + 2] = imageBits[nFileOffset + nOffsetRead];
              if (hasAlpha)
              {
                mask.AddPel(imageBits[nFileOffset + nOffsetRead + 3]);
                alphaMask[nOffsetWriteAlpha] = imageBits[nFileOffset + nOffsetRead + 3];
                if (!hasMask || !hasAlphaMask)
                {
                  if (imageBits[nFileOffset + nOffsetRead + 3] != 255)
                  {
                    hasMask = true;
                    if (imageBits[nFileOffset + nOffsetRead + 3] != 0)
                      hasAlphaMask = true;
                  }
                }
                ++nOffsetWriteAlpha;
              }
              nOffsetRead += hasAlpha ? 4 : components;
              nOffsetWrite += 3;
            }
            nOffsetRead = 4 * ((nOffsetRead + 3) / 4); // Align to 32 bit boundary
          }
        }
        else if (components == 1)
        {
          // Grayscale
          throw new NotImplementedException("Image format not supported (grayscales).");
        }

        FlateDecode fd = new FlateDecode();
        if (hasMask)
        {
          // monochrome mask is either sufficient or
          // provided for compatibility with older reader versions
          byte[] maskDataCompressed = fd.Encode(mask.MaskData);
          PdfDictionary pdfMask = new PdfDictionary(document);
          pdfMask.Elements.SetName(Keys.Type, "/XObject");
          pdfMask.Elements.SetName(Keys.Subtype, "/Image");

          Owner.irefTable.Add(pdfMask);
          pdfMask.Stream = new PdfStream(maskDataCompressed, pdfMask);
          pdfMask.Elements[Keys.Length] = new PdfInteger(maskDataCompressed.Length);
          pdfMask.Elements[Keys.Filter] = new PdfName("/FlateDecode");
          pdfMask.Elements[Keys.Width] = new PdfInteger(width);
          pdfMask.Elements[Keys.Height] = new PdfInteger(height);
          pdfMask.Elements[Keys.BitsPerComponent] = new PdfInteger(1);
          pdfMask.Elements[Keys.ImageMask] = new PdfBoolean(true);
          Elements[Keys.Mask] = pdfMask.Reference;
        }
        if (hasMask && hasAlphaMask && pdfVersion >= 14)
        {
          // The image provides an alpha mask (requires Arcrobat 5.0 or higher)
          byte[] alphaMaskCompressed = fd.Encode(alphaMask);
          PdfDictionary smask = new PdfDictionary(document);
          smask.Elements.SetName(Keys.Type, "/XObject");
          smask.Elements.SetName(Keys.Subtype, "/Image");

          Owner.irefTable.Add(smask);
          smask.Stream = new PdfStream(alphaMaskCompressed, smask);
          smask.Elements[Keys.Length] = new PdfInteger(alphaMaskCompressed.Length);
          smask.Elements[Keys.Filter] = new PdfName("/FlateDecode");
          smask.Elements[Keys.Width] = new PdfInteger(width);
          smask.Elements[Keys.Height] = new PdfInteger(height);
          smask.Elements[Keys.BitsPerComponent] = new PdfInteger(8);
          smask.Elements[Keys.ColorSpace] = new PdfName("/DeviceGray");
          Elements[Keys.SMask] = smask.Reference;
        }

        byte[] imageDataCompressed = fd.Encode(imageData);

        Stream = new PdfStream(imageDataCompressed, this);
        Elements[Keys.Length] = new PdfInteger(imageDataCompressed.Length);
        Elements[Keys.Filter] = new PdfName("/FlateDecode");
        Elements[Keys.Width] = new PdfInteger(width);
        Elements[Keys.Height] = new PdfInteger(height);
        Elements[Keys.BitsPerComponent] = new PdfInteger(8);
        // TODO: CMYK
        Elements[Keys.ColorSpace] = new PdfName("/DeviceRGB");
        if (image.Interpolate)
          Elements[Keys.Interpolate] = PdfBoolean.True;
      }
    }
Пример #35
0
 /// <summary>
 /// Create
 /// <see cref="PdfFormXObject"/>
 /// instance by
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// .
 /// Note, this constructor doesn't perform any additional checks
 /// </summary>
 /// <param name="pdfStream">
 ///
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// with Form XObject.
 /// </param>
 /// <seealso cref="PdfXObject.MakeXObject(iText.Kernel.Pdf.PdfStream)"/>
 public PdfFormXObject(PdfStream pdfStream)
     : base(pdfStream)
 {
 }
Пример #36
0
        private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs)
        {
            writer.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
            PdfDictionary catalog = reader.Catalog;

            stp.MarkUsed(catalog);
            foreach (PdfName vkey in validated.Keys)
            {
                PdfArray      ocsp = new PdfArray();
                PdfArray      crl  = new PdfArray();
                PdfArray      cert = new PdfArray();
                PdfDictionary vri  = new PdfDictionary();
                foreach (byte[] b in validated[vkey].crls)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    crl.Add(iref);
                    crls.Add(iref);
                }
                foreach (byte[] b in validated[vkey].ocsps)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    ocsp.Add(iref);
                    ocsps.Add(iref);
                }
                foreach (byte[] b in validated[vkey].certs)
                {
                    PdfStream ps = new PdfStream(b);
                    ps.FlateCompress();
                    PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
                    cert.Add(iref);
                    certs.Add(iref);
                }
                if (ocsp.Size > 0)
                {
                    vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference);
                }
                if (crl.Size > 0)
                {
                    vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference);
                }
                if (cert.Size > 0)
                {
                    vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference);
                }
                vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference);
            }
            dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference);
            if (ocsps.Size > 0)
            {
                dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference);
            }
            if (crls.Size > 0)
            {
                dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference);
            }
            if (certs.Size > 0)
            {
                dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference);
            }
            catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference);
        }
Пример #37
0
 /// <summary>
 /// This method checks compliance with the inline image restrictions in the
 /// PDF/A specs, specifically filter parameters.
 /// </summary>
 /// <param name="inlineImage">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfStream"/>
 /// containing the inline image
 /// </param>
 /// <param name="currentColorSpaces">
 /// a
 /// <see cref="iText.Kernel.Pdf.PdfDictionary"/>
 /// containing the color spaces used in the document
 /// </param>
 public abstract void CheckInlineImage(PdfStream inlineImage, PdfDictionary currentColorSpaces);
Пример #38
0
 private static PdfDictionary CreateDictionaryFromMap(PdfStream stream, IDictionary <String, Object> parms)
 {
     if (parms != null)
     {
         PdfDictionary dictionary = new PdfDictionary();
         foreach (KeyValuePair <String, Object> entry in parms)
         {
             Object value = entry.Value;
             String key   = entry.Key;
             if (value is int?)
             {
                 dictionary.Put(new PdfName(key), new PdfNumber((int)value));
             }
             else
             {
                 if (value is float?)
                 {
                     dictionary.Put(new PdfName(key), new PdfNumber((float)value));
                 }
                 else
                 {
                     if (value is String)
                     {
                         if (value.Equals("Mask"))
                         {
                             dictionary.Put(PdfName.Mask, new PdfLiteral((String)value));
                         }
                         else
                         {
                             String str = (String)value;
                             if (str.IndexOf('/') == 0)
                             {
                                 dictionary.Put(new PdfName(key), new PdfName(str.Substring(1)));
                             }
                             else
                             {
                                 dictionary.Put(new PdfName(key), new PdfString(str));
                             }
                         }
                     }
                     else
                     {
                         if (value is byte[])
                         {
                             //TODO Check inline images
                             PdfStream globalsStream = new PdfStream();
                             globalsStream.GetOutputStream().WriteBytes((byte[])value);
                             dictionary.Put(PdfName.JBIG2Globals, globalsStream);
                         }
                         else
                         {
                             if (value is bool?)
                             {
                                 dictionary.Put(new PdfName(key), PdfBoolean.ValueOf((bool)value));
                             }
                             else
                             {
                                 if (value is Object[])
                                 {
                                     dictionary.Put(new PdfName(key), CreateArray(stream, (Object[])value));
                                 }
                                 else
                                 {
                                     if (value is float[])
                                     {
                                         dictionary.Put(new PdfName(key), new PdfArray((float[])value));
                                     }
                                     else
                                     {
                                         if (value is int[])
                                         {
                                             dictionary.Put(new PdfName(key), new PdfArray((int[])value));
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         return(dictionary);
     }
     return(null);
 }
Пример #39
0
 protected internal abstract void CheckImage(PdfStream image, PdfDictionary currentColorSpaces);
Пример #40
0
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        PdfDocument document = new PdfDocument();

        // Specify content stream's content as a sequence of content stream operands and operators.
        var content = new StringBuilder();

        // Begin a text object.
        content.AppendLine("BT");
        // Set the font and font size to use, installing them as parameters in the text state.
        // In this case, the font resource identified by the name F1 specifies the font externally known as Helvetica.
        content.AppendLine("/F1 12 Tf");
        // Specify a starting position on the page, setting parameters in the text object.
        content.AppendLine("70 760 Td");
        // Paint the glyphs for a string of characters at that position.
        content.AppendLine("(GemBox.Pdf) Tj");
        // End the text object.
        content.AppendLine("ET");

        // Create content stream and write content to it.
        var contentStream = PdfStream.Create();

        contentStream.Filters.AddFilter(PdfFilterType.FlateDecode);

        using (var stream = contentStream.Open(PdfStreamDataMode.Write, PdfStreamDataState.Decoded))
        {
            var contentBytes = PdfEncoding.Byte.GetBytes(content.ToString());
            stream.Write(contentBytes, 0, contentBytes.Length);
        }

        // Create font dictionary for Standard Type 1 'Helvetica' font.
        var font = PdfDictionary.Create();

        font[PdfName.Create("Type")]     = PdfName.Create("Font");
        font[PdfName.Create("Subtype")]  = PdfName.Create("Type1");
        font[PdfName.Create("BaseFont")] = PdfName.Create("Helvetica");

        // Add font dictionary to resources.
        var fontResources = PdfDictionary.Create();

        fontResources[PdfName.Create("F1")] = PdfIndirectObject.Create(font);

        var resources = PdfDictionary.Create();

        resources[PdfName.Create("Font")] = fontResources;

        // Create new empty A4 page.
        var page = document.Pages.Add();

        // Set contents and resources of a page.
        var pageDictionary = page.GetDictionary();

        pageDictionary[PdfName.Create("Contents")]  = PdfIndirectObject.Create(contentStream);
        pageDictionary[PdfName.Create("Resources")] = resources;

        document.SaveOptions.CloseOutput = true;
        document.Save("Content Stream.pdf");
    }
Пример #41
0
 protected internal abstract void CheckFormXObject(PdfStream form);
Пример #42
0
            public void HandleXObject(PdfContentStreamProcessor processor, PdfStream stream, PdfIndirectReference refi) {
                
                PdfDictionary resources = stream.GetAsDict(PdfName.RESOURCES);

                // we read the content bytes up here so if it fails we don't leave the graphics state stack corrupted
                // this is probably not necessary (if we fail on this, probably the entire content stream processing
                // operation should be rejected
                byte[] contentBytes;
                contentBytes = ContentByteUtils.GetContentBytesFromContentObject(stream);
                PdfArray matrix = stream.GetAsArray(PdfName.MATRIX);

                new PushGraphicsState().Invoke(processor, null, null);

                if (matrix != null){
                    float a = matrix.GetAsNumber(0).FloatValue;
                    float b = matrix.GetAsNumber(1).FloatValue;
                    float c = matrix.GetAsNumber(2).FloatValue;
                    float d = matrix.GetAsNumber(3).FloatValue;
                    float e = matrix.GetAsNumber(4).FloatValue;
                    float f = matrix.GetAsNumber(5).FloatValue;
                    Matrix formMatrix = new Matrix(a, b, c, d, e, f);

                    processor.Gs().ctm = formMatrix.Multiply(processor.Gs().ctm);
                }

                processor.ProcessContent(contentBytes, resources);

                new PopGraphicsState().Invoke(processor, null, null);
                
            }
Пример #43
0
 protected internal abstract void CheckPdfStream(PdfStream stream);
Пример #44
0
 public void HandleXObject(PdfContentStreamProcessor processor, PdfStream xobjectStream, PdfIndirectReference refi) {
     // ignore XObject subtype
 }
Пример #45
0
        protected internal virtual void CheckResources(PdfDictionary resources)
        {
            if (resources == null)
            {
                return;
            }
            PdfDictionary xObjects = resources.GetAsDictionary(PdfName.XObject);
            PdfDictionary shadings = resources.GetAsDictionary(PdfName.Shading);
            PdfDictionary patterns = resources.GetAsDictionary(PdfName.Pattern);

            if (xObjects != null)
            {
                foreach (PdfObject xObject in xObjects.Values())
                {
                    PdfStream xObjStream = (PdfStream)xObject;
                    PdfObject subtype    = null;
                    bool      isFlushed  = xObjStream.IsFlushed();
                    if (!isFlushed)
                    {
                        subtype = xObjStream.Get(PdfName.Subtype);
                    }
                    if (PdfName.Image.Equals(subtype) || isFlushed)
                    {
                        // if flushed still may be need to check colorspace in given context
                        CheckImage(xObjStream, resources.GetAsDictionary(PdfName.ColorSpace));
                    }
                    else
                    {
                        if (PdfName.Form.Equals(subtype))
                        {
                            CheckFormXObject(xObjStream);
                        }
                    }
                }
            }
            if (shadings != null)
            {
                foreach (PdfObject shading in shadings.Values())
                {
                    PdfDictionary shadingDict = (PdfDictionary)shading;
                    if (!IsAlreadyChecked(shadingDict))
                    {
                        CheckColorSpace(PdfColorSpace.MakeColorSpace(shadingDict.Get(PdfName.ColorSpace)), resources.GetAsDictionary
                                            (PdfName.ColorSpace), true, null);
                    }
                }
            }
            if (patterns != null)
            {
                foreach (PdfObject p in patterns.Values())
                {
                    if (p.IsStream())
                    {
                        PdfStream pStream = (PdfStream)p;
                        if (!IsAlreadyChecked(pStream))
                        {
                            CheckResources(pStream.GetAsDictionary(PdfName.Resources));
                        }
                    }
                }
            }
        }
Пример #46
0
 private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs) {
     writer.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5);
     PdfDictionary catalog = reader.Catalog;
     stp.MarkUsed(catalog);
     foreach (PdfName vkey in validated.Keys) {
         PdfArray ocsp = new PdfArray();
         PdfArray crl = new PdfArray();
         PdfArray cert = new PdfArray();
         PdfDictionary vri = new PdfDictionary();
         foreach (byte[] b in validated[vkey].crls) {
             PdfStream ps = new PdfStream(b);
             ps.FlateCompress();
             PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
             crl.Add(iref);
             crls.Add(iref);
         }
         foreach (byte[] b in validated[vkey].ocsps) {
             PdfStream ps = new PdfStream(b);
             ps.FlateCompress();
             PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
             ocsp.Add(iref);
             ocsps.Add(iref);
         }
         foreach (byte[] b in validated[vkey].certs) {
             PdfStream ps = new PdfStream(b);
             ps.FlateCompress();
             PdfIndirectReference iref = writer.AddToBody(ps, false).IndirectReference;
             cert.Add(iref);
             certs.Add(iref);
         }
         if (ocsp.Size > 0)
             vri.Put(PdfName.OCSP, writer.AddToBody(ocsp, false).IndirectReference);
         if (crl.Size > 0)
             vri.Put(PdfName.CRL, writer.AddToBody(crl, false).IndirectReference);
         if (cert.Size > 0)
             vri.Put(PdfName.CERT, writer.AddToBody(cert, false).IndirectReference);
         vrim.Put(vkey, writer.AddToBody(vri, false).IndirectReference);
     }
     dss.Put(PdfName.VRI, writer.AddToBody(vrim, false).IndirectReference);
     if (ocsps.Size > 0)
         dss.Put(PdfName.OCSPS, writer.AddToBody(ocsps, false).IndirectReference);
     if (crls.Size > 0)
         dss.Put(PdfName.CRLS, writer.AddToBody(crls, false).IndirectReference);
     if (certs.Size > 0)
         dss.Put(PdfName.CERTS, writer.AddToBody(certs, false).IndirectReference);
     catalog.Put(PdfName.DSS, writer.AddToBody(dss, false).IndirectReference);
 }
Пример #47
0
 public PdfStream GetPdfStream()
 {
     PdfStream stream = new PdfStream();
     stream.Dictionary.Add("Length", "0");
     stream.Ref = NextRef;
     Streams.Add(stream);
     return stream;
 }