internal void Propagate(PdfObject obj, PdfIndirectReference refo, bool restricted)
        {
            if (obj == null)
            {
                return;
            }
            //        if (refo != null)
            //            AddToBody(obj, refo);
            if (obj is PdfIndirectReference)
            {
                return;
            }
            switch (obj.Type)
            {
            case PdfObject.DICTIONARY:
            case PdfObject.STREAM: {
                PdfDictionary dic = (PdfDictionary)obj;
                foreach (PdfName key in dic.Keys)
                {
                    if (restricted && (key.Equals(PdfName.PARENT) || key.Equals(PdfName.KIDS)))
                    {
                        continue;
                    }
                    PdfObject ob = dic.Get(key);
                    if (ob != null && ob.IsIndirect())
                    {
                        PRIndirectReference ind = (PRIndirectReference)ob;
                        if (!SetVisited(ind) && !IsPage(ind))
                        {
                            PdfIndirectReference refi = GetNewReference(ind);
                            Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted);
                        }
                    }
                    else
                    {
                        Propagate(ob, null, restricted);
                    }
                }
                break;
            }

            case PdfObject.ARRAY: {
                //PdfArray arr = new PdfArray();
                for (ListIterator it = ((PdfArray)obj).GetListIterator(); it.HasNext();)
                {
                    PdfObject ob = (PdfObject)it.Next();
                    if (ob != null && ob.IsIndirect())
                    {
                        PRIndirectReference ind = (PRIndirectReference)ob;
                        if (!IsVisited(ind) && !IsPage(ind))
                        {
                            PdfIndirectReference refi = GetNewReference(ind);
                            Propagate(PdfReader.GetPdfObjectRelease(ind), refi, restricted);
                        }
                    }
                    else
                    {
                        Propagate(ob, null, restricted);
                    }
                }
                break;
            }

            case PdfObject.INDIRECT: {
                throw new Exception(MessageLocalization.GetComposedMessage("reference.pointing.to.reference"));
            }
            }
        }
Beispiel #2
0
 protected override void CheckLayer(PdfWriter writer, int key, Object obj1)
 {
     throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("layers.are.not.allowed"));
 }
Beispiel #3
0
        protected override void CheckColor(PdfWriter writer, int key, Object obj1)
        {
            switch (key)
            {
            case PdfIsoKeys.PDFISOKEY_COLOR:
                if (obj1 is ExtendedColor)
                {
                    ExtendedColor ec = (ExtendedColor)obj1;
                    switch (ec.Type)
                    {
                    case ExtendedColor.TYPE_CMYK:
                        CheckColor(writer, PdfIsoKeys.PDFISOKEY_CMYK, obj1);
                        break;

                    case ExtendedColor.TYPE_GRAY:
                        CheckColor(writer, PdfIsoKeys.PDFISOKEY_GRAY, obj1);
                        return;

                    case ExtendedColor.TYPE_RGB:
                        CheckColor(writer, PdfIsoKeys.PDFISOKEY_RGB, obj1);
                        break;

                    case ExtendedColor.TYPE_SEPARATION:
                        SpotColor sc = (SpotColor)ec;
                        CheckColor(writer, PdfIsoKeys.PDFISOKEY_COLOR, sc.PdfSpotColor.AlternativeCS);
                        break;

                    case ExtendedColor.TYPE_SHADING:
                        ShadingColor xc = (ShadingColor)ec;
                        CheckColor(writer, PdfIsoKeys.PDFISOKEY_COLOR, xc.PdfShadingPattern.Shading.ColorSpace);
                        break;

                    case ExtendedColor.TYPE_PATTERN:
                        PatternColor pc = (PatternColor)ec;
                        CheckColor(writer, PdfIsoKeys.PDFISOKEY_COLOR, pc.Painter.DefaultColor);
                        break;
                    }
                }
                else if (obj1 is BaseColor)
                {
                    CheckColor(writer, PdfIsoKeys.PDFISOKEY_RGB, obj1);
                }
                break;

            case PdfIsoKeys.PDFISOKEY_CMYK:
                if (rgbUsed)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicergb.and.devicecmyk.colorspaces.cannot.be.used.both.in.one.file"));
                }
                cmykUsed = true;
                break;

            case PdfIsoKeys.PDFISOKEY_RGB:
                if (cmykUsed)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicergb.and.devicecmyk.colorspaces.cannot.be.used.both.in.one.file"));
                }
                rgbUsed = true;
                break;

            case PdfIsoKeys.PDFISOKEY_GRAY:
                grayUsed = true;
                break;
            }
        }
 public override System.Drawing.Image CreateDrawingImage(Android.Graphics.Color foreground, Android.Graphics.Color background)
 {
     throw new InvalidOperationException(MessageLocalization.GetComposedMessage("the.two.barcodes.must.be.composed.externally"));
 }
Beispiel #5
0
 /**
  * Always throws an exception since PDF/X conformance level cannot be set for PDF/A conformant documents.
  * @param pdfx
  */
 virtual public void SetPDFXConformance(int pdfx)
 {
     throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("pdfx.conformance.cannot.be.set.for.PdfAStamperImp.instance"));
 }
        virtual public bool ReadKey(PdfDictionary enc, byte[] password)
        {
            if (password == null)
            {
                password = new byte[0];
            }
            byte[] oValue  = DocWriter.GetISOBytes(enc.Get(PdfName.O).ToString());
            byte[] uValue  = DocWriter.GetISOBytes(enc.Get(PdfName.U).ToString());
            byte[] oeValue = DocWriter.GetISOBytes(enc.Get(PdfName.OE).ToString());
            byte[] ueValue = DocWriter.GetISOBytes(enc.Get(PdfName.UE).ToString());
            byte[] perms   = DocWriter.GetISOBytes(enc.Get(PdfName.PERMS).ToString());

            PdfNumber pValue = (PdfNumber)enc.Get(PdfName.P);

            this.oeKey = oeValue;
            this.ueKey = ueValue;
            this.perms = perms;

            this.ownerKey = oValue;
            this.userKey  = uValue;

            this.permissions = pValue.LongValue;

            bool    isUserPass = false;
            IDigest md         = DigestUtilities.GetDigest("SHA-256");

            md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
            md.BlockUpdate(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT);
            md.BlockUpdate(uValue, 0, OU_LENGHT);
            byte[]            hash        = DigestUtilities.DoFinal(md);
            bool              isOwnerPass = CompareArray(hash, oValue, 32);
            AESCipherCBCnoPad ac;

            if (isOwnerPass)
            {
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(oValue, KEY_SALT_OFFSET, SALT_LENGHT);
                md.BlockUpdate(uValue, 0, OU_LENGHT);
                md.DoFinal(hash, 0);
                ac  = new AESCipherCBCnoPad(false, hash);
                key = ac.ProcessBlock(oeValue, 0, oeValue.Length);
            }
            else
            {
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT);
                md.DoFinal(hash, 0);
                isUserPass = CompareArray(hash, uValue, 32);
                if (!isUserPass)
                {
                    throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password"));
                }
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(uValue, KEY_SALT_OFFSET, SALT_LENGHT);
                md.DoFinal(hash, 0);
                ac  = new AESCipherCBCnoPad(false, hash);
                key = ac.ProcessBlock(ueValue, 0, ueValue.Length);
            }
            ac = new AESCipherCBCnoPad(false, key);
            byte[] decPerms = ac.ProcessBlock(perms, 0, perms.Length);
            if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b')
            {
                throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password"));
            }
            permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8)
                          | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24);
            encryptMetadata = decPerms[8] == (byte)'T';
            return(isOwnerPass);
        }
Beispiel #7
0
        public static byte[] WrapBMP(Image image)
        {
            if (image.OriginalType != Image.ORIGINAL_BMP)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("only.bmp.can.be.wrapped.in.wmf"));
            }
            Stream imgIn;

            byte[] data = null;
            if (image.OriginalData == null)
            {
                WebRequest wr = WebRequest.Create(image.Url);
                wr.Credentials = CredentialCache.DefaultCredentials;
                imgIn          = wr.GetResponse().GetResponseStream();
                MemoryStream outp = new MemoryStream();
                int          b    = 0;
                while ((b = imgIn.ReadByte()) != -1)
                {
                    outp.WriteByte((byte)b);
                }
                imgIn.Close();
                data = outp.ToArray();
            }
            else
            {
                data = image.OriginalData;
            }
            int          sizeBmpWords = (data.Length - 14 + 1) >> 1;
            MemoryStream os           = new MemoryStream();

            // write metafile header
            WriteWord(os, 1);
            WriteWord(os, 9);
            WriteWord(os, 0x0300);
            WriteDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); // total metafile size
            WriteWord(os, 1);
            WriteDWord(os, 14 + sizeBmpWords);                       // max record size
            WriteWord(os, 0);
            // write records
            WriteDWord(os, 4);
            WriteWord(os, META_SETMAPMODE);
            WriteWord(os, 8);

            WriteDWord(os, 5);
            WriteWord(os, META_SETWINDOWORG);
            WriteWord(os, 0);
            WriteWord(os, 0);

            WriteDWord(os, 5);
            WriteWord(os, META_SETWINDOWEXT);
            WriteWord(os, (int)image.Height);
            WriteWord(os, (int)image.Width);

            WriteDWord(os, 13 + sizeBmpWords);
            WriteWord(os, META_DIBSTRETCHBLT);
            WriteDWord(os, 0x00cc0020);
            WriteWord(os, (int)image.Height);
            WriteWord(os, (int)image.Width);
            WriteWord(os, 0);
            WriteWord(os, 0);
            WriteWord(os, (int)image.Height);
            WriteWord(os, (int)image.Width);
            WriteWord(os, 0);
            WriteWord(os, 0);
            os.Write(data, 14, data.Length - 14);
            if ((data.Length & 1) == 1)
            {
                os.WriteByte(0);
            }
//        WriteDWord(os, 14 + sizeBmpWords);
//        WriteWord(os, META_STRETCHDIB);
//        WriteDWord(os, 0x00cc0020);
//        WriteWord(os, 0);
//        WriteWord(os, (int)image.Height);
//        WriteWord(os, (int)image.Width);
//        WriteWord(os, 0);
//        WriteWord(os, 0);
//        WriteWord(os, (int)image.Height);
//        WriteWord(os, (int)image.Width);
//        WriteWord(os, 0);
//        WriteWord(os, 0);
//        os.Write(data, 14, data.length - 14);
//        if ((data.length & 1) == 1)
//            os.Write(0);

            WriteDWord(os, 3);
            WriteWord(os, 0);
            os.Close();
            return(os.ToArray());
        }
