private ImageRenderInfo(GraphicsState gs, PdfIndirectReference refi, PdfDictionary colorSpaceDictionary)
 {
     this.gs = gs;
     this.refi = refi;
     this.inlineImageInfo = null;
     this.colorSpaceDictionary = colorSpaceDictionary;
 }
 /**
  * Shows the detail of a dictionary.
  * @param dic   the dictionary of which you want the detail
  * @param depth the depth of the current dictionary (for nested dictionaries)
  * @return  a String representation of the dictionary
  */
 public static  String GetDictionaryDetail(PdfDictionary dic, int depth){
     StringBuilder builder = new StringBuilder();
     builder.Append('(');
     IList<PdfName> subDictionaries = new List<PdfName>();
     foreach (PdfName key in dic.Keys) {
         PdfObject val = dic.GetDirectObject(key);
         if (val.IsDictionary())
             subDictionaries.Add(key);
         builder.Append(key);
         builder.Append('=');
         builder.Append(val);
         builder.Append(", ");
     }
     builder.Length = builder.Length-2;
     builder.Append(')');
     foreach (PdfName pdfSubDictionaryName in subDictionaries) {
         builder.Append('\n');
         for (int i = 0; i < depth+1; i++){
             builder.Append('\t');
         }
         builder.Append("Subdictionary ");
         builder.Append(pdfSubDictionaryName);
         builder.Append(" = ");
         builder.Append(GetDictionaryDetail(dic.GetAsDict(pdfSubDictionaryName), depth+1));
     }
     return builder.ToString();
 }
Exemple #3
0
        private PdfStream(PdfDictionary dictionary, PdfData data)
            : base(PdfObjectType.Stream)
        {
            IsContainer = true;
            StreamDictionary = dictionary;
            Data = data;

            //IPdfObject filter = StreamDictionary["Filter"];
            //if (filter.Text == "FlateDecode")
            //{
            //    ZInputStream zin = new ZInputStream(new MemoryStream(Data));
            //    //zin.
            //    int r;
            //    IList<char> output = new List<char>(data.Length*10);
            //    while ((r = zin.Read()) != -1)
            //    {
            //        output.Add((char)r);
            //    }
            //    char[] decompressed = output.ToArray();
            //    String test = new String(decompressed);
            //    zin.Close();
            //}
            //else if (filter.Text == "DCTDecode")
            //{
            //    // JPEG image
            //}
            //else
            //    throw new NotImplementedException("Implement Filter");
        }
 private ImageRenderInfo(GraphicsState gs, InlineImageInfo inlineImageInfo, PdfDictionary colorSpaceDictionary)
 {
     this.gs = gs;
     this.refi = null;
     this.inlineImageInfo = inlineImageInfo;
     this.colorSpaceDictionary = colorSpaceDictionary;
 }
Exemple #5
0
   public PdfStream(
 PdfDictionary header
 )
       : this(header,
   new bytes.Buffer())
   {
   }
        /**
         * Creates an object that can inform you about the type of signature
         * in a signature dictionary as well as some of the permissions
         * defined by the signature.
         */
        public SignaturePermissions(PdfDictionary sigDict, SignaturePermissions previous)
        {
            if (previous != null) {
                annotationsAllowed &= previous.AnnotationsAllowed;
                fillInAllowed &= previous.FillInAllowed;
                fieldLocks.AddRange(previous.FieldLocks);
            }
            PdfArray reference = sigDict.GetAsArray(PdfName.REFERENCE);
            if (reference != null) {
                for (int i = 0; i < reference.Size; i++) {
                    PdfDictionary dict = reference.GetAsDict(i);
                    PdfDictionary parameters = dict.GetAsDict(PdfName.TRANSFORMPARAMS);
                    if (PdfName.DOCMDP.Equals(dict.GetAsName(PdfName.TRANSFORMMETHOD)))
                        certification = true;

                    PdfName action = parameters.GetAsName(PdfName.ACTION);
                    if (action != null)
                        fieldLocks.Add(new FieldLock(action, parameters.GetAsArray(PdfName.FIELDS)));

                    PdfNumber p = parameters.GetAsNumber(PdfName.P);
                    if (p == null)
                        continue;
                    switch (p.IntValue) {
                    case 1:
                        fillInAllowed = false;
                        break;
                    case 2:
                        annotationsAllowed = false;
                        break;
                    }
                }
            }
        }
Exemple #7
0
        /**
          <summary>Loads the encoding differences into the given collection.</summary>
          <param name="encodingDictionary">Encoding dictionary.</param>
          <param name="codes">Encoding to alter applying differences.</param>
        */
        protected void LoadEncodingDifferences(
      PdfDictionary encodingDictionary,
      IDictionary<ByteArray,int> codes
      )
        {
            PdfArray differenceObjects = (PdfArray)encodingDictionary.Resolve(PdfName.Differences);
              if(differenceObjects == null)
            return;

              /*
            NOTE: Each code is the first index in a sequence of character codes to be changed.
            The first character name after the code becomes the name corresponding to that code.
            Subsequent names replace consecutive code indices until the next code appears
            in the array or the array ends.
              */
              byte[] charCodeData = new byte[1];
              foreach(PdfDirectObject differenceObject in differenceObjects)
              {
            if(differenceObject is PdfInteger)
            {charCodeData[0] = (byte)(((int)((PdfInteger)differenceObject).Value) & 0xFF);}
            else // NOTE: MUST be PdfName.
            {
              ByteArray charCode = new ByteArray(charCodeData);
              string charName = (string)((PdfName)differenceObject).Value;
              if(charName.Equals(".notdef"))
              {codes.Remove(charCode);}
              else
              {
            int? code = GlyphMapping.NameToCode(charName);
            codes[charCode] = (code ?? charCodeData[0]);
              }
              charCodeData[0]++;
            }
              }
        }
Exemple #8
0
        public File(
      )
        {
            Initialize();

              version = VersionEnum.PDF14.GetVersion();
              trailer = PrepareTrailer(new PdfDictionary());
              indirectObjects = new IndirectObjects(this, null);
              document = new Document(this);
        }
 /**
  * Creates a StructureObject for an OBJR dictionary.
  * @param structElem	the parent structure element
  * @param ref			the reference of the parent structure element
  * @param dict			the object reference dictionary
  */
 public StructureObject(PdfDictionary structElem, PdfIndirectReference refa, PdfDictionary dict) {
     this.structElem = structElem;
     this.refa = refa;
     this.obj = dict.GetDirectObject(PdfName.OBJ);
     this.objref = dict.GetAsIndirectObject(PdfName.OBJ);
     this.structParent = ((PdfDictionary) obj).GetAsNumber(PdfName.STRUCTPARENT).IntValue;
     PdfIndirectReference pg = dict.GetAsIndirectObject(PdfName.PG);
     if (pg == null)
         pg = structElem.GetAsIndirectObject(PdfName.PG);
     this.pageref = pg.Number;
 }
Exemple #10
0
 public override byte[] Decode(
     byte[] data,
     int offset,
     int length,
     PdfDictionary parameters
     )
 {
     MemoryStream outputStream = new MemoryStream();
       MemoryStream inputStream = new MemoryStream(data, offset, length);
       DeflateStream inputFilter = new DeflateStream(inputStream, CompressionMode.Decompress);
       inputStream.Position = 2; // Skips zlib's 2-byte header [RFC 1950] [FIX:0.0.8:JCT].
       Transform(inputFilter,outputStream);
       return DecodePredictor(outputStream.ToArray(), parameters);
 }
Exemple #11
0
 protected override void CheckEmbeddedFile(PdfDictionary embeddedFile)
 {
     PdfObject _params = GetDirectObject(embeddedFile.Get(PdfName.PARAMS));
     if (_params == null) {
         throw new PdfAConformanceException(embeddedFile,
             MessageLocalization.GetComposedMessage("embedded.file.shall.contain.valid.params.key"));
     } else if (_params.IsDictionary()) {
         PdfObject modDate = ((PdfDictionary) _params).Get(PdfName.MODDATE);
         if (modDate == null || !(modDate is PdfString)) {
             throw new PdfAConformanceException(embeddedFile,
                 MessageLocalization.GetComposedMessage("embedded.file.shall.contain.params.key.with.valid.moddate.key"));
         }
     }
 }
Exemple #12
0
        public PdfStream(
      PdfDictionary header,
      IBuffer body
      )
        {
            this.header = (PdfDictionary)Include(header);

              this.body = body;
              body.Clean();
              body.OnChange += delegate(
            object sender,
            EventArgs args
            )
              {Update();};
        }