Beispiel #8
0
        /**
         * Parses the content of a page, replacing appearances of annotations
         * with Form XObjects.
         * @param page a page dictionary
         * @throws IOException
         */
        virtual public void Parse(PdfDictionary page, PdfIndirectReference pageref)
        {
            LOGGER.Info("Parsing page with reference " + pageref);
            // initializing member variables
            baos         = new MemoryStream();
            this.page    = page;
            this.pageref = pageref;

            structParents = page.GetAsNumber(PdfName.STRUCTPARENTS);
            if (structParents == null)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("can.t.read.document.structure"));
            }
            annots = page.GetAsArray(PdfName.ANNOTS);
            if (annots == null)
            {
                annots = new PdfArray();
            }
            PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);

            xobjects = resources.GetAsDict(PdfName.XOBJECT);
            if (xobjects == null)
            {
                xobjects = new PdfDictionary();
                resources.Put(PdfName.XOBJECT, xobjects);
            }
            // parsing the content stream of the page
            PRStream stream = (PRStream)page.GetAsStream(PdfName.CONTENTS);

            byte[]           contentBytes = PdfReader.GetStreamBytes(stream);
            PRTokeniser      tokeniser    = new PRTokeniser(new RandomAccessFileOrArray(RASFACTORY.CreateSource(contentBytes)));
            PdfContentParser ps           = new PdfContentParser(tokeniser);
            List <PdfObject> operands     = new List <PdfObject>();

            while (ps.Parse(operands).Count > 0)
            {
                PdfLiteral opr = (PdfLiteral)operands[operands.Count - 1];
                ProcessOperator(opr, operands);
            }
            // dealing with orphans
            while (items.Count > 0 && items[0].GetPageref() == pageref.Number)
            {
                StructureItem item = items[0];
                if (item is StructureObject)
                {
                    ConvertToXObject((StructureObject)item);
                    items.RemoveAt(0);
                }
            }
            if (annots.Length == 0)
            {
                page.Remove(PdfName.ANNOTS);
            }
            else
            {
                PdfDictionary annot;
                for (int i = 0; i < annots.Size; i++)
                {
                    annot = annots.GetAsDict(i);
                    if (annot.GetAsNumber(PdfName.STRUCTPARENT) == null)
                    {
                        throw new DocumentException(MessageLocalization.GetComposedMessage("could.not.flatten.file.untagged.annotations.found"));
                    }
                }
            }
            // replacing the content stream
            baos.Flush();
            baos.Close();
            stream.SetData(baos.ToArray());
            // showing how many items are left
            LOGGER.Info(String.Format("There are {0} items left for processing", items.Count));
        }
Beispiel #9
0
 internal void ThrowError()
 {
     throw new Exception(MessageLocalization.GetComposedMessage("content.can.not.be.added.to.a.pdfimportedpage"));
 }
Beispiel #10
0
        /**
         * decodes the bytes currently captured in the streamBytes and replaces it with an image representation of the bytes
         * (this will either be a png or a tiff, depending on the color depth of the image)
         * @throws IOException
         */
        private void DecodeImageBytes()
        {
            if (streamContentType != null)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("Decoding.can't.happen.on.this.type.of.stream.(.1.)", streamContentType.FileExtension));
            }
            pngColorType = -1;
            PdfArray decode = dictionary.GetAsArray(PdfName.DECODE);

            width       = dictionary.GetAsNumber(PdfName.WIDTH).IntValue;
            height      = dictionary.GetAsNumber(PdfName.HEIGHT).IntValue;
            bpc         = dictionary.GetAsNumber(PdfName.BITSPERCOMPONENT).IntValue;
            pngBitDepth = bpc;
            PdfObject colorspace = dictionary.GetDirectObject(PdfName.COLORSPACE);

            if (colorspace is PdfName && colorSpaceDic != null)
            {
                PdfObject csLookup = colorSpaceDic.GetDirectObject((PdfName)colorspace);
                if (csLookup != null)
                {
                    colorspace = csLookup;
                }
            }

            palette = null;
            icc     = null;
            stride  = 0;
            FindColorspace(colorspace, true);
            MemoryStream ms = new MemoryStream();

            if (pngColorType < 0)
            {
                if (bpc != 8)
                {
                    throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.depth.1.is.not.supported", bpc));
                }
                if (PdfName.DEVICECMYK.Equals(colorspace))
                {
                }
                else if (colorspace is PdfArray)
                {
                    PdfArray  ca   = (PdfArray)colorspace;
                    PdfObject tyca = ca.GetDirectObject(0);
                    if (!PdfName.ICCBASED.Equals(tyca))
                    {
                        throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.space.1.is.not.supported", colorspace));
                    }
                    PRStream pr = (PRStream)ca.GetDirectObject(1);
                    int      n  = pr.GetAsNumber(PdfName.N).IntValue;
                    if (n != 4)
                    {
                        throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("N.value.1.is.not.supported", n));
                    }
                    icc = PdfReader.GetStreamBytes(pr);
                }
                else
                {
                    throw new UnsupportedPdfException(MessageLocalization.GetComposedMessage("the.color.space.1.is.not.supported", colorspace));
                }
                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, width));
                wr.AddField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, 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, 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, Version.GetInstance().GetVersion));
                MemoryStream comp = new MemoryStream();
                TiffWriter.CompressLZW(comp, 2, imageBytes, 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);
                streamContentType = ImageBytesType.CCITT;
                imageBytes        = ms.ToArray();
                return;
            }
            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;
                            }
                        }
                        else
                        {
                            // 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
                        }
                    }
                    else
                    {
                        // 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();
                streamContentType = ImageBytesType.PNG;
                imageBytes        = ms.ToArray();
            }
        }
Beispiel #11
0
 public static void ThrowColorSpaceError()
 {
     throw new ArgumentException(MessageLocalization.GetComposedMessage("a.tiling.or.shading.pattern.cannot.be.used.as.a.color.space.in.a.shading.pattern"));
 }
Beispiel #12
0
        /**
         * Use this constructor if you want to verify a signature using
         * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param tsp set to true if there's a PAdES LTV time stamp.
         * @param provider the provider or <code>null</code> for the default provider
         */
        public PdfPKCS7(byte[] contentsKey, bool tsp)
        {
            isTsp = tsp;
            Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));

            //
            // Basic checks to make sure it's a PKCS#7 SignedData Object
            //
            Asn1Object pkcs;

            try {
                pkcs = din.ReadObject();
            }
            catch  {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
            }
            if (!(pkcs is Asn1Sequence))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
            }
            Asn1Sequence        signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId      = (DerObjectIdentifier)signedData[0];

            if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
            }
            Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[1]).GetObject();

            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

            // the version
            version = ((DerInteger)content[0]).Value.IntValue;

            // the digestAlgorithms
            digestalgos = new Dictionary <string, object>();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();

            while (e.MoveNext())
            {
                Asn1Sequence        s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser();

            certs = new List <X509Certificate>();
            foreach (X509Certificate cc in cf.ReadCertificates(contentsKey))
            {
                certs.Add(cc);
            }
            crls = new List <X509Crl>();

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];

            if (rsaData.Count > 1)
            {
                Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;

            while (content[next] is Asn1TaggedObject)
            {
                ++next;
            }
            Asn1Set signerInfos = (Asn1Set)content[next];

            if (signerInfos.Count != 1)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
            }
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];

            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate issuer and serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];

            Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;

            foreach (X509Certificate cert in certs)
            {
                if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber))
                {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1",
                                                                                   issuer.ToString() + " / " + serialNumber.ToString(16)));
            }
            CalcSignCertificateChain();
            digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject)
            {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Set          sseq   = Asn1Set.GetInstance(tagsig, false);
                sigAttr = sseq.GetEncoded(Asn1Encodable.Der);

                for (int k = 0; k < sseq.Count; ++k)
                {
                    Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
                    if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST))
                    {
                        Asn1Set sset = (Asn1Set)seq2[1];
                        digestAttr = ((DerOctetString)sset[0]).GetOctets();
                    }
                    else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION))
                    {
                        Asn1Set      setout = (Asn1Set)seq2[1];
                        Asn1Sequence seqout = (Asn1Sequence)setout[0];
                        for (int j = 0; j < seqout.Count; ++j)
                        {
                            Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                            if (tg.TagNo == 1)
                            {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindOcsp(seqin);
                            }
                            if (tg.TagNo == 0)
                            {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindCRL(seqin);
                            }
                        }
                    }
                }
                if (digestAttr == null)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest"));
                }
                ++next;
            }
            digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
            digest = ((Asn1OctetString)signerInfo[next++]).GetOctets();
            if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject))
            {
                Asn1TaggedObject taggedObject = (Asn1TaggedObject)signerInfo[next];
                Asn1Set          unat         = Asn1Set.GetInstance(taggedObject, false);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
                Org.BouncyCastle.Asn1.Cms.Attribute      ts     = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
                if (ts != null && ts.AttrValues.Count > 0)
                {
                    Asn1Set      attributeValues = ts.AttrValues;
                    Asn1Sequence tokenSequence   = Asn1Sequence.GetInstance(attributeValues[0]);
                    Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
                    this.timeStampToken = new TimeStampToken(contentInfo);
                }
            }
            if (isTsp)
            {
                Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData);
                this.timeStampToken = new TimeStampToken(contentInfoTsp);
                TimeStampTokenInfo info   = timeStampToken.TimeStampInfo;
                String             algOID = info.MessageImprintAlgOid;
                messageDigest = DigestUtilities.GetDigest(algOID);
            }
            else
            {
                if (RSAdata != null || digestAttr != null)
                {
                    messageDigest = GetHashClass();
                    encContDigest = GetHashClass();
                }
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(false, signCert.GetPublicKey());
            }
        }
Beispiel #13
0
        /**
         * This method checks if the image is a valid JPEG and processes some parameters.
         * @throws BadElementException
         * @throws IOException
         */
        private void ProcessParameters()
        {
            type         = JPEG2000;
            originalType = ORIGINAL_JPEG2000;
            inp          = null;
            try {
                if (rawData == null)
                {
                    WebRequest w = WebRequest.Create(url);
                    w.Credentials = CredentialCache.DefaultCredentials;
                    inp           = w.GetResponse().GetResponseStream();
                }
                else
                {
                    inp = new MemoryStream(rawData);
                }
                boxLength = Cio_read(4);
                if (boxLength == 0x0000000c)
                {
                    boxType = Cio_read(4);
                    if (JP2_JP != boxType)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("expected.jp.marker"));
                    }
                    if (0x0d0a870a != Cio_read(4))
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("error.with.jp.marker"));
                    }

                    Jp2_read_boxhdr();
                    if (JP2_FTYP != boxType)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("expected.ftyp.marker"));
                    }
                    Utilities.Skip(inp, boxLength - 8);
                    Jp2_read_boxhdr();
                    do
                    {
                        if (JP2_JP2H != boxType)
                        {
                            if (boxType == JP2_JP2C)
                            {
                                throw new IOException(MessageLocalization.GetComposedMessage("expected.jp2h.marker"));
                            }
                            Utilities.Skip(inp, boxLength - 8);
                            Jp2_read_boxhdr();
                        }
                    } while (JP2_JP2H != boxType);
                    Jp2_read_boxhdr();
                    if (JP2_IHDR != boxType)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("expected.ihdr.marker"));
                    }
                    scaledHeight = Cio_read(4);
                    Top          = scaledHeight;
                    scaledWidth  = Cio_read(4);
                    Right        = scaledWidth;
                    bpc          = -1;
                }
                else if ((uint)boxLength == 0xff4fff51)
                {
                    Utilities.Skip(inp, 4);
                    int x1 = Cio_read(4);
                    int y1 = Cio_read(4);
                    int x0 = Cio_read(4);
                    int y0 = Cio_read(4);
                    Utilities.Skip(inp, 16);
                    colorspace   = Cio_read(2);
                    bpc          = 8;
                    scaledHeight = y1 - y0;
                    Top          = scaledHeight;
                    scaledWidth  = x1 - x0;
                    Right        = scaledWidth;
                }
                else
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("not.a.valid.jpeg2000.file"));
                }
            }
            finally {
                if (inp != null)
                {
                    try{ inp.Close(); }catch {}
                    inp = null;
                }
            }
            plainWidth  = this.Width;
            plainHeight = this.Height;
        }
Beispiel #14
0
        /**
         * Gives you a BaseColor based on a name.
         *
         * @param name
         *            a name such as black, violet, cornflowerblue or #RGB or #RRGGBB
         *            or RGB or RRGGBB or rgb(R,G,B)
         * @return the corresponding BaseColor object.  Never returns null.
         * @throws IllegalArgumentException
         *             if the String isn't a know representation of a color.
         */
        public static BaseColor GetRGBColor(String name)
        {
            int[] c = { 0, 0, 0, 255 };
            name = name.ToLowerInvariant();
            bool colorStrWithoutHash = MissingHashColorFormat(name);

            if (name.StartsWith("#") || colorStrWithoutHash)
            {
                if (!colorStrWithoutHash)
                {
                    name = name.Substring(1); // lop off the # to unify hex parsing.
                }
                if (name.Length == 3)
                {
                    String s = name.Substring(0, 1);
                    c[0] = int.Parse(s + s, NumberStyles.HexNumber);
                    String s2 = name.Substring(1, 1);
                    c[1] = int.Parse(s2 + s2, NumberStyles.HexNumber);
                    String s3 = name.Substring(2);
                    c[2] = int.Parse(s3 + s3, NumberStyles.HexNumber);
                    return(new BaseColor(c[0], c[1], c[2], c[3]));
                }
                if (name.Length == 6)
                {
                    c[0] = int.Parse(name.Substring(0, 2), NumberStyles.HexNumber);
                    c[1] = int.Parse(name.Substring(2, 2), NumberStyles.HexNumber);
                    c[2] = int.Parse(name.Substring(4), NumberStyles.HexNumber);
                    return(new BaseColor(c[0], c[1], c[2], c[3]));
                }
                throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb"));
            }
            else if (name.StartsWith("rgb("))
            {
                StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f");
                for (int k = 0; k < 3; ++k)
                {
                    String v = tok.NextToken();
                    if (v.EndsWith("%"))
                    {
                        c[k] = int.Parse(v.Substring(0, v.Length - 1)) * 255 / 100;
                    }
                    else
                    {
                        c[k] = int.Parse(v);
                    }
                    if (c[k] < 0)
                    {
                        c[k] = 0;
                    }
                    else if (c[k] > 255)
                    {
                        c[k] = 255;
                    }
                }
                return(new BaseColor(c[0], c[1], c[2], c[3]));
            }
            name = name.ToLower(CultureInfo.InvariantCulture);
            if (!NAMES.ContainsKey(name))
            {
                // TODO localize this error message.
                throw new ArgumentException("Color '" + name + "' not found.");
            }
            c = NAMES[name];
            return(new BaseColor(c[0], c[1], c[2], c[3]));
        }
        /**
         *
         * @param writer
         * @param key
         * @param obj1
         */
        static public void CheckPdfAConformance(PdfWriter writer, int key, Object obj1)
        {
            if (writer == null || !writer.IsPdfIso())
            {
                return;
            }
            switch (key)
            {
            case PdfIsoKeys.PDFISOKEY_FONT:
                BaseFont bf = (BaseFont)obj1;
                if (bf.FontType == BaseFont.FONT_TYPE_DOCUMENT)
                {
                    PdfStream     prs            = null;
                    PdfDictionary fontDictionary = ((DocumentFont)bf).FontDictionary;
                    PdfDictionary fontDescriptor = fontDictionary.GetAsDict(PdfName.FONTDESCRIPTOR);
                    if (fontDescriptor != null)
                    {
                        prs = fontDescriptor.GetAsStream(PdfName.FONTFILE);
                        if (prs == null)
                        {
                            prs = fontDescriptor.GetAsStream(PdfName.FONTFILE2);
                        }
                        if (prs == null)
                        {
                            prs = fontDescriptor.GetAsStream(PdfName.FONTFILE3);
                        }
                    }
                    if (prs == null)
                    {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont)obj1).PostscriptFontName));
                    }
                }
                else
                {
                    if (!bf.IsEmbedded())
                    {
                        throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont)obj1).PostscriptFontName));
                    }
                }
                break;

            case PdfIsoKeys.PDFISOKEY_IMAGE:
                PdfImage image = (PdfImage)obj1;
                if (image.Get(PdfName.SMASK) != null)
                {
                    throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.smask.key.is.not.allowed.in.images"));
                }
                break;

            case PdfIsoKeys.PDFISOKEY_GSTATE:
                PdfDictionary gs  = (PdfDictionary)obj1;
                PdfObject     obj = gs.Get(PdfName.BM);
                if (obj != null && !PdfGState.BM_NORMAL.Equals(obj) && !PdfGState.BM_COMPATIBLE.Equals(obj))
                {
                    throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("blend.mode.1.not.allowed", obj.ToString()));
                }
                obj = gs.Get(PdfName.CA);
                double v = 0.0;
                if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0)
                {
                    throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v));
                }
                obj = gs.Get(PdfName.ca_);
                v   = 0.0;
                if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0)
                {
                    throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v));
                }
                break;

            case PdfIsoKeys.PDFISOKEY_LAYER:
                throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("layers.are.not.allowed"));

            default:
                break;
            }
        }
Beispiel #16
0
        public override System.Drawing.Image CreateDrawingImage(System.Drawing.Color foreground, System.Drawing.Color background)
        {
            int width = 0;

            byte[] bars = null;
            switch (codeType)
            {
            case EAN13:
                bars  = GetBarsEAN13(code);
                width = 11 + 12 * 7;
                break;

            case EAN8:
                bars  = GetBarsEAN8(code);
                width = 11 + 8 * 7;
                break;

            case UPCA:
                bars  = GetBarsEAN13("0" + code);
                width = 11 + 12 * 7;
                break;

            case UPCE:
                bars  = GetBarsUPCE(code);
                width = 9 + 6 * 7;
                break;

            case SUPP2:
                bars  = GetBarsSupplemental2(code);
                width = 6 + 2 * 7;
                break;

            case SUPP5:
                bars  = GetBarsSupplemental5(code);
                width = 4 + 5 * 7 + 4 * 2;
                break;

            default:
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("invalid.code.type"));
            }
            int height = (int)barHeight;

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height);
            for (int h = 0; h < height; ++h)
            {
                bool print = true;
                int  ptr   = 0;
                for (int k = 0; k < bars.Length; ++k)
                {
                    int w = bars[k];
                    System.Drawing.Color c = background;
                    if (print)
                    {
                        c = foreground;
                    }
                    print = !print;
                    for (int j = 0; j < w; ++j)
                    {
                        bmp.SetPixel(ptr++, h, c);
                    }
                }
            }
            return(bmp);
        }
        JBIG2Segment ReadHeader()
        {
            int ptr = (int)ra.FilePointer;
            // 7.2.1
            int          segment_number = ra.ReadInt();
            JBIG2Segment s = new JBIG2Segment(segment_number);

            // 7.2.3
            int  segment_header_flags = ra.Read();
            bool deferred_non_retain  = ((segment_header_flags & 0x80) == 0x80);

            s.deferredNonRetain = deferred_non_retain;
            bool page_association_size = ((segment_header_flags & 0x40) == 0x40);
            int  segment_type          = (segment_header_flags & 0x3f);

            s.type = segment_type;

            //7.2.4
            int referred_to_byte0             = ra.Read();
            int count_of_referred_to_segments = (referred_to_byte0 & 0xE0) >> 5;

            int[]  referred_to_segment_numbers = null;
            bool[] segment_retention_flags     = null;

            if (count_of_referred_to_segments == 7)
            {
                // at least five bytes
                ra.Seek(ra.FilePointer - 1);
                count_of_referred_to_segments = (ra.ReadInt() & 0x1fffffff);
                segment_retention_flags       = new bool[count_of_referred_to_segments + 1];
                int i = 0;
                int referred_to_current_byte = 0;
                do
                {
                    int j = i % 8;
                    if (j == 0)
                    {
                        referred_to_current_byte = ra.Read();
                    }
                    segment_retention_flags[i] = ((((0x1 << j) & referred_to_current_byte) >> j) == 0x1);
                    i++;
                } while (i <= count_of_referred_to_segments);
            }
            else if (count_of_referred_to_segments <= 4)
            {
                // only one byte
                segment_retention_flags = new bool[count_of_referred_to_segments + 1];
                referred_to_byte0      &= 0x1f;
                for (int i = 0; i <= count_of_referred_to_segments; i++)
                {
                    segment_retention_flags[i] = ((((0x1 << i) & referred_to_byte0) >> i) == 0x1);
                }
            }
            else if (count_of_referred_to_segments == 5 || count_of_referred_to_segments == 6)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("count.of.referred.to.segments.had.bad.value.in.header.for.segment.1.starting.at.2", segment_number, ptr));
            }
            s.segmentRetentionFlags     = segment_retention_flags;
            s.countOfReferredToSegments = count_of_referred_to_segments;

            // 7.2.5
            referred_to_segment_numbers = new int[count_of_referred_to_segments + 1];
            for (int i = 1; i <= count_of_referred_to_segments; i++)
            {
                if (segment_number <= 256)
                {
                    referred_to_segment_numbers[i] = ra.Read();
                }
                else if (segment_number <= 65536)
                {
                    referred_to_segment_numbers[i] = ra.ReadUnsignedShort();
                }
                else
                {
                    referred_to_segment_numbers[i] = (int)ra.ReadUnsignedInt(); // TODO wtf ack
                }
            }
            s.referredToSegmentNumbers = referred_to_segment_numbers;

            // 7.2.6
            int segment_page_association;
            int page_association_offset = (int)ra.FilePointer - ptr;

            if (page_association_size)
            {
                segment_page_association = ra.ReadInt();
            }
            else
            {
                segment_page_association = ra.Read();
            }
            if (segment_page_association < 0)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("page.1.invalid.for.segment.2.starting.at.3", segment_page_association, segment_number, ptr));
            }
            s.page = segment_page_association;
            // so we can change the page association at embedding time.
            s.page_association_size   = page_association_size;
            s.page_association_offset = page_association_offset;

            if (segment_page_association > 0 && !pages.ContainsKey(segment_page_association))
            {
                pages[segment_page_association] = new JBIG2Page(segment_page_association, this);
            }
            if (segment_page_association > 0)
            {
                pages[segment_page_association].AddSegment(s);
            }
            else
            {
                globals[s] = null;
            }

            // 7.2.7
            long segment_data_length = ra.ReadUnsignedInt();

            // TODO the 0xffffffff value that might be here, and how to understand those afflicted segments
            s.dataLength = segment_data_length;

            int end_ptr = (int)ra.FilePointer;

            ra.Seek(ptr);
            byte[] header_data = new byte[end_ptr - ptr];
            ra.Read(header_data);
            s.headerData = header_data;

            return(s);
        }
 /**
  * @see com.itextpdf.text.pdf.PdfArray#addFirst(com.itextpdf.text.pdf.PdfObject)
  */
 public override void AddFirst(PdfObject obj)
 {
     throw new ArgumentException(MessageLocalization.GetComposedMessage("illegal.ve.value"));
 }