Exemple #13
0
 public override byte[] Encode(
     byte[] data,
     int offset,
     int length,
     PdfDictionary parameters
     )
 {
     MemoryStream inputStream = new MemoryStream(data, offset, length);
       MemoryStream outputStream = new MemoryStream();
       DeflateStream outputFilter = new DeflateStream(outputStream, CompressionMode.Compress, true);
       // Add zlib's 2-byte header [RFC 1950] [FIX:0.0.8:JCT]!
       outputStream.WriteByte(0x78); // CMF = {CINFO (bits 7-4) = 7; CM (bits 3-0) = 8} = 0x78.
       outputStream.WriteByte(0xDA); // FLG = {FLEVEL (bits 7-6) = 3; FDICT (bit 5) = 0; FCHECK (bits 4-0) = {31 - ((CMF * 256 + FLG - FCHECK) Mod 31)} = 26} = 0xDA.
       Transform(inputStream, outputFilter);
       return outputStream.ToArray();
 }
Exemple #14
0
 public PdfDictionary GetEncrypt(PdfObjectId objectId)
 {
     PdfDictionary encrypt = new PdfDictionary(objectId);
     encrypt[PdfName.Names.Filter] = PdfName.Names.Standard;
     encrypt[PdfName.Names.V] = new PdfNumeric(1);
     encrypt[PdfName.Names.Length] = new PdfNumeric(40);
     encrypt[PdfName.Names.R] = new PdfNumeric(2);
     PdfString o = new PdfString(ownerEntry);
     o.NeverEncrypt = true;
     encrypt[PdfName.Names.O] = o;
     PdfString u = new PdfString(userEntry);
     u.NeverEncrypt = true;
     encrypt[PdfName.Names.U] = u;
     encrypt[PdfName.Names.P] = new PdfNumeric(permissions);
     return encrypt;
 }
Exemple #15
0
        /// <summary>
        /// Initializes a new instance from an existing dictionary. Used for object type transformation.
        /// </summary>
        internal PdfObjectStream(PdfDictionary dict)
            : base(dict)
        {
            int n = Elements.GetInteger(Keys.N);
            int first = Elements.GetInteger(Keys.First);
            Stream.TryUnfilter();

            Parser parser = new Parser(null, new MemoryStream(Stream.Value));
            _header = parser.ReadObjectStreamHeader(n, first);

#if DEBUG && CORE
            if (Internal.PdfDiagnostics.TraceObjectStreams)
            {
                Debug.WriteLine(String.Format("PdfObjectStream(document) created. Header item count: {0}", _header.GetLength(0)));
            }
#endif
        }
Exemple #16
0
        public PdfCIDFont(PdfDocument document, PdfFontDescriptor fontDescriptor, byte[] fontData)
            : base(document)
        {
            Elements.SetName(Keys.Type, "/Font");
            Elements.SetName(Keys.Subtype, "/CIDFontType2");
            PdfDictionary cid = new PdfDictionary();
            cid.Elements.SetString("/Ordering", "Identity");
            cid.Elements.SetString("/Registry", "Adobe");
            cid.Elements.SetInteger("/Supplement", 0);
            Elements.SetValue(Keys.CIDSystemInfo, cid);

            FontDescriptor = fontDescriptor;
            // ReSharper disable once DoNotCallOverridableMethodsInConstructor
            Owner._irefTable.Add(fontDescriptor);
            Elements[Keys.FontDescriptor] = fontDescriptor.Reference;

            FontEncoding = PdfFontEncoding.Unicode;
        }
Exemple #17
0
        public static PdfStream Parse(PdfDictionary dictionary, Lexical.ILexer lexer)
        {
            lexer.Expects("stream");
            char eol = lexer.ReadChar();
            if (eol == '\r')
                eol = lexer.ReadChar();
            if (eol != '\n')
                throw new Exception(@"Parser error: stream needs to be followed by either \r\n or \n alone");

            if (dictionary == null)
                throw new Exception("Parser error: stream needs a dictionary");

            IPdfObject lengthObject = dictionary["Length"];
            if (lengthObject == null)
                throw new Exception("Parser error: stream dictionary requires a Length entry");

            int length = 0;
            if (lengthObject is PdfIndirectReference)
            {
                PdfIndirectReference reference = lengthObject as PdfIndirectReference;

                PdfIndirectObject lenobj = lexer.IndirectReferenceResolver
                    .GetObject(reference.ObjectNumber, reference.GenerationNumber);

                PdfNumeric len = lenobj.Object as PdfNumeric;
                length = int.Parse(len.ToString());
            }
            else
            {
                length = int.Parse(lengthObject.ToString());
            }

            PdfData data = PdfData.Parse(lexer, length);
            lexer.Expects("endstream");

            return new PdfStream(dictionary, data);
        }
Exemple #18
0
        private byte[] DecodePredictor(
            byte[] data,
            PdfDictionary parameters
            )
        {
            if (parameters == null)
            {
                return(data);
            }

            int predictor = (parameters.ContainsKey(PdfName.Predictor) ? ((PdfInteger)parameters[PdfName.Predictor]).RawValue : 1);

            if (predictor == 1) // No predictor was applied during data encoding.
            {
                return(data);
            }

            int sampleComponentBitsCount = (parameters.ContainsKey(PdfName.BitsPerComponent) ? ((PdfInteger)parameters[PdfName.BitsPerComponent]).RawValue : 8);
            int sampleComponentsCount    = (parameters.ContainsKey(PdfName.Colors) ? ((PdfInteger)parameters[PdfName.Colors]).RawValue : 1);
            int rowSamplesCount          = (parameters.ContainsKey(PdfName.Columns) ? ((PdfInteger)parameters[PdfName.Columns]).RawValue : 1);

            MemoryStream input  = new MemoryStream(data);
            MemoryStream output = new MemoryStream();

            switch (predictor)
            {
            case 2: // TIFF Predictor 2 (component-based).
            {
                int[] sampleComponentPredictions = new int[sampleComponentsCount];
                int   sampleComponentDelta       = 0;
                int   sampleComponentIndex       = 0;
                while ((sampleComponentDelta = input.ReadByte()) != -1)
                {
                    int sampleComponent = sampleComponentDelta + sampleComponentPredictions[sampleComponentIndex];
                    output.WriteByte((byte)sampleComponent);

                    sampleComponentPredictions[sampleComponentIndex] = sampleComponent;

                    sampleComponentIndex = ++sampleComponentIndex % sampleComponentsCount;
                }
                break;
            }

            default:                                                                                                                                              // PNG Predictors [RFC 2083] (byte-based).
            {
                int   sampleBytesCount           = (int)Math.Ceiling(sampleComponentBitsCount * sampleComponentsCount / 8d);                                      // Number of bytes per pixel (bpp).
                int   rowSampleBytesCount        = (int)Math.Ceiling(sampleComponentBitsCount * sampleComponentsCount * rowSamplesCount / 8d) + sampleBytesCount; // Number of bytes per row (comprising a leading upper-left sample (see Paeth method)).
                int[] previousRowBytePredictions = new int[rowSampleBytesCount];
                int[] currentRowBytePredictions  = new int[rowSampleBytesCount];
                int[] leftBytePredictions        = new int[sampleBytesCount];
                int   predictionMethod;
                while ((predictionMethod = input.ReadByte()) != -1)
                {
                    Array.Copy(currentRowBytePredictions, 0, previousRowBytePredictions, 0, currentRowBytePredictions.Length);
                    Array.Clear(leftBytePredictions, 0, leftBytePredictions.Length);
                    for (
                        int rowSampleByteIndex = sampleBytesCount; // Starts after the leading upper-left sample (see Paeth method).
                        rowSampleByteIndex < rowSampleBytesCount;
                        rowSampleByteIndex++
                        )
                    {
                        int byteDelta = input.ReadByte();

                        int sampleByteIndex = rowSampleByteIndex % sampleBytesCount;

                        int sampleByte;
                        switch (predictionMethod)
                        {
                        case 0: // None (no prediction).
                            sampleByte = byteDelta;
                            break;

                        case 1: // Sub (predicts the same as the sample to the left).
                            sampleByte = byteDelta + leftBytePredictions[sampleByteIndex];
                            break;

                        case 2: // Up (predicts the same as the sample above).
                            sampleByte = byteDelta + previousRowBytePredictions[rowSampleByteIndex];
                            break;

                        case 3: // Average (predicts the average of the sample to the left and the sample above).
                            sampleByte = byteDelta + (int)Math.Floor(((leftBytePredictions[sampleByteIndex] + previousRowBytePredictions[rowSampleByteIndex])) / 2d);
                            break;

                        case 4: // Paeth (a nonlinear function of the sample above, the sample to the left, and the sample to the upper left).
                        {
                            int paethPrediction;
                            {
                                int leftBytePrediction    = leftBytePredictions[sampleByteIndex];
                                int topBytePrediction     = previousRowBytePredictions[rowSampleByteIndex];
                                int topLeftBytePrediction = previousRowBytePredictions[rowSampleByteIndex - sampleBytesCount];
                                int initialPrediction     = leftBytePrediction + topBytePrediction - topLeftBytePrediction;
                                int leftPrediction        = Math.Abs(initialPrediction - leftBytePrediction);
                                int topPrediction         = Math.Abs(initialPrediction - topBytePrediction);
                                int topLeftPrediction     = Math.Abs(initialPrediction - topLeftBytePrediction);
                                if (leftPrediction <= topPrediction &&
                                    leftPrediction <= topLeftPrediction)
                                {
                                    paethPrediction = leftBytePrediction;
                                }
                                else if (topPrediction <= topLeftPrediction)
                                {
                                    paethPrediction = topBytePrediction;
                                }
                                else
                                {
                                    paethPrediction = topLeftBytePrediction;
                                }
                            }
                            sampleByte = byteDelta + paethPrediction;
                            break;
                        }

                        default:
                            throw new NotSupportedException("Prediction method " + predictionMethod + " unknown.");
                        }
                        output.WriteByte((byte)sampleByte);

                        leftBytePredictions[sampleByteIndex] = currentRowBytePredictions[rowSampleByteIndex] = sampleByte;
                    }
                }
                break;
            }
            }
            return(output.ToArray());
        }
 /**
  * Create an ImageRenderInfo object based on an XObject (this is the most common way of including an image in PDF)
  * @param ctm the coordinate transformation matrix at the time the image is rendered
  * @param ref a reference to the image XObject
  * @return the ImageRenderInfo representing the rendered XObject
  * @since 5.0.1
  */
 public static ImageRenderInfo CreateForXObject(GraphicsState gs, PdfIndirectReference refi, PdfDictionary colorSpaceDictionary)
 {
     return(new ImageRenderInfo(gs, refi, colorSpaceDictionary, null));
 }