Beispiel #19
0
        public void ReadAll()
        {
            if (meta.ReadInt() != unchecked ((int)0x9AC6CDD7))
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("not.a.placeable.windows.metafile"));
            }
            meta.ReadWord();
            left           = meta.ReadShort();
            top            = meta.ReadShort();
            right          = meta.ReadShort();
            bottom         = meta.ReadShort();
            inch           = meta.ReadWord();
            state.ScalingX = (float)(right - left) / (float)inch * 72f;
            state.ScalingY = (float)(bottom - top) / (float)inch * 72f;
            state.OffsetWx = left;
            state.OffsetWy = top;
            state.ExtentWx = right - left;
            state.ExtentWy = bottom - top;
            meta.ReadInt();
            meta.ReadWord();
            meta.Skip(18);

            int tsize;
            int function;

            cb.SetLineCap(1);
            cb.SetLineJoin(1);
            for (;;)
            {
                int lenMarker = meta.Length;
                tsize = meta.ReadInt();
                if (tsize < 3)
                {
                    break;
                }
                function = meta.ReadWord();
                switch (function)
                {
                case 0:
                    break;

                case META_CREATEPALETTE:
                case META_CREATEREGION:
                case META_DIBCREATEPATTERNBRUSH:
                    state.AddMetaObject(new MetaObject());
                    break;

                case META_CREATEPENINDIRECT:
                {
                    MetaPen pen = new MetaPen();
                    pen.Init(meta);
                    state.AddMetaObject(pen);
                    break;
                }

                case META_CREATEBRUSHINDIRECT:
                {
                    MetaBrush brush = new MetaBrush();
                    brush.Init(meta);
                    state.AddMetaObject(brush);
                    break;
                }

                case META_CREATEFONTINDIRECT:
                {
                    MetaFont font = new MetaFont();
                    font.Init(meta);
                    state.AddMetaObject(font);
                    break;
                }

                case META_SELECTOBJECT:
                {
                    int idx = meta.ReadWord();
                    state.SelectMetaObject(idx, cb);
                    break;
                }

                case META_DELETEOBJECT:
                {
                    int idx = meta.ReadWord();
                    state.DeleteMetaObject(idx);
                    break;
                }

                case META_SAVEDC:
                    state.SaveState(cb);
                    break;

                case META_RESTOREDC:
                {
                    int idx = meta.ReadShort();
                    state.RestoreState(idx, cb);
                    break;
                }

                case META_SETWINDOWORG:
                    state.OffsetWy = meta.ReadShort();
                    state.OffsetWx = meta.ReadShort();
                    break;

                case META_SETWINDOWEXT:
                    state.ExtentWy = meta.ReadShort();
                    state.ExtentWx = meta.ReadShort();
                    break;

                case META_MOVETO:
                {
                    int   y = meta.ReadShort();
                    Point p = new Point(meta.ReadShort(), y);
                    state.CurrentPoint = p;
                    break;
                }

                case META_LINETO:
                {
                    int   y = meta.ReadShort();
                    int   x = meta.ReadShort();
                    Point p = state.CurrentPoint;
                    cb.MoveTo(state.TransformX(p.x), state.TransformY(p.y));
                    cb.LineTo(state.TransformX(x), state.TransformY(y));
                    cb.Stroke();
                    state.CurrentPoint = new Point(x, y);
                    break;
                }

                case META_POLYLINE:
                {
                    state.LineJoinPolygon = cb;
                    int len = meta.ReadWord();
                    int x   = meta.ReadShort();
                    int y   = meta.ReadShort();
                    cb.MoveTo(state.TransformX(x), state.TransformY(y));
                    for (int k = 1; k < len; ++k)
                    {
                        x = meta.ReadShort();
                        y = meta.ReadShort();
                        cb.LineTo(state.TransformX(x), state.TransformY(y));
                    }
                    cb.Stroke();
                    break;
                }

                case META_POLYGON:
                {
                    if (IsNullStrokeFill(false))
                    {
                        break;
                    }
                    int len = meta.ReadWord();
                    int sx  = meta.ReadShort();
                    int sy  = meta.ReadShort();
                    cb.MoveTo(state.TransformX(sx), state.TransformY(sy));
                    for (int k = 1; k < len; ++k)
                    {
                        int x = meta.ReadShort();
                        int y = meta.ReadShort();
                        cb.LineTo(state.TransformX(x), state.TransformY(y));
                    }
                    cb.LineTo(state.TransformX(sx), state.TransformY(sy));
                    StrokeAndFill();
                    break;
                }

                case META_POLYPOLYGON:
                {
                    if (IsNullStrokeFill(false))
                    {
                        break;
                    }
                    int   numPoly = meta.ReadWord();
                    int[] lens    = new int[numPoly];
                    for (int k = 0; k < lens.Length; ++k)
                    {
                        lens[k] = meta.ReadWord();
                    }
                    for (int j = 0; j < lens.Length; ++j)
                    {
                        int len = lens[j];
                        int sx  = meta.ReadShort();
                        int sy  = meta.ReadShort();
                        cb.MoveTo(state.TransformX(sx), state.TransformY(sy));
                        for (int k = 1; k < len; ++k)
                        {
                            int x = meta.ReadShort();
                            int y = meta.ReadShort();
                            cb.LineTo(state.TransformX(x), state.TransformY(y));
                        }
                        cb.LineTo(state.TransformX(sx), state.TransformY(sy));
                    }
                    StrokeAndFill();
                    break;
                }

                case META_ELLIPSE:
                {
                    if (IsNullStrokeFill(state.LineNeutral))
                    {
                        break;
                    }
                    int b = meta.ReadShort();
                    int r = meta.ReadShort();
                    int t = meta.ReadShort();
                    int l = meta.ReadShort();
                    cb.Arc(state.TransformX(l), state.TransformY(b), state.TransformX(r), state.TransformY(t), 0, 360);
                    StrokeAndFill();
                    break;
                }

                case META_ARC:
                {
                    if (IsNullStrokeFill(state.LineNeutral))
                    {
                        break;
                    }
                    float yend   = state.TransformY(meta.ReadShort());
                    float xend   = state.TransformX(meta.ReadShort());
                    float ystart = state.TransformY(meta.ReadShort());
                    float xstart = state.TransformX(meta.ReadShort());
                    float b      = state.TransformY(meta.ReadShort());
                    float r      = state.TransformX(meta.ReadShort());
                    float t      = state.TransformY(meta.ReadShort());
                    float l      = state.TransformX(meta.ReadShort());
                    float cx     = (r + l) / 2;
                    float cy     = (t + b) / 2;
                    float arc1   = GetArc(cx, cy, xstart, ystart);
                    float arc2   = GetArc(cx, cy, xend, yend);
                    arc2 -= arc1;
                    if (arc2 <= 0)
                    {
                        arc2 += 360;
                    }
                    cb.Arc(l, b, r, t, arc1, arc2);
                    cb.Stroke();
                    break;
                }

                case META_PIE:
                {
                    if (IsNullStrokeFill(state.LineNeutral))
                    {
                        break;
                    }
                    float yend   = state.TransformY(meta.ReadShort());
                    float xend   = state.TransformX(meta.ReadShort());
                    float ystart = state.TransformY(meta.ReadShort());
                    float xstart = state.TransformX(meta.ReadShort());
                    float b      = state.TransformY(meta.ReadShort());
                    float r      = state.TransformX(meta.ReadShort());
                    float t      = state.TransformY(meta.ReadShort());
                    float l      = state.TransformX(meta.ReadShort());
                    float cx     = (r + l) / 2;
                    float cy     = (t + b) / 2;
                    float arc1   = GetArc(cx, cy, xstart, ystart);
                    float arc2   = GetArc(cx, cy, xend, yend);
                    arc2 -= arc1;
                    if (arc2 <= 0)
                    {
                        arc2 += 360;
                    }
                    List <float[]> ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2);
                    if (ar.Count == 0)
                    {
                        break;
                    }
                    float[] pt = ar[0];
                    cb.MoveTo(cx, cy);
                    cb.LineTo(pt[0], pt[1]);
                    for (int k = 0; k < ar.Count; ++k)
                    {
                        pt = ar[k];
                        cb.CurveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]);
                    }
                    cb.LineTo(cx, cy);
                    StrokeAndFill();
                    break;
                }

                case META_CHORD:
                {
                    if (IsNullStrokeFill(state.LineNeutral))
                    {
                        break;
                    }
                    float yend   = state.TransformY(meta.ReadShort());
                    float xend   = state.TransformX(meta.ReadShort());
                    float ystart = state.TransformY(meta.ReadShort());
                    float xstart = state.TransformX(meta.ReadShort());
                    float b      = state.TransformY(meta.ReadShort());
                    float r      = state.TransformX(meta.ReadShort());
                    float t      = state.TransformY(meta.ReadShort());
                    float l      = state.TransformX(meta.ReadShort());
                    float cx     = (r + l) / 2;
                    float cy     = (t + b) / 2;
                    float arc1   = GetArc(cx, cy, xstart, ystart);
                    float arc2   = GetArc(cx, cy, xend, yend);
                    arc2 -= arc1;
                    if (arc2 <= 0)
                    {
                        arc2 += 360;
                    }
                    List <float[]> ar = PdfContentByte.BezierArc(l, b, r, t, arc1, arc2);
                    if (ar.Count == 0)
                    {
                        break;
                    }
                    float[] pt = ar[0];
                    cx = pt[0];
                    cy = pt[1];
                    cb.MoveTo(cx, cy);
                    for (int k = 0; k < ar.Count; ++k)
                    {
                        pt = ar[k];
                        cb.CurveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]);
                    }
                    cb.LineTo(cx, cy);
                    StrokeAndFill();
                    break;
                }

                case META_RECTANGLE:
                {
                    if (IsNullStrokeFill(true))
                    {
                        break;
                    }
                    float b = state.TransformY(meta.ReadShort());
                    float r = state.TransformX(meta.ReadShort());
                    float t = state.TransformY(meta.ReadShort());
                    float l = state.TransformX(meta.ReadShort());
                    cb.Rectangle(l, b, r - l, t - b);
                    StrokeAndFill();
                    break;
                }

                case META_ROUNDRECT:
                {
                    if (IsNullStrokeFill(true))
                    {
                        break;
                    }
                    float h = state.TransformY(0) - state.TransformY(meta.ReadShort());
                    float w = state.TransformX(meta.ReadShort()) - state.TransformX(0);
                    float b = state.TransformY(meta.ReadShort());
                    float r = state.TransformX(meta.ReadShort());
                    float t = state.TransformY(meta.ReadShort());
                    float l = state.TransformX(meta.ReadShort());
                    cb.RoundRectangle(l, b, r - l, t - b, (h + w) / 4);
                    StrokeAndFill();
                    break;
                }

                case META_INTERSECTCLIPRECT:
                {
                    float b = state.TransformY(meta.ReadShort());
                    float r = state.TransformX(meta.ReadShort());
                    float t = state.TransformY(meta.ReadShort());
                    float l = state.TransformX(meta.ReadShort());
                    cb.Rectangle(l, b, r - l, t - b);
                    cb.EoClip();
                    cb.NewPath();
                    break;
                }

                case META_EXTTEXTOUT:
                {
                    int y     = meta.ReadShort();
                    int x     = meta.ReadShort();
                    int count = meta.ReadWord();
                    int flag  = meta.ReadWord();
                    int x1    = 0;
                    int y1    = 0;
                    int x2    = 0;
                    int y2    = 0;
                    if ((flag & (MetaFont.ETO_CLIPPED | MetaFont.ETO_OPAQUE)) != 0)
                    {
                        x1 = meta.ReadShort();
                        y1 = meta.ReadShort();
                        x2 = meta.ReadShort();
                        y2 = meta.ReadShort();
                    }
                    byte[] text = new byte[count];
                    int    k;
                    for (k = 0; k < count; ++k)
                    {
                        byte c = (byte)meta.ReadByte();
                        if (c == 0)
                        {
                            break;
                        }
                        text[k] = c;
                    }
                    string s;
                    try {
                        s = System.Text.Encoding.GetEncoding(1252).GetString(text, 0, k);
                    }
                    catch  {
                        s = System.Text.ASCIIEncoding.ASCII.GetString(text, 0, k);
                    }
                    OutputText(x, y, flag, x1, y1, x2, y2, s);
                    break;
                }

                case META_TEXTOUT:
                {
                    int    count = meta.ReadWord();
                    byte[] text  = new byte[count];
                    int    k;
                    for (k = 0; k < count; ++k)
                    {
                        byte c = (byte)meta.ReadByte();
                        if (c == 0)
                        {
                            break;
                        }
                        text[k] = c;
                    }
                    string s;
                    try {
                        s = System.Text.Encoding.GetEncoding(1252).GetString(text, 0, k);
                    }
                    catch {
                        s = System.Text.ASCIIEncoding.ASCII.GetString(text, 0, k);
                    }
                    count = (count + 1) & 0xfffe;
                    meta.Skip(count - k);
                    int y = meta.ReadShort();
                    int x = meta.ReadShort();
                    OutputText(x, y, 0, 0, 0, 0, 0, s);
                    break;
                }

                case META_SETBKCOLOR:
                    state.CurrentBackgroundColor = meta.ReadColor();
                    break;

                case META_SETTEXTCOLOR:
                    state.CurrentTextColor = meta.ReadColor();
                    break;

                case META_SETTEXTALIGN:
                    state.TextAlign = meta.ReadWord();
                    break;

                case META_SETBKMODE:
                    state.BackgroundMode = meta.ReadWord();
                    break;

                case META_SETPOLYFILLMODE:
                    state.PolyFillMode = meta.ReadWord();
                    break;

                case META_SETPIXEL:
                {
                    BaseColor color = meta.ReadColor();
                    int       y     = meta.ReadShort();
                    int       x     = meta.ReadShort();
                    cb.SaveState();
                    cb.SetColorFill(color);
                    cb.Rectangle(state.TransformX(x), state.TransformY(y), .2f, .2f);
                    cb.Fill();
                    cb.RestoreState();
                    break;
                }

                case META_DIBSTRETCHBLT:
                case META_STRETCHDIB: {
                    int rop = meta.ReadInt();
                    if (function == META_STRETCHDIB)
                    {
                        /*int usage = */ meta.ReadWord();
                    }
                    int    srcHeight  = meta.ReadShort();
                    int    srcWidth   = meta.ReadShort();
                    int    ySrc       = meta.ReadShort();
                    int    xSrc       = meta.ReadShort();
                    float  destHeight = state.TransformY(meta.ReadShort()) - state.TransformY(0);
                    float  destWidth  = state.TransformX(meta.ReadShort()) - state.TransformX(0);
                    float  yDest      = state.TransformY(meta.ReadShort());
                    float  xDest      = state.TransformX(meta.ReadShort());
                    byte[] b          = new byte[(tsize * 2) - (meta.Length - lenMarker)];
                    for (int k = 0; k < b.Length; ++k)
                    {
                        b[k] = (byte)meta.ReadByte();
                    }
                    try {
                        MemoryStream inb = new MemoryStream(b);
                        Image        bmp = BmpImage.GetImage(inb, true, b.Length);
                        cb.SaveState();
                        cb.Rectangle(xDest, yDest, destWidth, destHeight);
                        cb.Clip();
                        cb.NewPath();
                        bmp.ScaleAbsolute(destWidth * bmp.Width / srcWidth, -destHeight * bmp.Height / srcHeight);
                        bmp.SetAbsolutePosition(xDest - destWidth * xSrc / srcWidth, yDest + destHeight * ySrc / srcHeight - bmp.ScaledHeight);
                        cb.AddImage(bmp);
                        cb.RestoreState();
                    }
                    catch {
                        // empty on purpose
                    }
                    break;
                }
                }
                meta.Skip((tsize * 2) - (meta.Length - lenMarker));
            }
            state.Cleanup(cb);
        }
 /**
  * @see com.itextpdf.text.pdf.PdfArray#add(int[])
  */
 public override bool Add(int[] values)
 {
     throw new ArgumentException(MessageLocalization.GetComposedMessage("illegal.ve.value"));
 }