Exemple #20
0
        protected static Image GetTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s)
        {
            int            predictor   = 1;
            TIFFLZWDecoder lzwDecoder  = null;
            int            compression = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION);

            switch (compression)
            {
            case TIFFConstants.COMPRESSION_NONE:
            case TIFFConstants.COMPRESSION_LZW:
            case TIFFConstants.COMPRESSION_PACKBITS:
            case TIFFConstants.COMPRESSION_DEFLATE:
            case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
            case TIFFConstants.COMPRESSION_OJPEG:
            case TIFFConstants.COMPRESSION_JPEG:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("the.compression.1.is.not.supported", compression));
            }
            int photometric = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC);

            switch (photometric)
            {
            case TIFFConstants.PHOTOMETRIC_MINISWHITE:
            case TIFFConstants.PHOTOMETRIC_MINISBLACK:
            case TIFFConstants.PHOTOMETRIC_RGB:
            case TIFFConstants.PHOTOMETRIC_SEPARATED:
            case TIFFConstants.PHOTOMETRIC_PALETTE:
                break;

            default:
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("the.photometric.1.is.not.supported", photometric));
                }
                break;
            }
            float rotation = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ORIENTATION))
            {
                int rot = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION);
                if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT)
                {
                    rotation = (float)Math.PI;
                }
                else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT)
                {
                    rotation = (float)(Math.PI / 2.0);
                }
                else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT)
                {
                    rotation = -(float)(Math.PI / 2.0);
                }
            }

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) &&
                dir.GetFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("planar.images.are.not.supported"));
            }
            int extraSamples = 0;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES))
            {
                extraSamples = 1;
            }
            int samplePerPixel = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4
            {
                samplePerPixel = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL);
            }
            int bitsPerSample = 1;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE))
            {
                bitsPerSample = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE);
            }
            switch (bitsPerSample)
            {
            case 1:
            case 2:
            case 4:
            case 8:
                break;

            default:
                throw new ArgumentException(MessageLocalization.GetComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample));
            }
            Image img = null;

            int h              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH);
            int w              = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH);
            int dpiX           = 0;
            int dpiY           = 0;
            int resolutionUnit = TIFFConstants.RESUNIT_INCH;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT))
            {
                resolutionUnit = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT);
            }
            dpiX = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit);
            dpiY = GetDpi(dir.GetField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit);
            int       fillOrder      = 1;
            bool      reverse        = false;
            TIFFField fillOrderField = dir.GetField(TIFFConstants.TIFFTAG_FILLORDER);

            if (fillOrderField != null)
            {
                fillOrder = fillOrderField.GetAsInt(0);
            }
            reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB);
            int rowsStrip = h;

            if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs
            {
                rowsStrip = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP);
            }
            if (rowsStrip <= 0 || rowsStrip > h)
            {
                rowsStrip = h;
            }
            long[] offset = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS);
            long[] size   = GetArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS);
            if ((size == null || (size.Length == 1 && (size[0] == 0 || size[0] + offset[0] > s.Length))) && h == rowsStrip)   // some TIFF producers are really lousy, so...
            {
                size = new long[] { s.Length - (int)offset[0] };
            }
            if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE)
            {
                TIFFField predictorField = dir.GetField(TIFFConstants.TIFFTAG_PREDICTOR);
                if (predictorField != null)
                {
                    predictor = predictorField.GetAsInt(0);
                    if (predictor != 1 && predictor != 2)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("illegal.value.for.predictor.in.tiff.file"));
                    }
                    if (predictor == 2 && bitsPerSample != 8)
                    {
                        throw new Exception(MessageLocalization.GetComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample));
                    }
                }
            }
            if (compression == TIFFConstants.COMPRESSION_LZW)
            {
                lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel);
            }
            int                   rowsLeft = h;
            MemoryStream          stream   = null;
            MemoryStream          mstream  = null;
            ZDeflaterOutputStream zip      = null;
            ZDeflaterOutputStream mzip     = null;

            if (extraSamples > 0)
            {
                mstream = new MemoryStream();
                mzip    = new ZDeflaterOutputStream(mstream);
            }

            CCITTG4Encoder g4 = null;

            if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
            {
                g4 = new CCITTG4Encoder(w);
            }
            else
            {
                stream = new MemoryStream();
                if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
                {
                    zip = new ZDeflaterOutputStream(stream);
                }
            }
            if (compression == TIFFConstants.COMPRESSION_OJPEG)
            {
                // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and
                // is often missing

                if ((!dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET)))
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("missing.tag.s.for.ojpeg.compression"));
                }
                int jpegOffset = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET);
                int jpegLength = (int)s.Length - jpegOffset;

                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT))
                {
                    jpegLength = (int)dir.GetFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) +
                                 (int)size[0];
                }

                byte[] jpeg = new byte[Math.Min(jpegLength, s.Length - jpegOffset)];

                int posFilePointer = (int)s.FilePointer;
                posFilePointer += jpegOffset;
                s.Seek(posFilePointer);
                s.ReadFully(jpeg);
                // if quantization and/or Huffman tables are stored separately in the tiff,
                // we need to add them to the jpeg data
                TIFFField jpegtables = dir.GetField(TIFFConstants.TIFFTAG_JPEGTABLES);
                if (jpegtables != null)
                {
                    byte[] temp        = jpegtables.GetAsBytes();
                    int    tableoffset = 0;
                    int    tablelength = temp.Length;
                    // remove FFD8 from start
                    if (temp[0] == (byte)0xFF && temp[1] == (byte)0xD8)
                    {
                        tableoffset  = 2;
                        tablelength -= 2;
                    }
                    // remove FFD9 from end
                    if (temp[temp.Length - 2] == (byte)0xFF && temp[temp.Length - 1] == (byte)0xD9)
                    {
                        tablelength -= 2;
                    }
                    byte[] tables = new byte[tablelength];
                    Array.Copy(temp, tableoffset, tables, 0, tablelength);
                    // TODO insert after JFIF header, instead of at the start
                    byte[] jpegwithtables = new byte[jpeg.Length + tables.Length];
                    Array.Copy(jpeg, 0, jpegwithtables, 0, 2);
                    Array.Copy(tables, 0, jpegwithtables, 2, tables.Length);
                    Array.Copy(jpeg, 2, jpegwithtables, tables.Length + 2, jpeg.Length - 2);
                    jpeg = jpegwithtables;
                }
                img = new Jpeg(jpeg);
            }
            else if (compression == TIFFConstants.COMPRESSION_JPEG)
            {
                if (size.Length > 1)
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.Length));
                }
                byte[] jpeg = new byte[(int)size[0]];
                s.Seek(offset[0]);
                s.ReadFully(jpeg);
                img = new Jpeg(jpeg);
            }
            else
            {
                for (int k = 0; k < offset.Length; ++k)
                {
                    byte[] im = new byte[(int)size[k]];
                    s.Seek(offset[k]);
                    s.ReadFully(im);
                    int    height = Math.Min(rowsStrip, rowsLeft);
                    byte[] outBuf = null;
                    if (compression != TIFFConstants.COMPRESSION_NONE)
                    {
                        outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height];
                    }
                    if (reverse)
                    {
                        TIFFFaxDecoder.ReverseBits(im);
                    }
                    switch (compression)
                    {
                    case TIFFConstants.COMPRESSION_DEFLATE:
                    case TIFFConstants.COMPRESSION_ADOBE_DEFLATE:
                        Inflate(im, outBuf);
                        ApplyPredictor(outBuf, predictor, w, height, samplePerPixel);
                        break;

                    case TIFFConstants.COMPRESSION_NONE:
                        outBuf = im;
                        break;

                    case TIFFConstants.COMPRESSION_PACKBITS:
                        DecodePackbits(im, outBuf);
                        break;

                    case TIFFConstants.COMPRESSION_LZW:
                        lzwDecoder.Decode(im, outBuf, height);
                        break;
                    }
                    if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                    {
                        g4.Fax4Encode(outBuf, height);
                    }
                    else
                    {
                        if (extraSamples > 0)
                        {
                            ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height);
                        }
                        else
                        {
                            zip.Write(outBuf, 0, outBuf.Length);
                        }
                    }
                    rowsLeft -= rowsStrip;
                }
                if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE)
                {
                    img = Image.GetInstance(w, h, false, Image.CCITTG4,
                                            photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.Close());
                }
                else
                {
                    zip.Close();
                    img          = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.ToArray());
                    img.Deflated = true;
                }
            }
            img.SetDpi(dpiX, dpiY);
            if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG)
            {
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE))
                {
                    try {
                        TIFFField   fd       = dir.GetField(TIFFConstants.TIFFTAG_ICCPROFILE);
                        ICC_Profile icc_prof = ICC_Profile.GetInstance(fd.GetAsBytes());
                        if (samplePerPixel - extraSamples == icc_prof.NumComponents)
                        {
                            img.TagICC = icc_prof;
                        }
                    }
                    catch {
                        //empty
                    }
                }
                if (dir.IsTagPresent(TIFFConstants.TIFFTAG_COLORMAP))
                {
                    TIFFField fd      = dir.GetField(TIFFConstants.TIFFTAG_COLORMAP);
                    char[]    rgb     = fd.GetAsChars();
                    byte[]    palette = new byte[rgb.Length];
                    int       gColor  = rgb.Length / 3;
                    int       bColor  = gColor * 2;
                    for (int k = 0; k < gColor; ++k)
                    {
                        palette[k * 3]     = (byte)(rgb[k] >> 8);
                        palette[k * 3 + 1] = (byte)(rgb[k + gColor] >> 8);
                        palette[k * 3 + 2] = (byte)(rgb[k + bColor] >> 8);
                    }
                    // Colormap components are supposed to go from 0 to 655535 but,
                    // as usually, some tiff producers just put values from 0 to 255.
                    // Let's check for these broken tiffs.
                    bool colormapBroken = true;
                    for (int k = 0; k < palette.Length; ++k)
                    {
                        if (palette[k] != 0)
                        {
                            colormapBroken = false;
                            break;
                        }
                    }
                    if (colormapBroken)
                    {
                        for (int k = 0; k < gColor; ++k)
                        {
                            palette[k * 3]     = (byte)rgb[k];
                            palette[k * 3 + 1] = (byte)rgb[k + gColor];
                            palette[k * 3 + 2] = (byte)rgb[k + bColor];
                        }
                    }
                    PdfArray indexed = new PdfArray();
                    indexed.Add(PdfName.INDEXED);
                    indexed.Add(PdfName.DEVICERGB);
                    indexed.Add(new PdfNumber(gColor - 1));
                    indexed.Add(new PdfString(palette));
                    PdfDictionary additional = new PdfDictionary();
                    additional.Put(PdfName.COLORSPACE, indexed);
                    img.Additional = additional;
                }
                img.OriginalType = Image.ORIGINAL_TIFF;
            }
            if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE)
            {
                img.Inverted = true;
            }
            if (rotation != 0)
            {
                img.InitialRotation = rotation;
            }
            if (extraSamples > 0)
            {
                mzip.Close();
                Image mimg = Image.GetInstance(w, h, 1, bitsPerSample, mstream.ToArray());
                mimg.MakeMask();
                mimg.Deflated = true;
                img.ImageMask = mimg;
            }
            return(img);
        }