Beispiel #21
0
        // returns the top parent to include in the catalog
        internal PdfIndirectReference WritePageTree()
        {
            if (pages.Count == 0)
            {
                throw new IOException(MessageLocalization.GetComposedMessage("the.document.has.no.pages"));
            }
            int leaf = 1;
            List <PdfIndirectReference> tParents    = parents;
            List <PdfIndirectReference> tPages      = pages;
            List <PdfIndirectReference> nextParents = new List <PdfIndirectReference>();

            while (true)
            {
                leaf *= leafSize;
                int stdCount   = leafSize;
                int rightCount = tPages.Count % leafSize;
                if (rightCount == 0)
                {
                    rightCount = leafSize;
                }
                for (int p = 0; p < tParents.Count; ++p)
                {
                    int count;
                    int thisLeaf = leaf;
                    if (p == tParents.Count - 1)
                    {
                        count    = rightCount;
                        thisLeaf = pages.Count % leaf;
                        if (thisLeaf == 0)
                        {
                            thisLeaf = leaf;
                        }
                    }
                    else
                    {
                        count = stdCount;
                    }
                    PdfDictionary top = new PdfDictionary(PdfName.PAGES);
                    top.Put(PdfName.COUNT, new PdfNumber(thisLeaf));
                    PdfArray         kids   = new PdfArray();
                    List <PdfObject> intern = kids.ArrayList;
                    foreach (PdfObject obb in tPages.GetRange(p * stdCount, count))
                    {
                        intern.Add(obb);
                    }
                    top.Put(PdfName.KIDS, kids);
                    if (tParents.Count > 1)
                    {
                        if ((p % leafSize) == 0)
                        {
                            nextParents.Add(writer.PdfIndirectReference);
                        }
                        top.Put(PdfName.PARENT, nextParents[p / leafSize]);
                    }
                    writer.AddToBody(top, tParents[p]);
                }
                if (tParents.Count == 1)
                {
                    topParent = tParents[0];
                    return(topParent);
                }
                tPages      = tParents;
                tParents    = nextParents;
                nextParents = new List <PdfIndirectReference>();
            }
        }
 /**
  * @see com.itextpdf.text.pdf.PdfArray#add(int, com.itextpdf.text.pdf.PdfObject)
  */
 public override void Add(int index, PdfObject element)
 {
     throw new ArgumentException(MessageLocalization.GetComposedMessage("illegal.ve.value"));
 }
Beispiel #23
0
        internal override void WriteFont(PdfWriter writer, PdfIndirectReference piRef, Object[] oParams)
        {
            if (this.writer != writer)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("type3.font.used.with.the.wrong.pdfwriter"));
            }
            // Get first & lastchar ...
            int firstChar = 0;

            while (firstChar < usedSlot.Length && !usedSlot[firstChar])
            {
                firstChar++;
            }

            if (firstChar == usedSlot.Length)
            {
                throw new DocumentException(MessageLocalization.GetComposedMessage("no.glyphs.defined.for.type3.font"));
            }
            int lastChar = usedSlot.Length - 1;

            while (lastChar >= firstChar && !usedSlot[lastChar])
            {
                lastChar--;
            }

            int[] widths = new int[lastChar - firstChar + 1];
            int[] invOrd = new int[lastChar - firstChar + 1];

            int invOrdIndx = 0, w = 0;

            for (int u = firstChar; u <= lastChar; u++, w++)
            {
                if (usedSlot[u])
                {
                    invOrd[invOrdIndx++] = u;
                    widths[w]            = widths3[u];
                }
            }
            PdfArray      diffs     = new PdfArray();
            PdfDictionary charprocs = new PdfDictionary();
            int           last      = -1;

            for (int k = 0; k < invOrdIndx; ++k)
            {
                int c = invOrd[k];
                if (c > last)
                {
                    last = c;
                    diffs.Add(new PdfNumber(last));
                }
                ++last;
                int    c2 = invOrd[k];
                String s  = GlyphList.UnicodeToName(c2);
                if (s == null)
                {
                    s = "a" + c2;
                }
                PdfName n = new PdfName(s);
                diffs.Add(n);
                Type3Glyph glyph;
                char2glyph.TryGetValue((char)c2, out glyph);
                PdfStream stream = new PdfStream(glyph.ToPdf(null));
                stream.FlateCompress(compressionLevel);
                PdfIndirectReference refp = writer.AddToBody(stream).IndirectReference;
                charprocs.Put(n, refp);
            }
            PdfDictionary font = new PdfDictionary(PdfName.FONT);

            font.Put(PdfName.SUBTYPE, PdfName.TYPE3);
            if (colorized)
            {
                font.Put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0));
            }
            else
            {
                font.Put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury));
            }
            font.Put(PdfName.FONTMATRIX, new PdfArray(new float[] { 0.001f, 0, 0, 0.001f, 0, 0 }));
            font.Put(PdfName.CHARPROCS, writer.AddToBody(charprocs).IndirectReference);
            PdfDictionary encoding = new PdfDictionary();

            encoding.Put(PdfName.DIFFERENCES, diffs);
            font.Put(PdfName.ENCODING, writer.AddToBody(encoding).IndirectReference);
            font.Put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
            font.Put(PdfName.LASTCHAR, new PdfNumber(lastChar));
            font.Put(PdfName.WIDTHS, writer.AddToBody(new PdfArray(widths)).IndirectReference);
            if (pageResources.HasResources())
            {
                font.Put(PdfName.RESOURCES, writer.AddToBody(pageResources.Resources).IndirectReference);
            }
            writer.AddToBody(font, piRef);
        }
Beispiel #24
0
        /**
         * Compresses the stream.
         * @param compressionLevel the compression level (0 = best speed, 9 = best compression, -1 is default)
         * @since   2.1.3
         */
        virtual public void FlateCompress(int compressionLevel)
        {
            if (!Document.Compress)
            {
                return;
            }
            // check if the flateCompress-method has already been used
            if (compressed)
            {
                return;
            }
            this.compressionLevel = compressionLevel;
            if (inputStream != null)
            {
                compressed = true;
                return;
            }
            // check if a filter already exists
            PdfObject filter = PdfReader.GetPdfObject(Get(PdfName.FILTER));

            if (filter != null)
            {
                if (filter.IsName())
                {
                    if (PdfName.FLATEDECODE.Equals(filter))
                    {
                        return;
                    }
                }
                else if (filter.IsArray())
                {
                    if (((PdfArray)filter).Contains(PdfName.FLATEDECODE))
                    {
                        return;
                    }
                }
                else
                {
                    throw new PdfException(MessageLocalization.GetComposedMessage("stream.could.not.be.compressed.filter.is.not.a.name.or.array"));
                }
            }
            // compress
            MemoryStream          stream = new MemoryStream();
            ZDeflaterOutputStream zip    = new ZDeflaterOutputStream(stream, compressionLevel);

            if (streamBytes != null)
            {
                streamBytes.WriteTo(zip);
            }
            else
            {
                zip.Write(bytes, 0, bytes.Length);
            }
            //zip.Close();
            zip.Finish();
            // update the object
            streamBytes = stream;
            bytes       = null;
            Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length));
            if (filter == null)
            {
                Put(PdfName.FILTER, PdfName.FLATEDECODE);
            }
            else
            {
                PdfArray filters = new PdfArray(filter);
                filters.Add(PdfName.FLATEDECODE);
                Put(PdfName.FILTER, filters);
            }
            compressed = true;
        }
Beispiel #25
0
        // private methods

        /// <summary>
        /// This method checks if the image is a valid JPEG and processes some parameters.
        /// </summary>
        private void ProcessParameters()
        {
            type         = Element.JPEG;
            originalType = ORIGINAL_JPEG;
            Stream istr = null;

            try {
                string errorID;
                if (rawData == null)
                {
                    WebRequest w = WebRequest.Create(url);
                    w.Credentials = CredentialCache.DefaultCredentials;
                    istr          = w.GetResponse().GetResponseStream();
                    errorID       = url.ToString();
                }
                else
                {
                    istr    = new MemoryStream(rawData);
                    errorID = "Byte array";
                }
                if (istr.ReadByte() != 0xFF || istr.ReadByte() != 0xD8)
                {
                    throw new BadElementException(MessageLocalization.GetComposedMessage("1.is.not.a.valid.jpeg.file", errorID));
                }
                bool firstPass = true;
                int  len;
                while (true)
                {
                    int v = istr.ReadByte();
                    if (v < 0)
                    {
                        throw new IOException(MessageLocalization.GetComposedMessage("premature.eof.while.reading.jpg"));
                    }
                    if (v == 0xFF)
                    {
                        int marker = istr.ReadByte();
                        if (firstPass && marker == M_APP0)
                        {
                            firstPass = false;
                            len       = GetShort(istr);
                            if (len < 16)
                            {
                                Utilities.Skip(istr, len - 2);
                                continue;
                            }
                            byte[] bcomp = new byte[JFIF_ID.Length];
                            int    r     = istr.Read(bcomp, 0, bcomp.Length);
                            if (r != bcomp.Length)
                            {
                                throw new BadElementException(MessageLocalization.GetComposedMessage("1.corrupted.jfif.marker", errorID));
                            }
                            bool found = true;
                            for (int k = 0; k < bcomp.Length; ++k)
                            {
                                if (bcomp[k] != JFIF_ID[k])
                                {
                                    found = false;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                Utilities.Skip(istr, len - 2 - bcomp.Length);
                                continue;
                            }
                            Utilities.Skip(istr, 2);
                            int units = istr.ReadByte();
                            int dx    = GetShort(istr);
                            int dy    = GetShort(istr);
                            if (units == 1)
                            {
                                dpiX = dx;
                                dpiY = dy;
                            }
                            else if (units == 2)
                            {
                                dpiX = (int)((float)dx * 2.54f + 0.5f);
                                dpiY = (int)((float)dy * 2.54f + 0.5f);
                            }
                            Utilities.Skip(istr, len - 2 - bcomp.Length - 7);
                            continue;
                        }
                        if (marker == M_APPE)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteappe = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                byteappe[k] = (byte)istr.ReadByte();
                            }
                            if (byteappe.Length >= 12)
                            {
                                string appe = System.Text.ASCIIEncoding.ASCII.GetString(byteappe, 0, 5);
                                if (Util.EqualsIgnoreCase(appe, "adobe"))
                                {
                                    invert = true;
                                }
                            }
                            continue;
                        }
                        if (marker == M_APP2)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteapp2 = new byte[len];
                            for (int k = 0; k < len; ++k)
                            {
                                byteapp2[k] = (byte)istr.ReadByte();
                            }
                            if (byteapp2.Length >= 14)
                            {
                                String app2 = System.Text.ASCIIEncoding.ASCII.GetString(byteapp2, 0, 11);
                                if (app2.Equals("ICC_PROFILE"))
                                {
                                    int order = byteapp2[12] & 0xff;
                                    int count = byteapp2[13] & 0xff;
                                    // some jpeg producers don't know how to count to 1
                                    if (order < 1)
                                    {
                                        order = 1;
                                    }
                                    if (count < 1)
                                    {
                                        count = 1;
                                    }
                                    if (icc == null)
                                    {
                                        icc = new byte[count][];
                                    }
                                    icc[order - 1] = byteapp2;
                                }
                            }
                            continue;
                        }
                        if (marker == M_APPD)
                        {
                            len = GetShort(istr) - 2;
                            byte[] byteappd = new byte[len];
                            for (int k = 0; k < len; k++)
                            {
                                byteappd[k] = (byte)istr.ReadByte();
                            }
                            // search for '8BIM Resolution' marker
                            int j = 0;
                            for (j = 0; j < len - PS_8BIM_RESO.Length; j++)
                            {
                                bool found = true;
                                for (int i = 0; i < PS_8BIM_RESO.Length; i++)
                                {
                                    if (byteappd[j + i] != PS_8BIM_RESO[i])
                                    {
                                        found = false;
                                        break;
                                    }
                                }
                                if (found)
                                {
                                    break;
                                }
                            }

                            j += PS_8BIM_RESO.Length;
                            if (j < len - PS_8BIM_RESO.Length)
                            {
                                // "PASCAL String" for name, i.e. string prefix with length byte
                                // padded to be even length; 2 null bytes if empty
                                byte namelength = byteappd[j];
                                // add length byte
                                namelength++;
                                // add padding
                                if (namelength % 2 == 1)
                                {
                                    namelength++;
                                }
                                // just skip name
                                j += namelength;
                                // size of the resolution data
                                int resosize = (byteappd[j] << 24) + (byteappd[j + 1] << 16) + (byteappd[j + 2] << 8) + byteappd[j + 3];
                                // should be 16
                                if (resosize != 16)
                                {
                                    // fail silently, for now
                                    //System.err.println("DEBUG: unsupported resolution IRB size");
                                    continue;
                                }
                                j += 4;
                                int dx = (byteappd[j] << 8) + byteappd[j + 1];
                                j += 2;
                                // skip 2 unknown bytes
                                j += 2;
                                int unitsx = (byteappd[j] << 8) + byteappd[j + 1];
                                j += 2;
                                // skip 2 unknown bytes
                                j += 2;
                                int dy = (byteappd[j] << 8) + byteappd[j + 1];
                                j += 2;
                                // skip 2 unknown bytes
                                j += 2;
                                int unitsy = (byteappd[j] << 8) + byteappd[j + 1];

                                if (unitsx == 1 || unitsx == 2)
                                {
                                    dx = (unitsx == 2 ? (int)(dx * 2.54f + 0.5f) : dx);
                                    // make sure this is consistent with JFIF data
                                    if (dpiX != 0 && dpiX != dx)
                                    {
                                        //System.err.println("DEBUG: inconsistent metadata (dpiX: " + dpiX + " vs " + dx + ")");
                                    }
                                    else
                                    {
                                        dpiX = dx;
                                    }
                                }
                                if (unitsy == 1 || unitsy == 2)
                                {
                                    dy = (unitsy == 2 ? (int)(dy * 2.54f + 0.5f) : dy);
                                    // make sure this is consistent with JFIF data
                                    if (dpiY != 0 && dpiY != dy)
                                    {
                                        //System.err.println("DEBUG: inconsistent metadata (dpiY: " + dpiY + " vs " + dy + ")");
                                    }
                                    else
                                    {
                                        dpiY = dy;
                                    }
                                }
                            }
                            continue;
                        }
                        firstPass = false;
                        int markertype = MarkerType(marker);
                        if (markertype == VALID_MARKER)
                        {
                            Utilities.Skip(istr, 2);
                            if (istr.ReadByte() != 0x08)
                            {
                                throw new BadElementException(MessageLocalization.GetComposedMessage("1.must.have.8.bits.per.component", errorID));
                            }
                            scaledHeight = GetShort(istr);
                            Top          = scaledHeight;
                            scaledWidth  = GetShort(istr);
                            Right        = scaledWidth;
                            colorspace   = istr.ReadByte();
                            bpc          = 8;
                            break;
                        }
                        else if (markertype == UNSUPPORTED_MARKER)
                        {
                            throw new BadElementException(MessageLocalization.GetComposedMessage("1.unsupported.jpeg.marker.2", errorID, marker));
                        }
                        else if (markertype != NOPARAM_MARKER)
                        {
                            Utilities.Skip(istr, GetShort(istr) - 2);
                        }
                    }
                }
            }
            finally {
                if (istr != null)
                {
                    istr.Close();
                }
            }
            plainWidth  = this.Width;
            plainHeight = this.Height;
            if (icc != null)
            {
                int total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    if (icc[k] == null)
                    {
                        icc = null;
                        return;
                    }
                    total += icc[k].Length - 14;
                }
                byte[] ficc = new byte[total];
                total = 0;
                for (int k = 0; k < icc.Length; ++k)
                {
                    System.Array.Copy(icc[k], 14, ficc, total, icc[k].Length - 14);
                    total += icc[k].Length - 14;
                }
                try {
                    ICC_Profile icc_prof = ICC_Profile.GetInstance(ficc, colorspace);
                    TagICC = icc_prof;
                }
                catch {}
                icc = null;
            }
        }