Exemple #21
0
 internal PdfSignatureField(PdfDictionary dict)
     : base(dict)
 {
 }
        private void OutputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs)
        {
            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);
        }
Exemple #23
0
 public Shading(PdfDictionary pdfObject)
     : base(pdfObject)
 {
 }
 private String GetParentIndRefStr(PdfDictionary dict)
 {
     return(dict.GetAsIndirectObject(PdfName.PARENT).ToString());
 }
Exemple #25
0
   /**
     <summary>Parses the current PDF object [PDF:1.6:3.2].</summary>
   */
   public virtual PdfDataObject ParsePdfObject(
 )
   {
       switch(TokenType)
         {
       case TokenTypeEnum.Integer:
         return PdfInteger.Get((int)Token);
       case TokenTypeEnum.Name:
         return new PdfName((string)Token,true);
       case TokenTypeEnum.DictionaryBegin:
       {
         PdfDictionary dictionary = new PdfDictionary();
         dictionary.Updateable = false;
         while(true)
         {
       // Key.
       MoveNext(); if(TokenType == TokenTypeEnum.DictionaryEnd) break;
       PdfName key = (PdfName)ParsePdfObject();
       // Value.
       MoveNext();
       PdfDirectObject value = (PdfDirectObject)ParsePdfObject();
       // Add the current entry to the dictionary!
       dictionary[key] = value;
         }
         dictionary.Updateable = true;
         return dictionary;
       }
       case TokenTypeEnum.ArrayBegin:
       {
         PdfArray array = new PdfArray();
         array.Updateable = false;
         while(true)
         {
       // Value.
       MoveNext(); if(TokenType == TokenTypeEnum.ArrayEnd) break;
       // Add the current item to the array!
       array.Add((PdfDirectObject)ParsePdfObject());
         }
         array.Updateable = true;
         return array;
       }
       case TokenTypeEnum.Literal:
         if(Token is DateTime)
       return PdfDate.Get((DateTime)Token);
         else
       return new PdfTextString(
         Encoding.Pdf.Encode((string)Token)
         );
       case TokenTypeEnum.Hex:
         return new PdfTextString(
       (string)Token,
       PdfString.SerializationModeEnum.Hex
       );
       case TokenTypeEnum.Real:
         return PdfReal.Get((double)Token);
       case TokenTypeEnum.Boolean:
         return PdfBoolean.Get((bool)Token);
       case TokenTypeEnum.Null:
         return null;
       default:
         throw new Exception("Unknown type: " + TokenType);
         }
   }
Exemple #26
0
 /**
   <summary>Gets the Javascript script from the specified base data object.</summary>
 */
 internal static string GetScript(
     PdfDictionary baseDataObject,
     PdfName key
     )
 {
     PdfDataObject scriptObject = baseDataObject.Resolve(key);
       if(scriptObject == null)
     return null;
       else if(scriptObject is PdfTextString)
     return ((PdfTextString)scriptObject).StringValue;
       else
       {
     bytes::IBuffer scriptBuffer = ((PdfStream)scriptObject).Body;
     return scriptBuffer.GetString(0,(int)scriptBuffer.Length);
       }
 }
 /// <summary>
 /// see
 /// <see cref="PdfAnnotation.MakeAnnotation(iText.Kernel.Pdf.PdfObject)"/>
 /// </summary>
 protected internal PdfTextAnnotation(PdfDictionary pdfObject)
     : base(pdfObject)
 {
 }
Exemple #28
0
 internal PdfStandardSecurityHandler(PdfDictionary dict)
     : base(dict)
 {
 }
 internal virtual Object GetObjForStructDict(PdfDictionary structDict)
 {
     return(waitingTagToAssociatedObj.Get(structDict));
 }
Exemple #30
0
 /// <summary>
 /// Initializes a new instance from an existing dictionary. Used for object type transformation.
 /// </summary>
 protected PdfDictionaryWithContentStream(PdfDictionary dict)
     : base(dict)
 {
 }
 public PdfUserPropertiesAttributes(PdfDictionary attributesDict)
     : base(attributesDict)
 {
 }
        /**
         * Extracts locations from the redact annotations contained in the document and applied to the given page.
         */
        private IList <PdfCleanUpLocation> ExtractLocationsFromRedactAnnots(int page, PdfDictionary pageDict)
        {
            List <PdfCleanUpLocation> locations = new List <PdfCleanUpLocation>();

            if (pageDict.Contains(PdfName.ANNOTS))
            {
                PdfArray annotsArray = pageDict.GetAsArray(PdfName.ANNOTS);

                for (int i = 0; i < annotsArray.Size; ++i)
                {
                    PdfIndirectReference annotIndirRef = annotsArray.GetAsIndirectObject(i);
                    PdfDictionary        annotDict     = annotsArray.GetAsDict(i);
                    PdfName annotSubtype = annotDict.GetAsName(PdfName.SUBTYPE);

                    if (annotSubtype.Equals(PdfName.REDACT))
                    {
                        SaveRedactAnnotIndirRef(page, annotIndirRef.ToString());
                        locations.AddRange(ExtractLocationsFromRedactAnnot(page, i, annotDict));
                    }
                }
            }

            return(locations);
        }
        /**
         * Extracts locations from the concrete annotation.
         * Note: annotation can consist not only of one area specified by the RECT entry, but also of multiple areas specified
         * by the QuadPoints entry in the annotation dictionary.
         */
        private IList <PdfCleanUpLocation> ExtractLocationsFromRedactAnnot(int page, int annotIndex, PdfDictionary annotDict)
        {
            IList <PdfCleanUpLocation> locations        = new List <PdfCleanUpLocation>();
            List <Rectangle>           markedRectangles = new List <Rectangle>();
            PdfArray quadPoints = annotDict.GetAsArray(PdfName.QUADPOINTS);

            if (quadPoints.Size != 0)
            {
                markedRectangles.AddRange(TranslateQuadPointsToRectangles(quadPoints));
            }
            else
            {
                PdfArray annotRect = annotDict.GetAsArray(PdfName.RECT);
                markedRectangles.Add(new Rectangle(annotRect.GetAsNumber(0).FloatValue,
                                                   annotRect.GetAsNumber(1).FloatValue,
                                                   annotRect.GetAsNumber(2).FloatValue,
                                                   annotRect.GetAsNumber(3).FloatValue));
            }

            clippingRects.Add(annotIndex, markedRectangles);

            BaseColor cleanUpColor = null;
            PdfArray  ic           = annotDict.GetAsArray(PdfName.IC);

            if (ic != null)
            {
                cleanUpColor = new BaseColor(
                    ic.GetAsNumber(0).FloatValue,
                    ic.GetAsNumber(1).FloatValue,
                    ic.GetAsNumber(2).FloatValue
                    );
            }


            PdfStream ro = annotDict.GetAsStream(PdfName.RO);

            if (ro != null)
            {
                cleanUpColor = null;
            }

            foreach (Rectangle rect in markedRectangles)
            {
                locations.Add(new PdfCleanUpLocation(page, rect, cleanUpColor));
            }

            return(locations);
        }
Exemple #34
0
 public PdfObjRef(PdfDictionary pdfObject, PdfStructElem parent)
     : base(pdfObject, parent)
 {
 }
 public ElementIndexer(PdfDictionary searchedBead)
 {
     this.searchedBead = searchedBead;
 }