Beispiel #26
0
        // constructor

        /**
         * Constructs a <CODE>PdfImage</CODE>-object.
         *
         * @param image the <CODE>Image</CODE>-object
         * @param name the <CODE>PdfName</CODE> for this image
         * @throws BadPdfFormatException on error
         */

        public PdfImage(Image image, String name, PdfIndirectReference maskRef) : base()
        {
            this.image = image;
            if (name == null)
            {
                GenerateImgResName(image);
            }
            else
            {
                this.name = new PdfName(name);
            }
            Put(PdfName.TYPE, PdfName.XOBJECT);
            Put(PdfName.SUBTYPE, PdfName.IMAGE);
            Put(PdfName.WIDTH, new PdfNumber(image.Width));
            Put(PdfName.HEIGHT, new PdfNumber(image.Height));
            if (image.Layer != null)
            {
                Put(PdfName.OC, image.Layer.Ref);
            }
            if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 0xff))
            {
                Put(PdfName.IMAGEMASK, PdfBoolean.PDFTRUE);
            }
            if (maskRef != null)
            {
                if (image.Smask)
                {
                    Put(PdfName.SMASK, maskRef);
                }
                else
                {
                    Put(PdfName.MASK, maskRef);
                }
            }
            if (image.IsMask() && image.Inverted)
            {
                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
            }
            if (image.Interpolation)
            {
                Put(PdfName.INTERPOLATE, PdfBoolean.PDFTRUE);
            }
            Stream isp = null;

            try {
                // deal with transparency
                int[] transparency = image.Transparency;
                if (transparency != null && !image.IsMask() && maskRef == null)
                {
                    StringBuilder s = new StringBuilder("[");
                    for (int k = 0; k < transparency.Length; ++k)
                    {
                        s.Append(transparency[k]).Append(' ');
                    }
                    s.Append(']');
                    Put(PdfName.MASK, new PdfLiteral(s.ToString()));
                }
                // Raw Image data
                if (image.IsImgRaw())
                {
                    // will also have the CCITT parameters
                    int colorspace = image.Colorspace;
                    bytes = image.RawData;
                    Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                    int bpc = image.Bpc;
                    if (bpc > 0xff)
                    {
                        if (!image.IsMask())
                        {
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                        Put(PdfName.FILTER, PdfName.CCITTFAXDECODE);
                        int           k           = bpc - Image.CCITTG3_1D;
                        PdfDictionary decodeparms = new PdfDictionary();
                        if (k != 0)
                        {
                            decodeparms.Put(PdfName.K, new PdfNumber(k));
                        }
                        if ((colorspace & Image.CCITT_BLACKIS1) != 0)
                        {
                            decodeparms.Put(PdfName.BLACKIS1, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENCODEDBYTEALIGN) != 0)
                        {
                            decodeparms.Put(PdfName.ENCODEDBYTEALIGN, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENDOFLINE) != 0)
                        {
                            decodeparms.Put(PdfName.ENDOFLINE, PdfBoolean.PDFTRUE);
                        }
                        if ((colorspace & Image.CCITT_ENDOFBLOCK) != 0)
                        {
                            decodeparms.Put(PdfName.ENDOFBLOCK, PdfBoolean.PDFFALSE);
                        }
                        decodeparms.Put(PdfName.COLUMNS, new PdfNumber(image.Width));
                        decodeparms.Put(PdfName.ROWS, new PdfNumber(image.Height));
                        Put(PdfName.DECODEPARMS, decodeparms);
                    }
                    else
                    {
                        switch (colorspace)
                        {
                        case 1:
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0]"));
                            }
                            break;

                        case 3:
                            Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0]"));
                            }
                            break;

                        case 4:
                        default:
                            Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            if (image.Inverted)
                            {
                                Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                            }
                            break;
                        }
                        PdfDictionary additional = image.Additional;
                        if (additional != null)
                        {
                            Merge(additional);
                        }
                        if (image.IsMask() && (image.Bpc == 1 || image.Bpc > 8))
                        {
                            Remove(PdfName.COLORSPACE);
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                        if (image.Deflated)
                        {
                            Put(PdfName.FILTER, PdfName.FLATEDECODE);
                        }
                        else
                        {
                            FlateCompress(image.CompressionLevel);
                        }
                    }
                    return;
                }

                // GIF, JPEG or PNG
                String errorID;
                if (image.RawData == null)
                {
                    WebRequest wr = WebRequest.Create(image.Url);
                    wr.Credentials = CredentialCache.DefaultCredentials;
                    isp            = wr.GetResponse().GetResponseStream();
                    errorID        = image.Url.ToString();
                }
                else
                {
                    isp     = new MemoryStream(image.RawData);
                    errorID = "Byte array";
                }
                switch (image.Type)
                {
                case Image.JPEG:
                    Put(PdfName.FILTER, PdfName.DCTDECODE);
                    if (image.ColorTransform == 0)
                    {
                        PdfDictionary decodeparms = new PdfDictionary();
                        decodeparms.Put(PdfName.COLORTRANSFORM, new PdfNumber(0));
                        Put(PdfName.DECODEPARMS, decodeparms);
                    }
                    switch (image.Colorspace)
                    {
                    case 1:
                        Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                        break;

                    case 3:
                        Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                        break;

                    default:
                        Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                        if (image.Inverted)
                        {
                            Put(PdfName.DECODE, new PdfLiteral("[1 0 1 0 1 0 1 0]"));
                        }
                        break;
                    }
                    Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                case Image.JPEG2000:
                    Put(PdfName.FILTER, PdfName.JPXDECODE);
                    if (image.Colorspace > 0)
                    {
                        switch (image.Colorspace)
                        {
                        case 1:
                            Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                            break;

                        case 3:
                            Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                            break;

                        default:
                            Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
                            break;
                        }
                        Put(PdfName.BITSPERCOMPONENT, new PdfNumber(image.Bpc));
                    }
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                case Image.JBIG2:
                    Put(PdfName.FILTER, PdfName.JBIG2DECODE);
                    Put(PdfName.COLORSPACE, PdfName.DEVICEGRAY);
                    Put(PdfName.BITSPERCOMPONENT, new PdfNumber(1));
                    if (image.RawData != null)
                    {
                        bytes = image.RawData;
                        Put(PdfName.LENGTH, new PdfNumber(bytes.Length));
                        return;
                    }
                    streamBytes = new MemoryStream();
                    TransferBytes(isp, streamBytes, -1);
                    break;

                default:
                    throw new IOException(MessageLocalization.GetComposedMessage("1.is.an.unknown.image.format", errorID));
                }
                if (image.CompressionLevel > NO_COMPRESSION)
                {
                    FlateCompress(image.CompressionLevel);
                }
                Put(PdfName.LENGTH, new PdfNumber(streamBytes.Length));
            }
            finally {
                if (isp != null)
                {
                    try{
                        isp.Close();
                    }
                    catch  {
                        // empty on purpose
                    }
                }
            }
        }