Exemple #36
0
        private void Apply(
            CheckBox field
            )
        {
            Document document = field.Document;

            foreach (Widget widget in field.Widgets)
            {
                {
                    PdfDictionary widgetDataObject = widget.BaseDataObject;
                    widgetDataObject[PdfName.DA] = new PdfString("/ZaDb 0 Tf 0 0 0 rg");
                    widgetDataObject[PdfName.MK] = new PdfDictionary(
                        new PdfName[]
                    {
                        PdfName.BG,
                        PdfName.BC,
                        PdfName.CA
                    },
                        new PdfDirectObject[]
                    {
                        new PdfArray(new PdfDirectObject[] { PdfReal.Get(0.9412), PdfReal.Get(0.9412), PdfReal.Get(0.9412) }),
                        new PdfArray(new PdfDirectObject[] { PdfInteger.Default, PdfInteger.Default, PdfInteger.Default }),
                        new PdfString("4")
                    }
                        );
                    widgetDataObject[PdfName.BS] = new PdfDictionary(
                        new PdfName[]
                    {
                        PdfName.W,
                        PdfName.S
                    },
                        new PdfDirectObject[]
                    {
                        PdfReal.Get(0.8),
                        PdfName.S
                    }
                        );
                    widgetDataObject[PdfName.H] = PdfName.P;
                }

                Appearance       appearance       = widget.Appearance;
                AppearanceStates normalAppearance = appearance.Normal;
                SizeF            size             = widget.Box.Size;
                FormXObject      onState          = new FormXObject(document, size);
                normalAppearance[PdfName.Yes] = onState;

                //TODO:verify!!!
                //   appearance.getRollover().put(PdfName.Yes,onState);
                //   appearance.getDown().put(PdfName.Yes,onState);
                //   appearance.getRollover().put(PdfName.Off,offState);
                //   appearance.getDown().put(PdfName.Off,offState);

                float      lineWidth = 1;
                RectangleF frame     = new RectangleF(lineWidth / 2, lineWidth / 2, size.Width - lineWidth, size.Height - lineWidth);
                {
                    PrimitiveComposer composer = new PrimitiveComposer(onState);

                    if (GraphicsVisibile)
                    {
                        composer.BeginLocalState();
                        composer.SetLineWidth(lineWidth);
                        composer.SetFillColor(BackColor);
                        composer.SetStrokeColor(ForeColor);
                        composer.DrawRectangle(frame, 5);
                        composer.FillStroke();
                        composer.End();
                    }

                    BlockComposer blockComposer = new BlockComposer(composer);
                    blockComposer.Begin(frame, XAlignmentEnum.Center, YAlignmentEnum.Middle);
                    composer.SetFillColor(ForeColor);
                    composer.SetFont(
                        new StandardType1Font(
                            document,
                            StandardType1Font.FamilyEnum.ZapfDingbats,
                            true,
                            false
                            ),
                        size.Height * 0.8
                        );
                    blockComposer.ShowText(new String(new char[] { CheckSymbol }));
                    blockComposer.End();

                    composer.Flush();
                }

                FormXObject offState = new FormXObject(document, size);
                normalAppearance[PdfName.Off] = offState;
                {
                    if (GraphicsVisibile)
                    {
                        PrimitiveComposer composer = new PrimitiveComposer(offState);

                        composer.BeginLocalState();
                        composer.SetLineWidth(lineWidth);
                        composer.SetFillColor(BackColor);
                        composer.SetStrokeColor(ForeColor);
                        composer.DrawRectangle(frame, 5);
                        composer.FillStroke();
                        composer.End();

                        composer.Flush();
                    }
                }
            }
        }
        public JObject ObtenerFiguras(string nombrePDF)
        {
            string oldFile = nombrePDF;
            //string newFile = "C:\\Users\\Denisse\\Desktop\\EDDIE-Augmented-Reading-master\\AugmentedReadingApp\\bin\\x86\\Debug\\temporal.pdf"
            PdfReader     reader   = new PdfReader(oldFile);
            PdfDictionary pageDict = reader.GetPageN(1);



            iTextSharp.text.Rectangle pagesize = reader.GetPageSize(1);

            double anchoPDF = pagesize.Width - 30;
            double altoPDF  = pagesize.Height - 30;
            // MessageBox.Show("Tamano pagina pdf --> ancho :" + anchoPDF + " y alto : " + altoPDF);
            float anchoImagen = 400;
            float altoImagen  = 450;
            //MessageBox.Show("Tamano imagen --> ancho :" + anchoImagen+ " y alto : " + altoImagen);

            PdfArray annotArray = pageDict.GetAsArray(PdfName.ANNOTS);

            for (int i = 0; i < annotArray.Size; ++i)
            {
                PdfDictionary curAnnot = annotArray.GetAsDict(i);
                var           subtype  = curAnnot.Get(PdfName.SUBTYPE);
                var           rect     = curAnnot.Get(PdfName.RECT);
                var           contents = curAnnot.Get(PdfName.CONTENTS);
                var           page     = curAnnot.Get(PdfName.P);
                //MessageBox.Show("Subtipo "+subtype + " coordenadas: "+rect + " y contenido "+contents);
                if (subtype.ToString() == "/Square")
                {
                    Console.WriteLine("Encontro un rectangulo/cuadrado ");

                    //MessageBox.Show("Figura rectangular detectada coor "+rect);
                    var aux_rect = rect.ToString().Split(',');
                    aux_rect[0] = aux_rect[0].Remove(0, 1);
                    aux_rect[3] = aux_rect[3].Remove(aux_rect[3].Length - 1);
                    aux_rect[0] = aux_rect[0].Replace(".", ",");
                    aux_rect[1] = aux_rect[1].Replace(".", ",");
                    aux_rect[2] = aux_rect[2].Replace(".", ",");
                    aux_rect[3] = aux_rect[3].Replace(".", ",");
                    //MessageBox.Show("el split primero " + aux_rect[0]+ " el split ultimo "+ aux_rect[3]);
                    // MessageBox.Show("Esto es rect " + aux_rect[0] + " " + aux_rect[1] + " " + aux_rect[2] + " " + aux_rect[3]);
                    int puntox1 = Convert.ToInt32(Convert.ToSingle(aux_rect[0]));
                    int puntoy1 = Convert.ToInt32(Convert.ToSingle(aux_rect[1]));
                    int puntox2 = Convert.ToInt32(Convert.ToSingle(aux_rect[2]));
                    int puntoy2 = Convert.ToInt32(Convert.ToSingle(aux_rect[3]));
                    // MessageBox.Show("puntos "+ puntox1+" ,"+ puntoy1+ " , "+ puntox2+" , "+ puntoy2);

                    // TRANSFORMAR COORDENADAS DESDE PDF
                    int nuevoX1 = (Convert.ToInt32(anchoImagen) * (puntox1 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoX2 = (Convert.ToInt32(anchoImagen) * (puntox2 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoY1 = ((Convert.ToInt32(altoImagen) * (puntoy1 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    int nuevoY2 = ((Convert.ToInt32(altoImagen) * (puntoy2 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    // MessageBox.Show("puntos " + nuevoX1 + " ," + nuevoY1 + " , " + nuevoX2 + " , " + nuevoY2);

                    Rectangle rectangulo = new Rectangle(puntox1, puntoy1, puntox1 + puntox2, puntoy1 + puntoy2);

                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    //fondo.Draw(rectangulo, new Bgr(Color.Cyan), 1);
                    Rectangle rectangulo2 = new Rectangle(nuevoX1, (int)altoImagen - nuevoY1, nuevoX2 - nuevoX1, nuevoY2 - nuevoY1);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    //fondo.Draw(rectangulo2, new Bgr(Color.Red), 1);
                    rectList.Add(rectangulo2);
                }


                if (subtype.ToString() == "/Circle")
                {
                    var aux_rect = rect.ToString().Split(',');
                    aux_rect[0] = aux_rect[0].Remove(0, 1);
                    aux_rect[3] = aux_rect[3].Remove(aux_rect[3].Length - 1);
                    aux_rect[0] = aux_rect[0].Replace(".", ",");
                    aux_rect[1] = aux_rect[1].Replace(".", ",");
                    aux_rect[2] = aux_rect[2].Replace(".", ",");
                    aux_rect[3] = aux_rect[3].Replace(".", ",");
                    //MessageBox.Show("el split primero " + aux_rect[0]+ " el split ultimo "+ aux_rect[3]);
                    // MessageBox.Show("Esto es rect " + aux_rect[0] + " " + aux_rect[1] + " " + aux_rect[2] + " " + aux_rect[3]);
                    int puntox1 = Convert.ToInt32(Convert.ToSingle(aux_rect[0]));
                    int puntoy1 = Convert.ToInt32(Convert.ToSingle(aux_rect[1]));
                    int puntox2 = Convert.ToInt32(Convert.ToSingle(aux_rect[2]));
                    int puntoy2 = Convert.ToInt32(Convert.ToSingle(aux_rect[3]));
                    // MessageBox.Show("puntos "+ puntox1+" ,"+ puntoy1+ " , "+ puntox2+" , "+ puntoy2);

                    // TRANSFORMAR COORDENADAS DESDE PDF
                    int nuevoX1 = (Convert.ToInt32(anchoImagen) * (puntox1 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoX2 = (Convert.ToInt32(anchoImagen) * (puntox2 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoY1 = ((Convert.ToInt32(altoImagen) * (puntoy1 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    int nuevoY2 = ((Convert.ToInt32(altoImagen) * (puntoy2 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    // MessageBox.Show("puntos " + nuevoX1 + " ," + nuevoY1 + " , " + nuevoX2 + " , " + nuevoY2);

                    Rectangle rectangulo = new Rectangle(puntox1, puntoy1, puntox1 + puntox2, puntoy1 + puntoy2);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    //fondo.Draw(rectangulo, new Bgr(Color.Cyan), 1);
                    Rectangle rectangulo2 = new Rectangle(nuevoX1, nuevoY1, nuevoX2 - nuevoX1, nuevoY2 - nuevoY1);
                    float     mitadX      = nuevoX1 + (rectangulo2.Width / 2) - 30;
                    float     mitadY      = (int)altoImagen - nuevoY1 + (rectangulo2.Height / 2);
                    Console.WriteLine("x1 " + nuevoX1 + "y x2 " + nuevoX2);
                    Console.WriteLine("Mitades " + mitadX + " y " + mitadY);
                    Console.WriteLine("tamanos " + rectangulo2.Width + " y " + rectangulo2.Height);

                    Ellipse elip = new Ellipse(new PointF(mitadX, mitadY), new Size(rectangulo2.Width - 30, rectangulo2.Height), 90);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);

                    //fondo.Draw(elip, new Bgr(Color.Blue), 1);
                    //pictureBox1.Image = fondo.Bitmap;
                    ellipseList.Add(elip);
                }
            }



            //Guarda figuras en formato json
            string resultado = "{\"figuras\" : {\"rectangulos\" : [";
            string auxRes    = "";
            int    j         = 0;

            if (rectList.Count == 0)
            {
                auxRes = auxRes + "],";
            }
            else
            {
                foreach (var item in rectList)
                {
                    if (rectList.Count - 1 == j)
                    {
                        // auxRes = auxRes + "\"rect" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + item.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + item.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + item.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + item.Height + "\"}]";
                    }
                    else
                    {
                        // auxRes = auxRes + "\"rect" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + item.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + item.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + item.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + item.Height + "\"},";
                    }

                    j = j + 1;
                }
            }


            auxRes = auxRes + " ,\"circulos\": [";
            //Agregar circulos y elipses
            j = 0;
            if (ellipseList.Count == 0)
            {
                auxRes = auxRes + "]";
            }
            else
            {
                foreach (var item in ellipseList)
                {
                    RotatedRect aux_ellipse = item.RotatedRect;

                    if (ellipseList.Count - 1 == j)
                    {
                        // auxRes = auxRes + "\"circ" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Height + "\"}]";
                    }
                    else
                    {
                        //auxRes = auxRes + "\"circ" + j + "\":{";
                        auxRes = auxRes + "{\"puntoX\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.X + "\",";
                        auxRes = auxRes + "\"puntoY\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Center.Y + "\",";
                        auxRes = auxRes + "\"width\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Width + "\",";
                        auxRes = auxRes + "\"height\":";
                        auxRes = auxRes + "\"" + aux_ellipse.Size.Height + "\"},";
                    }

                    j = j + 1;
                }
            }

            auxRes    = auxRes + "}}";
            resultado = resultado + auxRes;
            Console.WriteLine("Este es el resultado " + resultado);
            var final = JObject.Parse(resultado);


            return(final);
        }
        /**
         * Create an ImageRenderInfo object based on inline image data.  This is nowhere near completely thought through
         * and really just acts as a placeholder.
         * @param ctm the coordinate transformation matrix at the time the image is rendered
         * @param imageObject the image object representing the inline image
         * @return the ImageRenderInfo representing the rendered embedded image
         * @since 5.0.1
         */
        protected internal static ImageRenderInfo CreateForEmbeddedImage(GraphicsState gs, InlineImageInfo inlineImageInfo, PdfDictionary colorSpaceDictionary, ICollection markedContentInfos)
        {
            ImageRenderInfo renderInfo = new ImageRenderInfo(gs, inlineImageInfo, colorSpaceDictionary, markedContentInfos);

            return(renderInfo);
        }
 /**
  * Creates a PdfImage object.
  * @param stream a PRStream
  * @param colorSpaceDic a color space dictionary
  * @throws IOException
  */
 public PdfImageObject(PRStream stream, PdfDictionary colorSpaceDic) : this(stream, PdfReader.GetStreamBytesRaw(stream), colorSpaceDic) {
 }
 public byte[] Decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) {
     lastFilterName = filterName;
     return b;
 }
Exemple #41
0
        private void Apply(
            ListBox field
            )
        {
            Document document = field.Document;
            Widget   widget   = field.Widgets[0];

            Appearance appearance = widget.Appearance;
            {
                PdfDictionary widgetDataObject = widget.BaseDataObject;
                widgetDataObject[PdfName.DA] = new PdfString("/Helv " + FontSize + " Tf 0 0 0 rg");
                widgetDataObject[PdfName.MK] = new PdfDictionary(
                    new PdfName[]
                {
                    PdfName.BG,
                    PdfName.BC
                },
                    new PdfDirectObject[]
                {
                    new PdfArray(new PdfDirectObject[] { PdfReal.Get(.9), PdfReal.Get(.9), PdfReal.Get(.9) }),
                    new PdfArray(new PdfDirectObject[] { PdfInteger.Default, PdfInteger.Default, PdfInteger.Default })
                }
                    );
            }

            FormXObject normalAppearanceState;

            {
                SizeF size = widget.Box.Size;
                normalAppearanceState = new FormXObject(document, size);
                PrimitiveComposer composer = new PrimitiveComposer(normalAppearanceState);

                float      lineWidth = 1;
                RectangleF frame     = new RectangleF(lineWidth / 2, lineWidth / 2, size.Width - lineWidth, size.Height - lineWidth);
                if (GraphicsVisibile)
                {
                    composer.BeginLocalState();
                    composer.SetLineWidth(lineWidth);
                    composer.SetFillColor(BackColor);
                    composer.SetStrokeColor(ForeColor);
                    composer.DrawRectangle(frame, 5);
                    composer.FillStroke();
                    composer.End();
                }

                composer.BeginLocalState();
                if (GraphicsVisibile)
                {
                    composer.DrawRectangle(frame, 5);
                    composer.Clip(); // Ensures that the visible content is clipped within the rounded frame.
                }
                composer.BeginMarkedContent(PdfName.Tx);
                composer.SetFont(
                    new StandardType1Font(
                        document,
                        StandardType1Font.FamilyEnum.Helvetica,
                        false,
                        false
                        ),
                    FontSize
                    );
                double y = 3;
                foreach (ChoiceItem item in field.Items)
                {
                    composer.ShowText(
                        item.Text,
                        new PointF(0, (float)y)
                        );
                    y += FontSize * 1.175;
                    if (y > size.Height)
                    {
                        break;
                    }
                }
                composer.End();
                composer.End();

                composer.Flush();
            }
            appearance.Normal[null] = normalAppearanceState;
        }
 public virtual AccessibilityProperties AddAttributes(PdfDictionary attributes) {
     attributesList.Add(attributes);
     return this;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PdfButtonField"/> class.
 /// </summary>
 protected PdfButtonField(PdfDictionary dict)
   : base(dict)
 { }
Exemple #44
0
 private Image IndexedModel(byte[] bdata, int bpc, int paletteEntries) {
     Image img = new ImgRaw(width, height, 1, bpc, bdata);
     PdfArray colorspace = new PdfArray();
     colorspace.Add(PdfName.INDEXED);
     colorspace.Add(PdfName.DEVICERGB);
     byte[] np = GetPalette(paletteEntries);
     int len = np.Length;
     colorspace.Add(new PdfNumber(len / 3 - 1));
     colorspace.Add(new PdfString(np));
     PdfDictionary ad = new PdfDictionary();
     ad.Put(PdfName.COLORSPACE, colorspace);
     img.Additional = ad;
     return img;
 }
 /// <summary>Creates an ExternalBlankSignatureContainer.</summary>
 /// <param name="sigDic">PdfDictionary containing signature iformation. /SubFilter and /Filter aren't set in this constructor.
 ///     </param>
 public ExternalBlankSignatureContainer(PdfDictionary sigDic)
 {
     /* The Signature dictionary. Should contain values for /Filter and /SubFilter at minimum. */
     this.sigDic = sigDic;
 }
 /**
  * Create an ImageRenderInfo object based on an XObject (this is the most common way of including an image in PDF)
  * @param ctm the coordinate transformation matrix at the time the image is rendered
  * @param ref a reference to the image XObject
  * @return the ImageRenderInfo representing the rendered XObject
  * @since 5.0.1
  */
 public static ImageRenderInfo CreateForXObject(GraphicsState gs, PdfIndirectReference refi, PdfDictionary colorSpaceDictionary, ICollection markedContentInfos)
 {
     return(new ImageRenderInfo(gs, refi, colorSpaceDictionary, markedContentInfos));
 }
Exemple #47
0
 /**
   <summary>Sets the Javascript script into the specified base data object.</summary>
 */
 internal static void SetScript(
     PdfDictionary baseDataObject,
     PdfName key,
     string value
     )
 {
     PdfDataObject scriptObject = baseDataObject.Resolve(key);
       if(!(scriptObject is PdfStream) && value.Length > 256)
       {baseDataObject[key] = baseDataObject.File.Register(scriptObject = new PdfStream());}
       // Insert the script!
       if(scriptObject is PdfStream)
       {
     bytes::IBuffer scriptBuffer = ((PdfStream)scriptObject).Body;
     scriptBuffer.SetLength(0);
     scriptBuffer.Append(value);
       }
       else
       {baseDataObject[key] = new PdfTextString(value);}
 }
 /// <summary>Creates an ExternalBlankSignatureContainer.</summary>
 /// <remarks>
 /// Creates an ExternalBlankSignatureContainer. This constructor will create the PdfDictionary for the
 /// signature information and will insert the  /Filter and /SubFilter values into this dictionary.
 /// </remarks>
 /// <param name="filter">PdfName of the signature handler to use when validating this signature</param>
 /// <param name="subFilter">PdfName that describes the encoding of the signature</param>
 public ExternalBlankSignatureContainer(PdfName filter, PdfName subFilter)
 {
     sigDic = new PdfDictionary();
     sigDic.Put(PdfName.Filter, filter);
     sigDic.Put(PdfName.SubFilter, subFilter);
 }
 internal PdfGenericField(PdfDictionary dict) : base(dict)
 {
 }
 public virtual void ModifySigningDictionary(PdfDictionary signDic)
 {
     signDic.PutAll(sigDic);
 }
 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);
 }
 /**
  * Shows the detail of a dictionary.
  * This is similar to the PdfLister functionality.
  * @param dic   the dictionary of which you want the detail
  * @return  a String representation of the dictionary
  */
 public static String GetDictionaryDetail(PdfDictionary dic)
 {
     return(GetDictionaryDetail(dic, 0));
 }
Exemple #53
0
 internal PdfAcroForm(PdfDictionary dictionary)
     : base(dictionary)
 { }
 internal RoleMappingResolver(String role, PdfDocument document)
 {
     this.currRole = PdfStructTreeRoot.ConvertRoleToPdfName(role);
     this.roleMap  = document.GetStructTreeRoot().GetRoleMap();
 }
 internal PdfPushButtonField(PdfDictionary dict) : base(dict)
 {
 }
Exemple #56
0
 private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] password)
 {
     try {
         if (password == null)
         {
             password = new byte[0];
         }
         else
         {
             if (password.Length > 127)
             {
                 password = JavaUtil.ArraysCopyOf(password, 127);
             }
         }
         isPdf2 = encryptionDictionary.GetAsNumber(PdfName.R).GetValue() == 6;
         byte[]    oValue  = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.O));
         byte[]    uValue  = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.U));
         byte[]    oeValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.OE));
         byte[]    ueValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.UE));
         byte[]    perms   = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.Perms));
         PdfNumber pValue  = (PdfNumber)encryptionDictionary.Get(PdfName.P);
         this.permissions = pValue.LongValue();
         byte[] hash;
         hash = ComputeHash(password, oValue, VALIDATION_SALT_OFFSET, SALT_LENGTH, uValue);
         usedOwnerPassword = CompareArray(hash, oValue, 32);
         if (usedOwnerPassword)
         {
             hash = ComputeHash(password, oValue, KEY_SALT_OFFSET, SALT_LENGTH, uValue);
             AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash);
             nextObjectKey = ac.ProcessBlock(oeValue, 0, oeValue.Length);
         }
         else
         {
             hash = ComputeHash(password, uValue, VALIDATION_SALT_OFFSET, SALT_LENGTH);
             if (!CompareArray(hash, uValue, 32))
             {
                 throw new BadPasswordException(PdfException.BadUserPassword);
             }
             hash = ComputeHash(password, uValue, KEY_SALT_OFFSET, SALT_LENGTH);
             AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash);
             nextObjectKey = ac.ProcessBlock(ueValue, 0, ueValue.Length);
         }
         nextObjectKeySize = 32;
         AESCipherCBCnoPad ac_1     = new AESCipherCBCnoPad(false, nextObjectKey);
         byte[]            decPerms = ac_1.ProcessBlock(perms, 0, perms.Length);
         if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b')
         {
             throw new BadPasswordException(PdfException.BadUserPassword);
         }
         int permissionsDecoded = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16)
                                  | ((decPerms[3] & 0xff) << 24);
         bool encryptMetadata      = decPerms[8] == (byte)'T';
         bool?encryptMetadataEntry = encryptionDictionary.GetAsBool(PdfName.EncryptMetadata);
         if (permissionsDecoded != permissions || encryptMetadataEntry != null && encryptMetadata != encryptMetadataEntry
             )
         {
             ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Crypto.Securityhandler.StandardHandlerUsingAes256));
             logger.Error(iText.IO.LogMessageConstant.ENCRYPTION_ENTRIES_P_AND_ENCRYPT_METADATA_NOT_CORRESPOND_PERMS_ENTRY
                          );
         }
         this.permissions     = permissionsDecoded;
         this.encryptMetadata = encryptMetadata;
     }
     catch (BadPasswordException ex) {
         throw;
     }
     catch (Exception ex) {
         throw new PdfException(PdfException.PdfEncryption, ex);
     }
 }
        /**
         * Creats a PdfImage object using an explicitly provided dictionary and image bytes
         * @param dictionary the dictionary for the image
         * @param samples the samples
         * @since 5.0.3
         */
        protected internal PdfImageObject(PdfDictionary dictionary, byte[] samples, PdfDictionary colorSpaceDic)  {
            this.dictionary = dictionary;
            this.colorSpaceDic = colorSpaceDic;
            TrackingFilter trackingFilter = new TrackingFilter();
            IDictionary<PdfName, FilterHandlers.IFilterHandler> handlers = new Dictionary<PdfName, FilterHandlers.IFilterHandler>(FilterHandlers.GetDefaultFilterHandlers());
            handlers[PdfName.JBIG2DECODE] = trackingFilter;
            handlers[PdfName.DCTDECODE] = trackingFilter;
            handlers[PdfName.JPXDECODE] = trackingFilter;

            imageBytes = PdfReader.DecodeBytes(samples, dictionary, handlers);
            
            if (trackingFilter.lastFilterName != null){
                if (PdfName.JBIG2DECODE.Equals(trackingFilter.lastFilterName))
                    streamContentType = ImageBytesType.JBIG2;
                else if (PdfName.DCTDECODE.Equals(trackingFilter.lastFilterName))
                    streamContentType = ImageBytesType.JPG;
                else if (PdfName.JPXDECODE.Equals(trackingFilter.lastFilterName))
                    streamContentType = ImageBytesType.JP2;
            } else {
                DecodeImageBytes();
            }
        }