Beispiel #27
0
        protected override void CheckPdfObject(PdfWriter writer, int key, Object obj1)
        {
            if (obj1 is PdfNumber)
            {
                PdfNumber number = (PdfNumber)obj1;
                if (Math.Abs(number.DoubleValue) > maxRealValue && number.ToString().Contains("."))
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("real.number.is.out.of.range"));
                }
            }
            else if (obj1 is PdfString)
            {
                PdfString str = (PdfString)obj1;
                if (str.GetBytes().Length > maxStringLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.string.is.too.long"));
                }
            }
            else if (obj1 is PdfArray)
            {
                PdfArray array = (PdfArray)obj1;
                if (array.Size > maxArrayLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.array.exceeds.length.set.by.PDFA1.standard", array.Length.ToString()));
                }
            }
            else if (obj1 is PdfDictionary)
            {
                PdfDictionary dictionary = (PdfDictionary)obj1;
                if (dictionary.Size > maxDictionaryLength)
                {
                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("pdf.dictionary.is.out.of.bounds"));
                }
                PdfName type = dictionary.GetAsName(PdfName.TYPE);
                if (PdfName.CATALOG.Equals(type))
                {
                    if (!dictionary.Contains(PdfName.METADATA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.contain.metadata"));
                    }

                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.an.aa.entry"));
                    }

                    if (dictionary.Contains(PdfName.NAMES))
                    {
                        PdfDictionary names = GetDirectDictionary(dictionary.Get(PdfName.NAMES));
                        if (names != null && names.Contains(PdfName.EMBEDDEDFILES))
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.document.catalog.dictionary.shall.not.include.embeddedfiles.names.entry"));
                        }
                    }

                    if (CheckStructure(conformanceLevel))
                    {
                        PdfDictionary markInfo = GetDirectDictionary(dictionary.Get(PdfName.MARKINFO));
                        if (markInfo == null || markInfo.GetAsBoolean(PdfName.MARKED) == null || markInfo.GetAsBoolean(PdfName.MARKED).BooleanValue == false)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.shall.include.a.markinfo.dictionary.whose.entry.marked.shall.have.a.value.of.true"));
                        }
                        if (!dictionary.Contains(PdfName.LANG))
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("document.catalog.dictionary.should.contain.lang.entry"));
                        }
                    }
                }
                else if (PdfName.PAGE.Equals(type))
                {
                    if (dictionary.Contains(PdfName.AA))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("page.dictionary.shall.not.include.aa.entry"));
                    }
                }
                else if (PdfName.OUTPUTINTENT.Equals(type))
                {
                    PdfObject destOutputIntent = dictionary.Get(PdfName.DESTOUTPUTPROFILE);
                    if (destOutputIntent != null && pdfaDestOutputIntent != null)
                    {
                        if (pdfaDestOutputIntent.IndRef != destOutputIntent.IndRef)
                        {
                            throw new PdfAConformanceException(obj1,
                                                               MessageLocalization.GetComposedMessage(
                                                                   "if.outputintents.array.more.than.one.entry.the.same.indirect.object"));
                        }
                    }
                    else
                    {
                        pdfaDestOutputIntent = destOutputIntent;
                    }

                    PdfName gts = dictionary.GetAsName(PdfName.S);
                    if (pdfaDestOutputIntent != null)
                    {
                        if (PdfName.GTS_PDFA1.Equals(gts))
                        {
                            if (pdfaOutputIntentColorSpace != null)
                            {
                                throw new PdfAConformanceException(obj1,
                                                                   MessageLocalization.GetComposedMessage("a.pdfa.file.may.have.only.one.pdfa.outputintent"));
                            }
                            pdfaOutputIntentColorSpace = "";
                            ICC_Profile icc_profile = writer.ColorProfile;
                            pdfaOutputIntentColorSpace = Encoding.GetEncoding("US-ASCII").GetString(icc_profile.Data, 16, 4);
                        }
                    }
                    else
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                    }
                }
            }
        }
        /** Converts the human readable text to the characters needed to
         * create a barcode using the specified code set.
         * @param text the text to convert
         * @param ucc <CODE>true</CODE> if it is an UCC/EAN-128. In this case
         * the character FNC1 is added
         * @param codeSet forced code set, or AUTO for optimized barcode.
         * @return the code ready to be fed to getBarsCode128Raw()
         */
        public static string GetRawText(string text, bool ucc, Barcode128CodeSet codeSet)
        {
            String outs = "";
            int    tLen = text.Length;

            if (tLen == 0)
            {
                outs += GetStartSymbol(codeSet);
                if (ucc)
                {
                    outs += FNC1_INDEX;
                }
                return(outs);
            }
            int c = 0;

            for (int k = 0; k < tLen; ++k)
            {
                c = text[k];
                if (c > 127 && c != FNC1)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("there.are.illegal.characters.for.barcode.128.in.1", text));
                }
            }
            c = text[0];
            char currentCode = START_B;
            int  index       = 0;

            if ((codeSet == Barcode128CodeSet.AUTO || codeSet == Barcode128CodeSet.C) && IsNextDigits(text, index, 2))
            {
                currentCode = START_C;
                outs       += currentCode;
                if (ucc)
                {
                    outs += FNC1_INDEX;
                }
                String out2 = GetPackedRawDigits(text, index, 2);
                index += (int)out2[0];
                outs  += out2.Substring(1);
            }
            else if (c < ' ')
            {
                currentCode = START_A;
                outs       += currentCode;
                if (ucc)
                {
                    outs += FNC1_INDEX;
                }
                outs += (char)(c + 64);
                ++index;
            }
            else
            {
                outs += currentCode;
                if (ucc)
                {
                    outs += FNC1_INDEX;
                }
                if (c == FNC1)
                {
                    outs += FNC1_INDEX;
                }
                else
                {
                    outs += (char)(c - ' ');
                }
                ++index;
            }
            if (codeSet != Barcode128CodeSet.AUTO && currentCode != GetStartSymbol(codeSet))
            {
                throw new Exception(MessageLocalization.GetComposedMessage("there.are.illegal.characters.for.barcode.128.in.1", text));
            }
            while (index < tLen)
            {
                switch (currentCode)
                {
                case START_A: {
                    if (codeSet == Barcode128CodeSet.AUTO && IsNextDigits(text, index, 4))
                    {
                        currentCode = START_C;
                        outs       += CODE_AB_TO_C;
                        String out2 = GetPackedRawDigits(text, index, 4);
                        index += (int)out2[0];
                        outs  += out2.Substring(1);
                    }
                    else
                    {
                        c = text[index++];
                        if (c == FNC1)
                        {
                            outs += FNC1_INDEX;
                        }
                        else if (c > '_')
                        {
                            currentCode = START_B;
                            outs       += CODE_AC_TO_B;
                            outs       += (char)(c - ' ');
                        }
                        else if (c < ' ')
                        {
                            outs += (char)(c + 64);
                        }
                        else
                        {
                            outs += (char)(c - ' ');
                        }
                    }
                }
                break;

                case START_B: {
                    if (codeSet == Barcode128CodeSet.AUTO && IsNextDigits(text, index, 4))
                    {
                        currentCode = START_C;
                        outs       += CODE_AB_TO_C;
                        String out2 = GetPackedRawDigits(text, index, 4);
                        index += (int)out2[0];
                        outs  += out2.Substring(1);
                    }
                    else
                    {
                        c = text[index++];
                        if (c == FNC1)
                        {
                            outs += FNC1_INDEX;
                        }
                        else if (c < ' ')
                        {
                            currentCode = START_A;
                            outs       += CODE_BC_TO_A;
                            outs       += (char)(c + 64);
                        }
                        else
                        {
                            outs += (char)(c - ' ');
                        }
                    }
                }
                break;

                case START_C: {
                    if (IsNextDigits(text, index, 2))
                    {
                        String out2 = GetPackedRawDigits(text, index, 2);
                        index += (int)out2[0];
                        outs  += out2.Substring(1);
                    }
                    else
                    {
                        c = text[index++];
                        if (c == FNC1)
                        {
                            outs += FNC1_INDEX;
                        }
                        else if (c < ' ')
                        {
                            currentCode = START_A;
                            outs       += CODE_BC_TO_A;
                            outs       += (char)(c + 64);
                        }
                        else
                        {
                            currentCode = START_B;
                            outs       += CODE_AC_TO_B;
                            outs       += (char)(c - ' ');
                        }
                    }
                }
                break;
                }
                if (codeSet != Barcode128CodeSet.AUTO && currentCode != GetStartSymbol(codeSet))
                {
                    throw new Exception(MessageLocalization.GetComposedMessage("there.are.illegal.characters.for.barcode.128.in.1", text));
                }
            }
            return(outs);
        }
Beispiel #29
0
 protected override void CheckAnnotation(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is PdfFormField)
     {
         PdfFormField field = (PdfFormField)obj1;
         if (!field.Contains(PdfName.SUBTYPE))
         {
             return;
         }
         if (field.Contains(PdfName.AA) || field.Contains(PdfName.A))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("widget.annotation.dictionary.or.field.dictionary.shall.not.include.a.or.aa.entry"));
         }
     }
     if (obj1 is PdfAnnotation)
     {
         PdfAnnotation annot   = (PdfAnnotation)obj1;
         PdfName       subtype = annot.Get(PdfName.SUBTYPE) as PdfName;
         if (subtype != null && !allowedAnnotTypes.Contains(subtype))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("annotation.type.1.not.allowed", subtype.ToString()));
         }
         PdfNumber ca = annot.GetAsNumber(PdfName.CA);
         if (ca != null && ca.FloatValue != 1.0)
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("an.annotation.dictionary.shall.not.contain.the.ca.key.with.a.value.other.than.1"));
         }
         PdfNumber f = annot.GetAsNumber(PdfName.F);
         if (f == null)
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("an.annotation.dictionary.shall.contain.the.f.key"));
         }
         int flags = f.IntValue;
         if (CheckFlag(flags, PdfAnnotation.FLAGS_PRINT) == false || CheckFlag(flags, PdfAnnotation.FLAGS_HIDDEN) ||
             CheckFlag(flags, PdfAnnotation.FLAGS_INVISIBLE) || CheckFlag(flags, PdfAnnotation.FLAGS_NOVIEW))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("the.f.keys.print.flag.bit.shall.be.set.to.1.and.its.hidden.invisible.and.noview.flag.bits.shall.be.set.to.0"));
         }
         if (PdfName.TEXT.Equals(annot.GetAsName(PdfName.SUBTYPE)))
         {
             if (CheckFlag(flags, PdfAnnotation.FLAGS_NOZOOM) == false || CheckFlag(flags, PdfAnnotation.FLAGS_NOROTATE) == false)
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("text.annotations.should.set.the.nozoom.and.norotate.flag.bits.of.the.f.key.to.1"));
             }
         }
         if (annot.Contains(PdfName.C) || annot.Contains(PdfName.IC))
         {
             ICC_Profile colorProfile = ((PdfAWriter)writer).ColorProfile;
             String      cs           = "";
             cs = System.Text.Encoding.ASCII.GetString(colorProfile.Data, 16, 4);
             cs = cs.Trim();
             if (!"RGB".Equals(cs.ToUpper()))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("destoutputprofile.in.the.pdfa1.outputintent.dictionary.shall.be.rgb"));
             }
         }
         PdfDictionary ap = GetDirectDictionary(annot.Get(PdfName.AP));
         if (ap != null)
         {
             if (ap.Contains(PdfName.R) || ap.Contains(PdfName.D))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("appearance.dictionary.shall.contain.only.the.n.key.with.stream.value"));
             }
             PdfObject n = ap.Get(PdfName.N);
             if (!(n is PdfIndirectReference))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("appearance.dictionary.shall.contain.only.the.n.key.with.stream.value"));
             }
         }
         if (PdfName.WIDGET.Equals(annot.GetAsName(PdfName.SUBTYPE)) && (annot.Contains(PdfName.AA) || annot.Contains(PdfName.A)))
         {
             throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("widget.annotation.dictionary.or.field.dictionary.shall.not.include.a.or.aa.entry"));
         }
         if (CheckStructure(conformanceLevel))
         {
             if (contentAnnotations.Contains(subtype) && !annot.Contains(PdfName.CONTENTS))
             {
                 throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("annotation.of.type.1.should.have.contents.key", subtype.ToString()));
             }
         }
     }
 }
Beispiel #30
0
        /**
         * Gets an encoded byte array with OCSP validation. The method should not throw an exception.
         * @param checkCert to certificate to check
         * @param rootCert the parent certificate
         * @param the url to get the verification. It it's null it will be taken
         * from the check cert or from other implementation specific source
         * @return  a byte array with the validation or null if the validation could not be obtained
         */
        public virtual byte[] GetEncoded(X509Certificate checkCert, X509Certificate rootCert, String url)
        {
            try {
                if (checkCert == null || rootCert == null)
                {
                    return(null);
                }
                if (url == null)
                {
                    url = CertificateUtil.GetOCSPURL(checkCert);
                }
                if (url == null)
                {
                    return(null);
                }
                OcspReq        request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber);
                byte[]         array   = request.GetEncoded();
                HttpWebRequest con     = (HttpWebRequest)WebRequest.Create(url);
                con.ContentLength = array.Length;
                con.ContentType   = "application/ocsp-request";
                con.Accept        = "application/ocsp-response";
                con.Method        = "POST";
                Stream outp = con.GetRequestStream();
                outp.Write(array, 0, array.Length);
                outp.Close();
                HttpWebResponse response = (HttpWebResponse)con.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("invalid.http.response.1", (int)response.StatusCode));
                }
                Stream   inp          = response.GetResponseStream();
                OcspResp ocspResponse = new OcspResp(inp);
                inp.Close();
                response.Close();

                if (ocspResponse.Status != 0)
                {
                    throw new IOException(MessageLocalization.GetComposedMessage("invalid.status.1", ocspResponse.Status));
                }
                BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();
                if (basicResponse != null)
                {
                    SingleResp[] responses = basicResponse.Responses;
                    if (responses.Length == 1)
                    {
                        SingleResp resp   = responses[0];
                        Object     status = resp.GetCertStatus();
                        if (status == CertificateStatus.Good)
                        {
                            return(basicResponse.GetEncoded());
                        }
                        else if (status is Org.BouncyCastle.Ocsp.RevokedStatus)
                        {
                            throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.revoked"));
                        }
                        else
                        {
                            throw new IOException(MessageLocalization.GetComposedMessage("ocsp.status.is.unknown"));
                        }
                    }
                }
            }
            catch (Exception ex) {
                if (LOGGER.IsLogging(Level.ERROR))
                {
                    LOGGER.Error("OcspClientBouncyCastle", ex);
                }
            }
            return(null);
        }