Exemple #58
0
 public StandardHandlerUsingAes256(PdfDictionary encryptionDictionary, byte[] password)
 {
     InitKeyAndReadDictionary(encryptionDictionary, password);
 }
Exemple #59
0
 internal PdfCatalog(PdfDictionary dictionary)
     : base(dictionary)
 { }
Exemple #60
0
 private void InitKeyAndFillDictionary(PdfDictionary encryptionDictionary, byte[] userPassword, byte[] ownerPassword
                                       , int permissions, bool encryptMetadata, bool embeddedFilesOnly)
 {
     ownerPassword = GenerateOwnerPasswordIfNullOrEmpty(ownerPassword);
     permissions  |= PERMS_MASK_1_FOR_REVISION_3_OR_GREATER;
     permissions  &= PERMS_MASK_2;
     try {
         byte[] userKey;
         byte[] ownerKey;
         byte[] ueKey;
         byte[] oeKey;
         byte[] aes256Perms;
         if (userPassword == null)
         {
             userPassword = new byte[0];
         }
         else
         {
             if (userPassword.Length > 127)
             {
                 userPassword = JavaUtil.ArraysCopyOf(userPassword, 127);
             }
         }
         if (ownerPassword.Length > 127)
         {
             ownerPassword = JavaUtil.ArraysCopyOf(ownerPassword, 127);
         }
         // first 8 bytes are validation salt; second 8 bytes are key salt
         byte[] userValAndKeySalt  = IVGenerator.GetIV(16);
         byte[] ownerValAndKeySalt = IVGenerator.GetIV(16);
         nextObjectKey     = IVGenerator.GetIV(32);
         nextObjectKeySize = 32;
         byte[] hash;
         // Algorithm 8.1
         hash    = ComputeHash(userPassword, userValAndKeySalt, 0, 8);
         userKey = JavaUtil.ArraysCopyOf(hash, 48);
         Array.Copy(userValAndKeySalt, 0, userKey, 32, 16);
         // Algorithm 8.2
         hash = ComputeHash(userPassword, userValAndKeySalt, 8, 8);
         AESCipherCBCnoPad ac = new AESCipherCBCnoPad(true, hash);
         ueKey = ac.ProcessBlock(nextObjectKey, 0, nextObjectKey.Length);
         // Algorithm 9.1
         hash     = ComputeHash(ownerPassword, ownerValAndKeySalt, 0, 8, userKey);
         ownerKey = JavaUtil.ArraysCopyOf(hash, 48);
         Array.Copy(ownerValAndKeySalt, 0, ownerKey, 32, 16);
         // Algorithm 9.2
         hash  = ComputeHash(ownerPassword, ownerValAndKeySalt, 8, 8, userKey);
         ac    = new AESCipherCBCnoPad(true, hash);
         oeKey = ac.ProcessBlock(nextObjectKey, 0, nextObjectKey.Length);
         // Algorithm 10
         byte[] permsp = IVGenerator.GetIV(16);
         permsp[0]            = (byte)permissions;
         permsp[1]            = (byte)(permissions >> 8);
         permsp[2]            = (byte)(permissions >> 16);
         permsp[3]            = (byte)(permissions >> 24);
         permsp[4]            = (byte)(255);
         permsp[5]            = (byte)(255);
         permsp[6]            = (byte)(255);
         permsp[7]            = (byte)(255);
         permsp[8]            = encryptMetadata ? (byte)'T' : (byte)'F';
         permsp[9]            = (byte)'a';
         permsp[10]           = (byte)'d';
         permsp[11]           = (byte)'b';
         ac                   = new AESCipherCBCnoPad(true, nextObjectKey);
         aes256Perms          = ac.ProcessBlock(permsp, 0, permsp.Length);
         this.permissions     = permissions;
         this.encryptMetadata = encryptMetadata;
         SetStandardHandlerDicEntries(encryptionDictionary, userKey, ownerKey);
         SetAES256DicEntries(encryptionDictionary, oeKey, ueKey, aes256Perms, encryptMetadata, embeddedFilesOnly);
     }
     catch (Exception ex) {
         throw new PdfException(PdfException.PdfEncryption, ex);
     }
 }