Beispiel #1
0
 protected override void CheckEmbeddedFile(PdfDictionary embeddedFile)
 {
     PdfObject _params = GetDirectObject(embeddedFile.Get(PdfName.PARAMS));
     if (_params == null) {
         throw new PdfAConformanceException(embeddedFile,
             MessageLocalization.GetComposedMessage("embedded.file.shall.contain.valid.params.key"));
     } else if (_params.IsDictionary()) {
         PdfObject modDate = ((PdfDictionary) _params).Get(PdfName.MODDATE);
         if (modDate == null || !(modDate is PdfString)) {
             throw new PdfAConformanceException(embeddedFile,
                 MessageLocalization.GetComposedMessage("embedded.file.shall.contain.params.key.with.valid.moddate.key"));
         }
     }
 }
Beispiel #2
0
        public List <LocationModel> ReadPdfFile(String fileName)
        {
            string strText = string.Empty;


            PdfReader reader = new PdfReader(fileName);

            var locationList = new List <LocationModel>();

            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                var p        = reader.GetPageN(page);
                var pageSize = reader.GetPageSizeWithRotation(page);
                var rotation = pageSize.Rotation;

                float factor;
                if (pageSize.Height > pageSize.Width)
                {
                    //Portait
                    factor = 2000 / pageSize.Width;
                }
                else
                {
                    //landscape
                    factor = 1700 / pageSize.Height;
                }

                var annotationList = p.GetAsArray(iTextSharp.text.pdf.PdfName.ANNOTS);

                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));


                foreach (PdfObject annot in annotationList.ArrayList)
                {
                    PdfDictionary annotationDict = (PdfDictionary)PdfReader.GetPdfObject(annot);
                    var           subtype        = annotationDict.Get(PdfName.SUBTYPE);
                    if (subtype == PdfName.FREETEXT)
                    {
                        var content = annotationDict.GetAsString(PdfName.CONTENTS);
                        var tmp     = annotationDict.GetAsArray(PdfName.RECT);
                        var rect    = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue, tmp.GetAsNumber(2).FloatValue, tmp.GetAsNumber(3).FloatValue);

                        var left = Convert.ToDouble(rect.Right);
                        var top  = Convert.ToDouble(pageSize.Height - rect.Top); // Convert Bottom to Top Coordinate System

                        //Comment this line if the coordinate is weird

                        /*
                         * if (rotation == 90)
                         * {
                         * left = pageSize.Height > pageSize.Width ? Convert.ToDouble(rect[3].ToString()) : pageSize.Height - float.Parse(rect[2].ToString());
                         * top = pageSize.Height > pageSize.Width ? float.Parse(rect[2].ToString()) : float.Parse(rect[3].ToString());
                         * }
                         */

                        //Comment this line if the coordinate is weird
                        //left = Convert.ToDouble(rect[3].ToString());
                        //top = Convert.ToDouble(rect[0].ToString());

                        var offsetX = 30;
                        var offsetY = 20;

                        var location = new LocationModel {
                            X     = Convert.ToInt32(Double.Parse(left.ToString()) * factor) + offsetX,
                            Y     = Convert.ToInt32(Double.Parse(top.ToString()) * factor) + offsetY,
                            Title = content.ToString()
                        };
                        locationList.Add(location);
                    }
                }
            }

            reader.Close();

            return(locationList);
        }
Beispiel #3
0
        Image GetImage()
        {
            ReadPng();
            int pal0   = 0;
            int palIdx = 0;

            palShades = false;
            if (trans != null)
            {
                for (int k = 0; k < trans.Length; ++k)
                {
                    int n = trans[k] & 0xff;
                    if (n == 0)
                    {
                        ++pal0;
                        palIdx = k;
                    }
                    if (n != 0 && n != 255)
                    {
                        palShades = true;
                        break;
                    }
                }
            }
            if ((colorType & 4) != 0)
            {
                palShades = true;
            }
            genBWMask = (!palShades && (pal0 > 1 || transRedGray >= 0));
            if (!palShades && !genBWMask && pal0 == 1)
            {
                additional.Put(PdfName.MASK, new PdfLiteral("[" + palIdx + " " + palIdx + "]"));
            }
            bool needDecode = (interlaceMethod == 1) || (bitDepth == 16) || ((colorType & 4) != 0) || palShades || genBWMask;

            switch (colorType)
            {
            case 0:
                inputBands = 1;
                break;

            case 2:
                inputBands = 3;
                break;

            case 3:
                inputBands = 1;
                break;

            case 4:
                inputBands = 2;
                break;

            case 6:
                inputBands = 4;
                break;
            }
            if (needDecode)
            {
                DecodeIdat();
            }
            int components = inputBands;

            if ((colorType & 4) != 0)
            {
                --components;
            }
            int bpc = bitDepth;

            if (bpc == 16)
            {
                bpc = 8;
            }
            Image img;

            if (image != null)
            {
                img = Image.GetInstance(width, height, components, bpc, image);
            }
            else
            {
                img          = new ImgRaw(width, height, components, bpc, idat.ToArray());
                img.Deflated = true;
                PdfDictionary decodeparms = new PdfDictionary();
                decodeparms.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(bitDepth));
                decodeparms.Put(PdfName.PREDICTOR, new PdfNumber(15));
                decodeparms.Put(PdfName.COLUMNS, new PdfNumber(width));
                decodeparms.Put(PdfName.COLORS, new PdfNumber((colorType == 3 || (colorType & 2) == 0) ? 1 : 3));
                additional.Put(PdfName.DECODEPARMS, decodeparms);
            }
            if (additional.Get(PdfName.COLORSPACE) == null)
            {
                additional.Put(PdfName.COLORSPACE, GetColorspace());
            }
            if (intent != null)
            {
                additional.Put(PdfName.INTENT, intent);
            }
            if (additional.Size > 0)
            {
                img.Additional = additional;
            }
            if (icc_profile != null)
            {
                img.TagICC = icc_profile;
            }
            if (palShades)
            {
                Image im2 = Image.GetInstance(width, height, 1, 8, smask);
                im2.MakeMask();
                img.ImageMask = im2;
            }
            if (genBWMask)
            {
                Image im2 = Image.GetInstance(width, height, 1, 1, smask);
                im2.MakeMask();
                img.ImageMask = im2;
            }
            img.SetDpi(dpiX, dpiY);
            img.XYRatio      = XYRatio;
            img.OriginalType = Image.ORIGINAL_PNG;
            return(img);
        }
Beispiel #4
0
        private void CompressPdf(string fileId, FileInfo fi)
        {
            //ITextSharp是一个生成Pdf文件的开源项目
            PdfReader reader = new PdfReader(fi.FullName);

            if (File.Exists(@"D:\Compress\" + fileId + ".pdf"))//先判断对应文件ID的压缩文件是否存在  如果存在,将其删除
            {
                File.Delete(@"D:\Compress\" + fileId + ".pdf");
            }
            string newPath = @"D:\Compress\" + fileId + ".pdf";

            using (FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (PdfStamper stamper = new PdfStamper(reader, fs))
                {
                    #region
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfDictionary page      = reader.GetPageN(i);
                        PdfDictionary resources = (PdfDictionary)PdfReader.GetPdfObject(page.Get(PdfName.RESOURCES));
                        PdfDictionary xobject   = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT));
                        if (xobject != null)
                        {
                            PdfObject obj;
                            foreach (PdfName name in xobject.Keys)
                            {
                                obj = xobject.Get(name);
                                if (obj.IsIndirect())
                                {
                                    //Get the current key as a PDF object
                                    PdfDictionary imgObject = (PdfDictionary)PdfReader.GetPdfObject(obj);
                                    //See if its an image
                                    if (imgObject.Get(PdfName.SUBTYPE).Equals(PdfName.IMAGE))
                                    {
                                        //NOTE: There's a bunch of different types of filters, I'm only handing the simplest one here which is basically raw JPG, you'll have to research others
                                        if (imgObject.Get(PdfName.FILTER).Equals(PdfName.DCTDECODE))
                                        {
                                            //Get the raw bytes of the current image
                                            byte[] oldBytes = PdfReader.GetStreamBytesRaw((PRStream)imgObject);
                                            //Will hold bytes of the compressed image later
                                            byte[] newBytes;
                                            //Wrap a stream around our original image
                                            using (MemoryStream sourceMS = new MemoryStream(oldBytes))
                                            {
                                                //Convert the bytes into a .Net image
                                                using (System.Drawing.Image oldImage = Bitmap.FromStream(sourceMS))
                                                {
                                                    //Shrink the image to 90% of the original
                                                    using (System.Drawing.Image newImage = ShrinkImage(oldImage, 40 / 100f))
                                                    {
                                                        //Convert the image to bytes using JPG at 85%
                                                        newBytes = ConvertImageToBytes(newImage, 35);
                                                    }
                                                }
                                            }
                                            //Create a new iTextSharp image from our bytes
                                            iTextSharp.text.Image compressedImage = iTextSharp.text.Image.GetInstance(newBytes);
                                            //Kill off the old image
                                            PdfReader.KillIndirect(obj);
                                            //Add our image in its place
                                            stamper.Writer.AddDirectImageSimple(compressedImage, (PRIndirectReference)obj);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            reader.Close(); reader.Dispose();
        }
Beispiel #5
0
        private Image getImage()
        {
            readPng();
            var pal0   = 0;
            var palIdx = 0;

            _palShades = false;
            if (_trans != null)
            {
                for (var k = 0; k < _trans.Length; ++k)
                {
                    var n = _trans[k] & 0xff;
                    if (n == 0)
                    {
                        ++pal0;
                        palIdx = k;
                    }
                    if (n != 0 && n != 255)
                    {
                        _palShades = true;
                        break;
                    }
                }
            }
            if ((_colorType & 4) != 0)
            {
                _palShades = true;
            }

            _genBwMask = (!_palShades && (pal0 > 1 || _transRedGray >= 0));
            if (!_palShades && !_genBwMask && pal0 == 1)
            {
                _additional.Put(PdfName.Mask, new PdfLiteral("[" + palIdx + " " + palIdx + "]"));
            }
            var needDecode = (_interlaceMethod == 1) || (_bitDepth == 16) || ((_colorType & 4) != 0) || _palShades || _genBwMask;

            switch (_colorType)
            {
            case 0:
                _inputBands = 1;
                break;

            case 2:
                _inputBands = 3;
                break;

            case 3:
                _inputBands = 1;
                break;

            case 4:
                _inputBands = 2;
                break;

            case 6:
                _inputBands = 4;
                break;
            }
            if (needDecode)
            {
                decodeIdat();
            }

            var components = _inputBands;

            if ((_colorType & 4) != 0)
            {
                --components;
            }

            var bpc = _bitDepth;

            if (bpc == 16)
            {
                bpc = 8;
            }

            Image img;

            if (_image != null)
            {
                if (_colorType == 3)
                {
                    img = new ImgRaw(_width, _height, components, bpc, _image);
                }
                else
                {
                    img = Image.GetInstance(_width, _height, components, bpc, _image);
                }
            }
            else
            {
                img = new ImgRaw(_width, _height, components, bpc, _idat.ToArray())
                {
                    Deflated = true
                };
                var decodeparms = new PdfDictionary();
                decodeparms.Put(PdfName.Bitspercomponent, new PdfNumber(_bitDepth));
                decodeparms.Put(PdfName.Predictor, new PdfNumber(15));
                decodeparms.Put(PdfName.Columns, new PdfNumber(_width));
                decodeparms.Put(PdfName.Colors, new PdfNumber((_colorType == 3 || (_colorType & 2) == 0) ? 1 : 3));
                _additional.Put(PdfName.Decodeparms, decodeparms);
            }
            if (_additional.Get(PdfName.Colorspace) == null)
            {
                _additional.Put(PdfName.Colorspace, getColorspace());
            }

            if (_intent != null)
            {
                _additional.Put(PdfName.Intent, _intent);
            }

            if (_additional.Size > 0)
            {
                img.Additional = _additional;
            }

            if (_iccProfile != null)
            {
                img.TagIcc = _iccProfile;
            }

            if (_palShades)
            {
                var im2 = Image.GetInstance(_width, _height, 1, 8, _smask);
                im2.MakeMask();
                img.ImageMask = im2;
            }
            if (_genBwMask)
            {
                var im2 = Image.GetInstance(_width, _height, 1, 1, _smask);
                im2.MakeMask();
                img.ImageMask = im2;
            }
            img.SetDpi(_dpiX, _dpiY);
            img.XyRatio      = _xyRatio;
            img.OriginalType = Image.ORIGINAL_PNG;
            return(img);
        }
Beispiel #6
0
 private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] password)
 {
     try {
         if (password == null)
         {
             password = new byte[0];
         }
         byte[]    oValue  = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.O));
         byte[]    uValue  = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.U));
         byte[]    oeValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.OE));
         byte[]    ueValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.UE));
         byte[]    perms   = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.Perms));
         PdfNumber pValue  = (PdfNumber)encryptionDictionary.Get(PdfName.P);
         this.permissions = pValue.LongValue();
         IDigest md = Org.BouncyCastle.Security.DigestUtilities.GetDigest("SHA-256");
         md.Update(password, 0, Math.Min(password.Length, 127));
         md.Update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGTH);
         md.Update(uValue, 0, OU_LENGTH);
         byte[] hash = md.Digest();
         usedOwnerPassword = CompareArray(hash, oValue, 32);
         if (usedOwnerPassword)
         {
             md.Update(password, 0, Math.Min(password.Length, 127));
             md.Update(oValue, KEY_SALT_OFFSET, SALT_LENGTH);
             md.Update(uValue, 0, OU_LENGTH);
             hash = md.Digest();
             AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash);
             nextObjectKey = ac.ProcessBlock(oeValue, 0, oeValue.Length);
         }
         else
         {
             md.Update(password, 0, Math.Min(password.Length, 127));
             md.Update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGTH);
             hash = md.Digest();
             if (!CompareArray(hash, uValue, 32))
             {
                 throw new BadPasswordException(PdfException.BadUserPassword);
             }
             md.Update(password, 0, Math.Min(password.Length, 127));
             md.Update(uValue, KEY_SALT_OFFSET, SALT_LENGTH);
             hash = md.Digest();
             AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash);
             nextObjectKey = ac.ProcessBlock(ueValue, 0, ueValue.Length);
         }
         nextObjectKeySize = 32;
         AESCipherCBCnoPad ac_1     = new AESCipherCBCnoPad(false, nextObjectKey);
         byte[]            decPerms = ac_1.ProcessBlock(perms, 0, perms.Length);
         if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b')
         {
             throw new BadPasswordException(PdfException.BadUserPassword);
         }
         permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms
                                                                                                             [2] & 0xff) << 24);
         encryptMetadata = decPerms[8] == (byte)'T';
     }
     catch (BadPasswordException ex) {
         throw;
     }
     catch (Exception ex) {
         throw new PdfException(PdfException.PdfEncryption, ex);
     }
 }
Beispiel #7
0
        virtual public void CopyTaggedPdf6()
        {
            InitializeDocument("6");
            PdfReader reader = new PdfReader(SOURCE11);
            int       n      = 12;

            copy.AddPage(copy.GetImportedPage(reader, 1, true));
            copy.AddPage(copy.GetImportedPage(reader, 25, true));
            copy.AddPage(copy.GetImportedPage(reader, 7, true));
            copy.AddPage(copy.GetImportedPage(reader, 48, true));
            copy.AddPage(copy.GetImportedPage(reader, 50, true));
            copy.AddPage(copy.GetImportedPage(reader, 2, true));
            copy.AddPage(copy.GetImportedPage(reader, 8, true));
            copy.AddPage(copy.GetImportedPage(reader, 90, true));
            document.Close();
            reader.Close();

            reader = new PdfReader(output);
            PdfDictionary structTreeRoot =
                VerifyIsDictionary(reader.Catalog.GetDirectObject(PdfName.STRUCTTREEROOT), NO_STRUCT_TREE_ROOT);

            VerifyArraySize(structTreeRoot.Get(PdfName.K), 6, "Invalid count of kids in StructTreeRoot");
            PdfObject obj = PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE));

            VerifyIsDictionary(obj, NO_PARENT_TREE);
            PdfArray array = ((PdfDictionary)obj).GetAsArray(PdfName.NUMS);

            VerifyArraySize(array, n * 2, "Nums");
            int[] nums = new int[] { 5, 0, 33, 12, 0, 48, 35, 182, 0, 0, 17, 37 };
            for (int i = 0; i < n; ++i)
            {
                VerifyArraySize(PdfStructTreeController.GetDirectObject(array.GetDirectObject(i * 2 + 1)), nums[i],
                                "Nums of page " + (i + 1), true);
            }

            PdfDictionary ClassMap =
                VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.CLASSMAP)),
                                   NO_CLASS_MAP);

            if (ClassMap.Size != 27)
            {
                Assert.Fail("ClassMap incorrect");
            }
            String[] CMs = new String[]
            {
                "CM118", "CM117", "CM133", "CM47", "CM46", "CM114", "CM43", "CM110", "CM21", "CM22", "CM26", "CM27",
                "CM145", "CM128", "CM29", "CM56", "CM1", "CM2", "CM72", "CM16", "CM34", "CM17", "CM14", "CM15",
                "CM119", "CM12", "CM13"
            };
            for (int i = 0; i < CMs.Length; ++i)
            {
                VerifyIsDictionary(PdfStructTreeController.GetDirectObject(ClassMap.Get(new PdfName(CMs[i]))),
                                   "ClassMap.does.not.contain.\"" + CMs[i] + "\"");
            }

            PdfDictionary RoleMap =
                VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.ROLEMAP)),
                                   NO_ROLE_MAP);

            if (!PdfName.SPAN.Equals(RoleMap.Get(new PdfName("ParagraphSpan"))))
            {
                throw new BadPdfFormatException("RoleMap does not contain \"ParagraphSpan\".");
            }
            //if (reader.eofPos != 249068) Assert.Fail("Invalid size of pdf.");

            reader.Close();
            CompareResults("6");
        }
Beispiel #8
0
        private int GetCommonNumsCount(String filename)
        {
            PdfReader     reader         = new PdfReader(filename);
            PdfDictionary structTreeRoot = reader.Catalog.GetAsDict(PdfName.STRUCTTREEROOT);
            PdfArray      kids           = ((PdfDictionary)PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE))).GetAsArray(PdfName.KIDS);
            int           cnt            = 0;

            for (int i = 0; i < kids.Size; i++)
            {
                PdfArray nums = kids.GetAsDict(i).GetAsArray(PdfName.NUMS);
                cnt += nums.Size;
            }
            reader.Close();
            return(cnt);
        }
        /**
         * Business logic that checks if a certain object is in conformance with PDF/X.
         * @param writer    the writer that is supposed to write the PDF/X file
         * @param key       the type of PDF/X conformance that has to be checked
         * @param obj1      the object that is checked for conformance
         */
        public static void CheckPDFXConformance(PdfWriter writer, int key, Object obj1)
        {
            if (writer == null || !writer.IsPdfX())
            {
                return;
            }
            int conf = writer.PDFXConformance;

            switch (key)
            {
            case PDFXKEY_COLOR:
                switch (conf)
                {
                case PdfWriter.PDFX1A2001:
                    if (obj1 is ExtendedColor)
                    {
                        ExtendedColor ec = (ExtendedColor)obj1;
                        switch (ec.Type)
                        {
                        case ExtendedColor.TYPE_CMYK:
                        case ExtendedColor.TYPE_GRAY:
                            return;

                        case ExtendedColor.TYPE_RGB:
                            throw new PdfXConformanceException("Colorspace RGB is not allowed.");

                        case ExtendedColor.TYPE_SEPARATION:
                            SpotColor sc = (SpotColor)ec;
                            CheckPDFXConformance(writer, PDFXKEY_COLOR, sc.PdfSpotColor.AlternativeCS);
                            break;

                        case ExtendedColor.TYPE_SHADING:
                            ShadingColor xc = (ShadingColor)ec;
                            CheckPDFXConformance(writer, PDFXKEY_COLOR, xc.PdfShadingPattern.Shading.ColorSpace);
                            break;

                        case ExtendedColor.TYPE_PATTERN:
                            PatternColor pc = (PatternColor)ec;
                            CheckPDFXConformance(writer, PDFXKEY_COLOR, pc.Painter.DefaultColor);
                            break;
                        }
                    }
                    else if (obj1 is Color)
                    {
                        throw new PdfXConformanceException("Colorspace RGB is not allowed.");
                    }
                    break;
                }
                break;

            case PDFXKEY_CMYK:
                break;

            case PDFXKEY_RGB:
                if (conf == PdfWriter.PDFX1A2001)
                {
                    throw new PdfXConformanceException("Colorspace RGB is not allowed.");
                }
                break;

            case PDFXKEY_FONT:
                if (!((BaseFont)obj1).IsEmbedded())
                {
                    throw new PdfXConformanceException("All the fonts must be embedded. This one isn't: " + ((BaseFont)obj1).PostscriptFontName);
                }
                break;

            case PDFXKEY_IMAGE:
                PdfImage image = (PdfImage)obj1;
                if (image.Get(PdfName.SMASK) != null)
                {
                    throw new PdfXConformanceException("The /SMask key is not allowed in images.");
                }
                switch (conf)
                {
                case PdfWriter.PDFX1A2001:
                    PdfObject cs = image.Get(PdfName.COLORSPACE);
                    if (cs == null)
                    {
                        return;
                    }
                    if (cs.IsName())
                    {
                        if (PdfName.DEVICERGB.Equals(cs))
                        {
                            throw new PdfXConformanceException("Colorspace RGB is not allowed.");
                        }
                    }
                    else if (cs.IsArray())
                    {
                        if (PdfName.CALRGB.Equals(((PdfArray)cs)[0]))
                        {
                            throw new PdfXConformanceException("Colorspace CalRGB is not allowed.");
                        }
                    }
                    break;
                }
                break;

            case PDFXKEY_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 PdfXConformanceException("Blend mode " + obj.ToString() + " not allowed.");
                }
                obj = gs.Get(PdfName.CA);
                double v = 0.0;
                if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0)
                {
                    throw new PdfXConformanceException("Transparency is not allowed: /CA = " + v);
                }
                obj = gs.Get(PdfName.ca_);
                v   = 0.0;
                if (obj != null && (v = ((PdfNumber)obj).DoubleValue) != 1.0)
                {
                    throw new PdfXConformanceException("Transparency is not allowed: /ca = " + v);
                }
                break;

            case PDFXKEY_LAYER:
                throw new PdfXConformanceException("Layers are not allowed.");
            }
        }
Beispiel #10
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))
                        {
                            if (LOGGER.IsLogging(Level.WARN))
                            {
                                LOGGER.Warn(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))
                {
                    isCheckOutputIntent = true;
                    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"));
                    }
                }
            }
        }
        private void CreateRawContent(List <byte> rawContent, PdfObject pdfObject)
        {
            Type pdfObjectType = pdfObject.GetType();

            if (pdfObjectType == typeof(PdfName))
            {
                rawContent.AddRange(pdfObject.GetBytes());
            }
            else if (pdfObjectType == typeof(PdfLiteral))
            {
                string t = pdfObject.ToString();

                if (t == "EMC" || t == "BMC" || t == "BDC")
                {
                    rawContent.Add(BYTE_SPACE);
                }

                rawContent.AddRange(pdfObject.GetBytes());

                if (t == "BT")
                {
                    rawContent.AddRange(BYTES_LINE_BREAK_WINDOWS);
                }

                if (t == "EMC" || t == "BMC" || t == "BDC")
                {
                    rawContent.Add(BYTE_SPACE);
                }
            }
            else if (pdfObjectType == typeof(PdfNumber))
            {
                rawContent.AddRange(pdfObject.GetBytes());
            }
            else if (pdfObjectType == typeof(PdfString))
            {
                rawContent.Add(BYTE_ROUND_OPENING_BRACKET);

                byte[] objectBuffer = pdfObject.GetBytes();

                foreach (byte objectByte in objectBuffer)
                {
                    switch (objectByte)
                    {
                    case BYTE_CARRIAGE_RETURN:
                    {
                        rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_r);
                        break;
                    }

                    case BYTE_LINE_FEED:
                    {
                        rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_n);
                        break;
                    }

                    case BYTE_HORIZONTAL_TAB:
                    {
                        rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_t);
                        break;
                    }

                    case BYTE_BACKSPACE:
                    {
                        rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_b);
                        break;
                    }

                    case BYTE_FORM_FEED:
                    {
                        rawContent.AddRange(BYTES_REVERSE_SOLIDUS_AND_CHAR_f);
                        break;
                    }

                    case BYTE_ROUND_OPENING_BRACKET:
                    case BYTE_ROUND_CLOSING_BRACKET:
                    case BYTE_REVERSE_SOLIDUS:
                    {
                        rawContent.Add(BYTE_ESCAPE_CHAR);
                        rawContent.Add(objectByte);
                        break;
                    }

                    default:
                    {
                        rawContent.Add(objectByte);
                        break;
                    }
                    }
                }

                rawContent.Add(BYTE_ROUND_CLOSING_BRACKET);
            }
            else if (pdfObjectType == typeof(PdfDictionary))
            {
                rawContent.AddRange(BYTES_DOUBLE_ANGLE_OPENING_BRACKETS);

                PdfDictionary dict = pdfObject as PdfDictionary;

                foreach (PdfObject key in dict.Keys)
                {
                    CreateRawContent(rawContent, key);

                    PdfName keyName = key as PdfName;

                    this.CreateRawContent(rawContent, dict.Get(keyName));
                }

                rawContent.AddRange(BYTES_DOUBLE_ANGLE_CLOSING_BRACKETS);
            }
            else if (pdfObjectType == typeof(PdfArray))
            {
                rawContent.Add(BYTE_SQUARE_OPENING_BRACKET);

                PdfArray pa = pdfObject as PdfArray;

                foreach (PdfObject obj in pa.ArrayList)
                {
                    this.CreateRawContent(rawContent, obj);
                }

                rawContent.Add(BYTE_SQUARE_CLOSING_BRACKET);
            }
            else
            {
                rawContent.AddRange(pdfObject.GetBytes());
            }

            rawContent.Add(BYTE_SPACE);
        }
Beispiel #12
0
        private static void SeparateKids(PdfDictionary structElem, ICollection <PdfObject> firstPartElems, StructureTreeCopier.LastClonedAncestor
                                         lastCloned, PdfDocument document)
        {
            PdfObject k = structElem.Get(PdfName.K);

            // If /K entry is not a PdfArray - it would be a kid which we won't clone at the moment, because it won't contain
            // kids from both parts at the same time. It would either be cloned as an ancestor later, or not cloned at all.
            // If it's kid is struct elem - it would definitely be structElem from the first part, so we simply call separateKids for it.
            if (!k.IsArray())
            {
                if (k.IsDictionary() && PdfStructElem.IsStructElem((PdfDictionary)k))
                {
                    SeparateKids((PdfDictionary)k, firstPartElems, lastCloned, document);
                }
            }
            else
            {
                PdfArray kids = (PdfArray)k;
                for (int i = 0; i < kids.Size(); ++i)
                {
                    PdfObject     kid     = kids.Get(i);
                    PdfDictionary dictKid = null;
                    if (kid.IsDictionary())
                    {
                        dictKid = (PdfDictionary)kid;
                    }
                    if (dictKid != null && PdfStructElem.IsStructElem(dictKid))
                    {
                        if (firstPartElems.Contains(kid))
                        {
                            SeparateKids((PdfDictionary)kid, firstPartElems, lastCloned, document);
                        }
                        else
                        {
                            if (dictKid.IsFlushed())
                            {
                                throw new PdfException(PdfException.TagFromTheExistingTagStructureIsFlushedCannotAddCopiedPageTags);
                            }
                            // elems with no kids will not be marked as from the first part,
                            // but nonetheless we don't want to move all of them to the second part; we just leave them as is
                            if (dictKid.ContainsKey(PdfName.K))
                            {
                                CloneParents(structElem, lastCloned, document);
                                kids.Remove(i--);
                                PdfStructElem.AddKidObject(lastCloned.clone, -1, kid);
                            }
                        }
                    }
                    else
                    {
                        if (!firstPartElems.Contains(kid))
                        {
                            CloneParents(structElem, lastCloned, document);
                            PdfMcr mcr;
                            if (dictKid != null)
                            {
                                if (dictKid.Get(PdfName.Type).Equals(PdfName.MCR))
                                {
                                    mcr = new PdfMcrDictionary(dictKid, new PdfStructElem(lastCloned.clone));
                                }
                                else
                                {
                                    mcr = new PdfObjRef(dictKid, new PdfStructElem(lastCloned.clone));
                                }
                            }
                            else
                            {
                                mcr = new PdfMcrNumber((PdfNumber)kid, new PdfStructElem(lastCloned.clone));
                            }
                            kids.Remove(i--);
                            PdfStructElem.AddKidObject(lastCloned.clone, -1, kid);
                            // re-register mcr
                            document.GetStructTreeRoot().GetParentTreeHandler().RegisterMcr(mcr);
                        }
                    }
                }
            }
            if (lastCloned.ancestor == structElem)
            {
                lastCloned.ancestor = lastCloned.ancestor.GetAsDictionary(PdfName.P);
                lastCloned.clone    = lastCloned.clone.GetAsDictionary(PdfName.P);
            }
        }
Beispiel #13
0
        private static PdfDictionary CopyObject(PdfDictionary source, PdfDictionary destPage, bool parentChangePg,
                                                StructureTreeCopier.StructElemCopyingParams copyingParams)
        {
            PdfDictionary copied;

            if (copyingParams.IsCopyFromDestDocument())
            {
                //TODO: detect wether object is needed to be cloned at all
                copied = source.Clone(ignoreKeysForClone);
                if (source.IsIndirect())
                {
                    copied.MakeIndirect(copyingParams.GetToDocument());
                }
                PdfDictionary pg = source.GetAsDictionary(PdfName.Pg);
                if (pg != null)
                {
                    if (copyingParams.IsCopyFromDestDocument())
                    {
                        if (pg != destPage)
                        {
                            copied.Put(PdfName.Pg, destPage);
                            parentChangePg = true;
                        }
                        else
                        {
                            parentChangePg = false;
                        }
                    }
                }
            }
            else
            {
                copied = source.CopyTo(copyingParams.GetToDocument(), ignoreKeysForCopy, true);
                PdfDictionary obj = source.GetAsDictionary(PdfName.Obj);
                if (obj != null)
                {
                    // Link annotations could be not added to the toDocument, so we need to identify this case.
                    // When obj.copyTo is called, and annotation was already copied, we would get this already created copy.
                    // If it was already copied and added, /P key would be set. Otherwise /P won't be set.
                    obj = obj.CopyTo(copyingParams.GetToDocument(), JavaUtil.ArraysAsList(PdfName.P), false);
                    copied.Put(PdfName.Obj, obj);
                }
                PdfDictionary nsDict = source.GetAsDictionary(PdfName.NS);
                if (nsDict != null)
                {
                    PdfDictionary copiedNsDict = CopyNamespaceDict(nsDict, copyingParams);
                    copied.Put(PdfName.NS, copiedNsDict);
                }
                PdfDictionary pg = source.GetAsDictionary(PdfName.Pg);
                if (pg != null)
                {
                    PdfDictionary pageAnalog = copyingParams.GetPage2page().Get(pg);
                    if (pageAnalog == null)
                    {
                        pageAnalog     = destPage;
                        parentChangePg = true;
                    }
                    else
                    {
                        parentChangePg = false;
                    }
                    copied.Put(PdfName.Pg, pageAnalog);
                }
            }
            PdfObject k = source.Get(PdfName.K);

            if (k != null)
            {
                if (k.IsArray())
                {
                    PdfArray kArr   = (PdfArray)k;
                    PdfArray newArr = new PdfArray();
                    for (int i = 0; i < kArr.Size(); i++)
                    {
                        PdfObject copiedKid = CopyObjectKid(kArr.Get(i), copied, destPage, parentChangePg, copyingParams);
                        if (copiedKid != null)
                        {
                            newArr.Add(copiedKid);
                        }
                    }
                    if (!newArr.IsEmpty())
                    {
                        if (newArr.Size() == 1)
                        {
                            copied.Put(PdfName.K, newArr.Get(0));
                        }
                        else
                        {
                            copied.Put(PdfName.K, newArr);
                        }
                    }
                }
                else
                {
                    PdfObject copiedKid = CopyObjectKid(k, copied, destPage, parentChangePg, copyingParams);
                    if (copiedKid != null)
                    {
                        copied.Put(PdfName.K, copiedKid);
                    }
                }
            }
            return(copied);
        }
Beispiel #14
0
        /// <param name="in">Input byte array.</param>
        /// <param name="decodeParams">PdfDictionary of decodeParams.</param>
        /// <returns>a byte array</returns>
        public static byte[] DecodePredictor(byte[] @in, PdfObject decodeParams)
        {
            if (decodeParams == null || decodeParams.GetObjectType() != PdfObject.DICTIONARY)
            {
                return(@in);
            }
            PdfDictionary dic = (PdfDictionary)decodeParams;
            PdfObject     obj = dic.Get(PdfName.Predictor);

            if (obj == null || obj.GetObjectType() != PdfObject.NUMBER)
            {
                return(@in);
            }
            int predictor = ((PdfNumber)obj).IntValue();

            if (predictor < 10 && predictor != 2)
            {
                return(@in);
            }
            int          width         = GetNumberOrDefault(dic, PdfName.Columns, 1);
            int          colors        = GetNumberOrDefault(dic, PdfName.Colors, 1);
            int          bpc           = GetNumberOrDefault(dic, PdfName.BitsPerComponent, 8);
            BinaryReader dataStream    = new BinaryReader(new MemoryStream(@in));
            MemoryStream fout          = new MemoryStream(@in.Length);
            int          bytesPerPixel = colors * bpc / 8;
            int          bytesPerRow   = (colors * width * bpc + 7) / 8;

            byte[] curr  = new byte[bytesPerRow];
            byte[] prior = new byte[bytesPerRow];
            if (predictor == 2)
            {
                if (bpc == 8)
                {
                    int numRows = @in.Length / bytesPerRow;
                    for (int row = 0; row < numRows; row++)
                    {
                        int rowStart = row * bytesPerRow;
                        for (int col = bytesPerPixel; col < bytesPerRow; col++)
                        {
                            @in[rowStart + col] = (byte)(@in[rowStart + col] + @in[rowStart + col - bytesPerPixel]);
                        }
                    }
                }
                return(@in);
            }
            // Decode the (sub)image row-by-row
            while (true)
            {
                // Read the filter type byte and a row of data
                int filter;
                try {
                    filter = dataStream.Read();
                    if (filter < 0)
                    {
                        return(fout.ToArray());
                    }
                    dataStream.ReadFully(curr, 0, bytesPerRow);
                }
                catch (Exception) {
                    return(fout.ToArray());
                }
                switch (filter)
                {
                case 0: {
                    //PNG_FILTER_NONE
                    break;
                }

                case 1: {
                    //PNG_FILTER_SUB
                    for (int i = bytesPerPixel; i < bytesPerRow; i++)
                    {
                        curr[i] += curr[i - bytesPerPixel];
                    }
                    break;
                }

                case 2: {
                    //PNG_FILTER_UP
                    for (int i = 0; i < bytesPerRow; i++)
                    {
                        curr[i] += prior[i];
                    }
                    break;
                }

                case 3: {
                    //PNG_FILTER_AVERAGE
                    for (int i = 0; i < bytesPerPixel; i++)
                    {
                        curr[i] += (byte)(prior[i] / 2);
                    }
                    for (int i = bytesPerPixel; i < bytesPerRow; i++)
                    {
                        curr[i] += (byte)(((curr[i - bytesPerPixel] & 0xff) + (prior[i] & 0xff)) / 2);
                    }
                    break;
                }

                case 4: {
                    //PNG_FILTER_PAETH
                    for (int i = 0; i < bytesPerPixel; i++)
                    {
                        curr[i] += prior[i];
                    }
                    for (int i = bytesPerPixel; i < bytesPerRow; i++)
                    {
                        int a  = curr[i - bytesPerPixel] & 0xff;
                        int b  = prior[i] & 0xff;
                        int c  = prior[i - bytesPerPixel] & 0xff;
                        int p  = a + b - c;
                        int pa = Math.Abs(p - a);
                        int pb = Math.Abs(p - b);
                        int pc = Math.Abs(p - c);
                        int ret;
                        if (pa <= pb && pa <= pc)
                        {
                            ret = a;
                        }
                        else
                        {
                            if (pb <= pc)
                            {
                                ret = b;
                            }
                            else
                            {
                                ret = c;
                            }
                        }
                        curr[i] += (byte)ret;
                    }
                    break;
                }

                default: {
                    // Error -- unknown filter type
                    throw new PdfException(PdfException.PngFilterUnknown);
                }
                }
                try {
                    fout.Write(curr);
                }
                catch (System.IO.IOException) {
                    // Never happens
                    System.Diagnostics.Debug.Assert(true, "Happens!");
                }
                // Swap curr and prior
                byte[] tmp = prior;
                prior = curr;
                curr  = tmp;
            }
        }
Beispiel #15
0
        public static PdfViewerPreferencesImp GetViewerPreferences(PdfDictionary catalog)
        {
            PdfViewerPreferencesImp preferences = new PdfViewerPreferencesImp();
            int     prefs = 0;
            PdfName name  = null;
            // page layout
            PdfObject obj = PdfReader.GetPdfObjectRelease(catalog.Get(PdfName.PAGELAYOUT));

            if (obj != null && obj.IsName())
            {
                name = (PdfName)obj;
                if (name.Equals(PdfName.SINGLEPAGE))
                {
                    prefs |= PdfWriter.PageLayoutSinglePage;
                }
                else if (name.Equals(PdfName.ONECOLUMN))
                {
                    prefs |= PdfWriter.PageLayoutOneColumn;
                }
                else if (name.Equals(PdfName.TWOCOLUMNLEFT))
                {
                    prefs |= PdfWriter.PageLayoutTwoColumnLeft;
                }
                else if (name.Equals(PdfName.TWOCOLUMNRIGHT))
                {
                    prefs |= PdfWriter.PageLayoutTwoColumnRight;
                }
                else if (name.Equals(PdfName.TWOPAGELEFT))
                {
                    prefs |= PdfWriter.PageLayoutTwoPageLeft;
                }
                else if (name.Equals(PdfName.TWOPAGERIGHT))
                {
                    prefs |= PdfWriter.PageLayoutTwoPageRight;
                }
            }
            // page mode
            obj = PdfReader.GetPdfObjectRelease(catalog.Get(PdfName.PAGEMODE));
            if (obj != null && obj.IsName())
            {
                name = (PdfName)obj;
                if (name.Equals(PdfName.USENONE))
                {
                    prefs |= PdfWriter.PageModeUseNone;
                }
                else if (name.Equals(PdfName.USEOUTLINES))
                {
                    prefs |= PdfWriter.PageModeUseOutlines;
                }
                else if (name.Equals(PdfName.USETHUMBS))
                {
                    prefs |= PdfWriter.PageModeUseThumbs;
                }
                else if (name.Equals(PdfName.FULLSCREEN))
                {
                    prefs |= PdfWriter.PageModeFullScreen;
                }
                else if (name.Equals(PdfName.USEOC))
                {
                    prefs |= PdfWriter.PageModeUseOC;
                }
                else if (name.Equals(PdfName.USEATTACHMENTS))
                {
                    prefs |= PdfWriter.PageModeUseAttachments;
                }
            }
            // set page layout and page mode preferences
            preferences.ViewerPreferences = prefs;
            // other preferences
            obj = PdfReader.GetPdfObjectRelease(catalog
                                                .Get(PdfName.VIEWERPREFERENCES));
            if (obj != null && obj.IsDictionary())
            {
                PdfDictionary vp = (PdfDictionary)obj;
                for (int i = 0; i < VIEWER_PREFERENCES.Length; i++)
                {
                    obj = PdfReader.GetPdfObjectRelease(vp.Get(VIEWER_PREFERENCES[i]));
                    preferences.AddViewerPreference(VIEWER_PREFERENCES[i], obj);
                }
            }
            return(preferences);
        }
Beispiel #16
0
        /// <summary>
        /// Gets image from PDF and compresses it - Found on StackOverflow - asis
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="quality"></param>
        public static void ReduceResolution(PdfReader reader, long quality)
        {
            int n = reader.XrefSize;

            for (int i = 0; i < n; i++)
            {
                PdfObject obj = reader.GetPdfObject(i);
                if (obj == null || !obj.IsStream())
                {
                    continue;
                }

                PdfDictionary dict    = (PdfDictionary)PdfReader.GetPdfObject(obj);
                PdfName       subType = (PdfName)PdfReader.GetPdfObject(
                    dict.Get(PdfName.SUBTYPE)
                    );
                if (!PdfName.IMAGE.Equals(subType))
                {
                    continue;
                }

                PRStream stream = (PRStream)obj;
                try
                {
                    PdfImageObject image = new PdfImageObject(stream);
                    //PdfName filter = (PdfName)image.Get(PdfName.FILTER);
                    //if (
                    //  PdfName.JBIG2DECODE.Equals(filter)
                    //  || PdfName.JPXDECODE.Equals(filter)
                    //  || PdfName.CCITTFAXDECODE.Equals(filter)
                    //  || PdfName.FLATEDECODE.Equals(filter)
                    //) continue;

                    System.Drawing.Image img = image.GetDrawingImage();
                    if (img == null)
                    {
                        continue;
                    }

                    var ll     = image.GetImageBytesType();
                    int width  = img.Width;
                    int height = img.Height;
                    using (System.Drawing.Bitmap dotnetImg =
                               new System.Drawing.Bitmap(img))
                    {
                        // set codec to jpeg type => jpeg index codec is "1"
                        System.Drawing.Imaging.ImageCodecInfo codec =
                            System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
                        // set parameters for image quality
                        System.Drawing.Imaging.EncoderParameters eParams =
                            new System.Drawing.Imaging.EncoderParameters(1);
                        eParams.Param[0] =
                            new System.Drawing.Imaging.EncoderParameter(
                                System.Drawing.Imaging.Encoder.Quality, quality
                                );
                        using (MemoryStream msImg = new MemoryStream())
                        {
                            dotnetImg.Save(msImg, codec, eParams);
                            msImg.Position = 0;
                            stream.SetData(msImg.ToArray());
                            stream.SetData(
                                msImg.ToArray(), false, PRStream.BEST_COMPRESSION
                                );
                            stream.Put(PdfName.TYPE, PdfName.XOBJECT);
                            stream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
                            stream.Put(PdfName.FILTER, image.Get(PdfName.FILTER));
                            stream.Put(PdfName.FILTER, PdfName.DCTDECODE);
                            stream.Put(PdfName.WIDTH, new PdfNumber(width));
                            stream.Put(PdfName.HEIGHT, new PdfNumber(height));
                            stream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
                            stream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
                        }
                    }
                }
                catch
                {
                    // throw;
                    // iText[Sharp] can't handle all image types...
                }
                finally
                {
                    // may or may not help
                    reader.RemoveUnusedObjects();
                }
            }
        }
Beispiel #17
0
 protected internal PdfSimpleFont(PdfDictionary fontDictionary)
     : base(fontDictionary)
 {
     toUnicode = FontUtil.ProcessToUnicode(fontDictionary.Get(PdfName.ToUnicode));
 }
Beispiel #18
0
        virtual public void PdfMergeTest()
        {
            PdfDictionary CM31  = new PdfDictionary();
            PdfDictionary sElem = new PdfDictionary();

            //<</O/Layout/EndIndent 18.375/StartIndent 11.25/TextIndent -11.25/LineHeight 13>>
            //<</C/SC.7.147466/Pg 118 0 R/Type/StructElem/K 3/S/Span/Lang(en)/P 1 0 R>>
            CM31.Put(PdfName.O, new PdfName("Layout"));
            CM31.Put(new PdfName("EndIndent"), new PdfNumber(18.375));
            CM31.Put(new PdfName("StartIndent"), new PdfNumber(11.25));
            CM31.Put(new PdfName("TextIndent"), new PdfNumber(-11.25));
            CM31.Put(new PdfName("LineHeight"), new PdfNumber(13));
            sElem.Put(PdfName.C, new PdfName("SC.7.147466"));
            sElem.Put(PdfName.K, new PdfNumber(5));
            sElem.Put(PdfName.S, PdfName.SPAN);
            sElem.Put(PdfName.LANG, new PdfString("en"));


            InitializeDocument("-merge");

            int       n       = 14;
            PdfReader reader1 = new PdfReader(SOURCE11);

            copy.AddPage(copy.GetImportedPage(reader1, 76, true));
            copy.AddPage(copy.GetImportedPage(reader1, 83, true));
            PdfReader reader2 = new PdfReader(SOURCE32);

            copy.AddPage(copy.GetImportedPage(reader2, 69, true));
            copy.AddPage(copy.GetImportedPage(reader2, 267, true));
            document.Close();
            reader1.Close();
            reader2.Close();
            PdfReader     reader         = new PdfReader(output);
            PdfDictionary structTreeRoot =
                VerifyIsDictionary(reader.Catalog.GetDirectObject(PdfName.STRUCTTREEROOT), NO_STRUCT_TREE_ROOT);

            VerifyArraySize(structTreeRoot.Get(PdfName.K), 2, "Kids in StructTreeRoot");
            PdfObject obj = PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.PARENTTREE));

            VerifyIsDictionary(obj, NO_PARENT_TREE);

            PdfArray array = ((PdfDictionary)obj).GetAsArray(PdfName.NUMS);

            int[] nums = new int[] { 44, 0, 65, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 81 };
            for (int i = 0; i < n; ++i)
            {
                VerifyArraySize(PdfStructTreeController.GetDirectObject(array.GetDirectObject(i * 2 + 1)), nums[i],
                                "Nums of page " + (i + 1), true);
            }

            PdfDictionary ClassMap =
                VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.CLASSMAP)),
                                   NO_CLASS_MAP);
            PdfDictionary currCM31 =
                VerifyIsDictionary(PdfStructTreeController.GetDirectObject(ClassMap.Get(new PdfName("CM31"))),
                                   "ClassMap does not contain.\"CM31\"");

            if (!PdfStructTreeController.CompareObjects(CM31, currCM31))
            {
                Assert.Fail("ClassMap contains incorrect \"CM31\"");
            }

            PdfDictionary RoleMap =
                VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.ROLEMAP)),
                                   NO_ROLE_MAP);

            if (!PdfName.SPAN.Equals(RoleMap.Get(new PdfName("ParagraphSpan"))))
            {
                throw new BadPdfFormatException("RoleMap does not contain \"ParagraphSpan\"");
            }

            reader.Close();
        }
Beispiel #19
0
        public static void ApplyProperties(string inputPdfPath, string outputPdfPath)
        {
            try
            {
                string author = string.Empty;
                using (PdfReader reader = new PdfReader(inputPdfPath))
                {
                    PdfStamper            stamp = new PdfStamper(reader, new FileStream(outputPdfPath, FileMode.Create), reader.PdfVersion);
                    List <AnnotationMark> marks = new List <AnnotationMark>();
                    for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
                    {
                        PdfDictionary pageDict   = reader.GetPageN(pageIndex);
                        PdfArray      annotArray = pageDict.GetAsArray(PdfName.ANNOTS);
                        //PdfArray removeannotarray
                        PdfGState gstate = new PdfGState();
                        gstate.FillOpacity   = 0.1f;
                        gstate.StrokeOpacity = (0.1f);
                        var pcb = stamp.GetOverContent(pageIndex);
                        pcb.SetGState(gstate);

                        if (annotArray != null)
                        {
                            List <int>    ind    = new List <int>();
                            List <string> strind = new List <string>();
                            List <int>    rind   = new List <int>();
                            for (int i = 0; i < annotArray.Count(); ++i)
                            {
                                PdfDictionary annotation = annotArray.GetAsDict(i);

                                if (annotation != null)
                                {
                                    PdfArray r       = annotation.GetAsArray(PdfName.RECT);
                                    var      subType = annotation.Get(subTypeName);
                                    if (subType != null && !String.IsNullOrEmpty(subType.ToString()) && subType.ToString() == "/FreeText")
                                    {
                                        var content = annotation.GetAsString(PdfName.CONTENTS);
                                        if (content != null && (content.ToString().ToUpper().Contains("RXN") || Regex.IsMatch(content.ToString(), S8000_MARKUP_REG_EXP)))
                                        {
                                            string status = content.ToString();

                                            PdfArray rect    = annotation.GetAsArray(PdfName.RECT);
                                            var      newRect = new iTextSharp.text.Rectangle(rect.GetAsNumber(0).FloatValue, rect.GetAsNumber(1).FloatValue, rect.GetAsNumber(2).FloatValue + 15, rect.GetAsNumber(3).FloatValue);
                                            pcb.SetFontAndSize(FontFactory.GetFont(FontFactory.COURIER).BaseFont, 12);
                                            var newAnnotation = PdfAnnotation.CreateFreeText(stamp.Writer, newRect, status.ToString(), pcb);
                                            if (newAnnotation != null)
                                            {
                                                newAnnotation.Put(PdfName.T, new PdfString(String.Empty));
                                                newAnnotation.Put(new PdfName("IT"), new PdfString("FreeTextTypeWriter"));
                                                newAnnotation.Put(new PdfName("DS"), new PdfString("font: Courier 12pt; text-align:left; margin:0pt; line-height:13.8pt; color:#FF0000"));
                                                newAnnotation.Border = new PdfBorderArray(0, 0, 0);
                                                newAnnotation.Put(new PdfName("DA"), new PdfString("0 0 0 rg /Cour 12 Tf"));
                                                newAnnotation.Put(new PdfName("Subj"), new PdfString("Typewritten Text"));
                                                newAnnotation.Put(new PdfName("RC"), new PdfString($"<?xml version=\"1.0\"?><body xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:contentType=\"text/html\" xfa:APIVersion=\"BluebeamPDFRevu:12.1.0\" xfa:spec=\"2.2.0\" style=\"font:Courier 12pt; text-align:left; margin:0pt; line-height:13.8pt; color:#FF0000\" xmlns=\"http://www.w3.org/1999/xhtml\">{status.ToString()}</body>"));
                                                marks.Add(new AnnotationMark {
                                                    Annotation = newAnnotation, PageIndex = pageIndex
                                                });
                                                rind.Add(i);
                                            }
                                        }
                                    }
                                }
                            }
                            for (int i = rind.Count(); i > 0; i--)
                            {
                                annotArray.Remove(rind[i - 1]);
                            }
                        }
                    }
                    foreach (var annotationMark in marks)
                    {
                        stamp.AddAnnotation(annotationMark.Annotation, annotationMark.PageIndex);
                    }
                    stamp.Close();
                }
            }
            catch (Exception ex)
            {
                //Log.This(ex);
            }
        }
 private void InitKeyAndReadDictionary(PdfDictionary encryptionDictionary, byte[] password)
 {
     try {
         if (password == null)
         {
             password = new byte[0];
         }
         else
         {
             if (password.Length > 127)
             {
                 password = JavaUtil.ArraysCopyOf(password, 127);
             }
         }
         isPdf2 = encryptionDictionary.GetAsNumber(PdfName.R).GetValue() == 6;
         byte[]    oValue  = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.O));
         byte[]    uValue  = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.U));
         byte[]    oeValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.OE));
         byte[]    ueValue = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.UE));
         byte[]    perms   = GetIsoBytes(encryptionDictionary.GetAsString(PdfName.Perms));
         PdfNumber pValue  = (PdfNumber)encryptionDictionary.Get(PdfName.P);
         this.permissions = pValue.LongValue();
         byte[] hash;
         hash = ComputeHash(password, oValue, VALIDATION_SALT_OFFSET, SALT_LENGTH, uValue);
         usedOwnerPassword = CompareArray(hash, oValue, 32);
         if (usedOwnerPassword)
         {
             hash = ComputeHash(password, oValue, KEY_SALT_OFFSET, SALT_LENGTH, uValue);
             AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash);
             nextObjectKey = ac.ProcessBlock(oeValue, 0, oeValue.Length);
         }
         else
         {
             hash = ComputeHash(password, uValue, VALIDATION_SALT_OFFSET, SALT_LENGTH);
             if (!CompareArray(hash, uValue, 32))
             {
                 throw new BadPasswordException(PdfException.BadUserPassword);
             }
             hash = ComputeHash(password, uValue, KEY_SALT_OFFSET, SALT_LENGTH);
             AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash);
             nextObjectKey = ac.ProcessBlock(ueValue, 0, ueValue.Length);
         }
         nextObjectKeySize = 32;
         AESCipherCBCnoPad ac_1     = new AESCipherCBCnoPad(false, nextObjectKey);
         byte[]            decPerms = ac_1.ProcessBlock(perms, 0, perms.Length);
         if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b')
         {
             throw new BadPasswordException(PdfException.BadUserPassword);
         }
         int permissionsDecoded = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16)
                                  | ((decPerms[3] & 0xff) << 24);
         bool encryptMetadata      = decPerms[8] == (byte)'T';
         bool?encryptMetadataEntry = encryptionDictionary.GetAsBool(PdfName.EncryptMetadata);
         if (permissionsDecoded != permissions || encryptMetadataEntry != null && encryptMetadata != encryptMetadataEntry
             )
         {
             ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Crypto.Securityhandler.StandardHandlerUsingAes256));
             logger.Error(iText.IO.LogMessageConstant.ENCRYPTION_ENTRIES_P_AND_ENCRYPT_METADATA_NOT_CORRESPOND_PERMS_ENTRY
                          );
         }
         this.permissions     = permissionsDecoded;
         this.encryptMetadata = encryptMetadata;
     }
     catch (BadPasswordException ex) {
         throw;
     }
     catch (Exception ex) {
         throw new PdfException(PdfException.PdfEncryption, ex);
     }
 }
Beispiel #21
0
 /**
  * @param os
  * @param info
  * @throws IOException
  */
 public XmpWriter(Stream os, PdfDictionary info) : this(os) {
     if (info != null)
     {
         DublinCoreSchema dc    = new DublinCoreSchema();
         PdfSchema        p     = new PdfSchema();
         XmpBasicSchema   basic = new XmpBasicSchema();
         PdfObject        obj;
         foreach (PdfName key in info.Keys)
         {
             obj = info.Get(key);
             if (obj == null)
             {
                 continue;
             }
             if (PdfName.TITLE.Equals(key))
             {
                 dc.AddTitle(((PdfString)obj).ToUnicodeString());
             }
             if (PdfName.AUTHOR.Equals(key))
             {
                 dc.AddAuthor(((PdfString)obj).ToUnicodeString());
             }
             if (PdfName.SUBJECT.Equals(key))
             {
                 dc.AddSubject(((PdfString)obj).ToUnicodeString());
             }
             if (PdfName.KEYWORDS.Equals(key))
             {
                 p.AddKeywords(((PdfString)obj).ToUnicodeString());
             }
             if (PdfName.CREATOR.Equals(key))
             {
                 basic.AddCreatorTool(((PdfString)obj).ToUnicodeString());
             }
             if (PdfName.PRODUCER.Equals(key))
             {
                 p.AddProducer(((PdfString)obj).ToUnicodeString());
             }
             if (PdfName.CREATIONDATE.Equals(key))
             {
                 basic.AddCreateDate(((PdfDate)obj).GetW3CDate());
             }
             if (PdfName.MODDATE.Equals(key))
             {
                 basic.AddModDate(((PdfDate)obj).GetW3CDate());
             }
         }
         if (dc.Count > 0)
         {
             AddRdfDescription(dc);
         }
         if (p.Count > 0)
         {
             AddRdfDescription(p);
         }
         if (basic.Count > 0)
         {
             AddRdfDescription(basic);
         }
     }
 }
Beispiel #22
0
 /// <summary>This is the last method to be called when using external signatures.</summary>
 /// <remarks>
 /// This is the last method to be called when using external signatures. The general sequence is:
 /// preClose(), getDocumentBytes() and close().
 /// <p>
 /// update is a PdfDictionary that must have exactly the
 /// same keys as the ones provided in
 /// <see cref="PreClose(System.Collections.Generic.IDictionary{K, V})"/>
 /// .
 /// </remarks>
 /// <param name="update">
 /// a PdfDictionary with the key/value that will fill the holes defined
 /// in
 /// <see cref="PreClose(System.Collections.Generic.IDictionary{K, V})"/>
 /// </param>
 /// <exception cref="System.IO.IOException">on error</exception>
 protected internal virtual void Close(PdfDictionary update)
 {
     try {
         if (!preClosed)
         {
             throw new PdfException(PdfException.DocumentMustBePreClosed);
         }
         MemoryStream    bous = new MemoryStream();
         PdfOutputStream os   = new PdfOutputStream(bous);
         foreach (PdfName key in update.KeySet())
         {
             PdfObject  obj = update.Get(key);
             PdfLiteral lit = exclusionLocations.Get(key);
             if (lit == null)
             {
                 throw new ArgumentException("The key didn't reserve space in preclose");
             }
             bous.JReset();
             os.Write(obj);
             if (bous.Length > lit.GetBytesCount())
             {
                 throw new ArgumentException("The key is too big");
             }
             if (tempFile == null)
             {
                 System.Array.Copy(bous.ToArray(), 0, bout, (int)lit.GetPosition(), bous.Length);
             }
             else
             {
                 raf.Seek(lit.GetPosition());
                 raf.Write(bous.ToArray(), 0, (int)bous.Length);
             }
         }
         if (update.Size() != exclusionLocations.Count)
         {
             throw new ArgumentException("The update dictionary has less keys than required");
         }
         if (tempFile == null)
         {
             originalOS.Write(bout, 0, bout.Length);
         }
         else
         {
             if (originalOS != null)
             {
                 raf.Seek(0);
                 long   length = raf.Length;
                 byte[] buf    = new byte[8192];
                 while (length > 0)
                 {
                     int r = raf.JRead(buf, 0, (int)Math.Min((long)buf.Length, length));
                     if (r < 0)
                     {
                         throw new EndOfStreamException("unexpected eof");
                     }
                     originalOS.Write(buf, 0, r);
                     length -= r;
                 }
             }
         }
     }
     finally {
         if (tempFile != null)
         {
             raf.Close();
             if (originalOS != null)
             {
                 tempFile.Delete();
             }
         }
         if (originalOS != null)
         {
             try {
                 originalOS.Close();
             }
             catch (Exception) {
             }
         }
     }
 }
Beispiel #23
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.is.out.of.bounds"));
                }
            }
            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"));
                        }
                    }

                    PdfArray outputIntents          = GetDirectArray(dictionary.Get(PdfName.OUTPUTINTENTS));
                    bool     pdfa1OutputIntentFound = false;
                    if (outputIntents != null && outputIntents.Size > 0)
                    {
                        for (int i = 0; i < outputIntents.Size; i++)
                        {
                            PdfDictionary outputIntentDictionary = GetDirectDictionary(outputIntents[i]);
                            PdfName       gts = outputIntentDictionary.GetAsName(PdfName.S);
                            if (PdfName.GTS_PDFA1.Equals(gts))
                            {
                                if (pdfa1OutputIntentFound)
                                {
                                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("a.pdfa.file.may.have.only.one.pdfa.outputintent"));
                                }
                                pdfa1OutputIntentFound = true;
                            }
                            if (outputIntentDictionary != null)
                            {
                                PdfObject destOutputIntent = outputIntentDictionary.Get(PdfName.DESTOUTPUTPROFILE);
                                if (destOutputIntent == null && PdfName.GTS_PDFA1.Equals(gts))
                                {
                                    throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                                }
                            }
                        }
                    }

                    if ((rgbUsed || cmykUsed || grayUsed) && !pdfa1OutputIntentFound)
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("if.device.rgb.cmyk.gray.used.in.file.that.file.shall.contain.pdfa.outputintent"));
                    }
                }
                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 iccProfileStream = dictionary.Get(PdfName.DESTOUTPUTPROFILE);
                    String    inputColorSpace  = "";
                    if (iccProfileStream != null)
                    {
                        ICC_Profile icc_profile = writer.ColorProfile;
                        inputColorSpace = Encoding.GetEncoding("US-ASCII").GetString(icc_profile.Data, 16, 4);
                    }
                    PdfName gts = dictionary.GetAsName(PdfName.S);
                    if (!PdfName.GTS_PDFA1.Equals(gts))
                    {
                        throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("outputintent.shall.have.gtspdfa1.and.destoutputintent"));
                    }
                    if ("RGB ".Equals(inputColorSpace))
                    {
                        if (cmykUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicecmyk.may.be.used.only.if.the.file.has.a.cmyk.pdfa.outputIntent"));
                        }
                    }
                    else if ("CMYK".Equals(inputColorSpace))
                    {
                        if (rgbUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicergb.may.be.used.only.if.the.file.has.a.rgb.pdfa.outputIntent"));
                        }
                    }
                    else
                    {
                        if (cmykUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicecmyk.may.be.used.only.if.the.file.has.a.cmyk.pdfa.outputIntent"));
                        }
                        if (rgbUsed)
                        {
                            throw new PdfAConformanceException(obj1, MessageLocalization.GetComposedMessage("devicergb.may.be.used.only.if.the.file.has.a.rgb.pdfa.outputIntent"));
                        }
                    }
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Bitmap default_image = new Bitmap(pictureBox1.Image);
            Bitmap getIcono      = new Bitmap("./noteIcon.png");

            Image <Bgr, Byte> fondo  = new Image <Bgr, Byte>(default_image);
            Image <Bgr, Byte> fondo2 = new Image <Bgr, Byte>(default_image);
            Image <Bgr, Byte> icono  = new Image <Bgr, Byte>(getIcono).Resize(0.8, Inter.Area);
            //MessageBox.Show("tamano icono " + icono.Width + " y " + icono.Height);
            string        oldFile  = "ejemploOK1.pdf";
            string        newFile  = "temporal.pdf";
            PdfReader     reader   = new PdfReader(oldFile);
            PdfDictionary pageDict = reader.GetPageN(1);



            iTextSharp.text.Rectangle pagesize = reader.GetPageSize(1);
            double anchoPDF = pagesize.Width;
            double altoPDF  = pagesize.Height;
            // MessageBox.Show("Tamano pagina pdf --> ancho :" + anchoPDF + " y alto : " + altoPDF);
            float anchoImagen = fondo.Width;
            float altoImagen  = fondo.Height;
            //MessageBox.Show("Tamano imagen --> ancho :" + anchoImagen+ " y alto : " + altoImagen);

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

            for (int i = 0; i < annotArray.Size; ++i)
            {
                PdfDictionary curAnnot = annotArray.GetAsDict(i);
                var           subtype  = curAnnot.Get(PdfName.SUBTYPE);
                var           rect     = curAnnot.Get(PdfName.RECT);
                var           contents = curAnnot.Get(PdfName.CONTENTS);
                var           page     = curAnnot.Get(PdfName.P);
                //MessageBox.Show("Subtipo "+subtype + " coordenadas: "+rect + " y contenido "+contents);
                if (subtype.ToString() == "/Square")
                {
                    //MessageBox.Show("Figura rectangular detectada coor "+rect);
                    var aux_rect = rect.ToString().Split(',');
                    aux_rect[0] = aux_rect[0].Remove(0, 1);
                    aux_rect[3] = aux_rect[3].Remove(aux_rect[3].Length - 1);
                    aux_rect[0] = aux_rect[0].Replace(".", ",");
                    aux_rect[1] = aux_rect[1].Replace(".", ",");
                    aux_rect[2] = aux_rect[2].Replace(".", ",");
                    aux_rect[3] = aux_rect[3].Replace(".", ",");
                    //MessageBox.Show("el split primero " + aux_rect[0]+ " el split ultimo "+ aux_rect[3]);
                    // MessageBox.Show("Esto es rect " + aux_rect[0] + " " + aux_rect[1] + " " + aux_rect[2] + " " + aux_rect[3]);
                    int puntox1 = Convert.ToInt32(Convert.ToSingle(aux_rect[0]));
                    int puntoy1 = Convert.ToInt32(Convert.ToSingle(aux_rect[1]));
                    int puntox2 = Convert.ToInt32(Convert.ToSingle(aux_rect[2]));
                    int puntoy2 = Convert.ToInt32(Convert.ToSingle(aux_rect[3]));
                    // MessageBox.Show("puntos "+ puntox1+" ,"+ puntoy1+ " , "+ puntox2+" , "+ puntoy2);

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

                    Rectangle rectangulo = new Rectangle(puntox1, puntoy1, puntox1 + puntox2, puntoy1 + puntoy2);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    fondo.Draw(rectangulo, new Bgr(Color.Cyan), 1);
                    Rectangle rectangulo2 = new Rectangle(nuevoX1, nuevoY1, nuevoX2 - nuevoX1, nuevoY2 - nuevoY1);
                    //Rectangle rectangulo = new Rectangle(0, 0, 100, 200);
                    fondo.Draw(rectangulo2, new Bgr(Color.Red), 1);
                    pictureBox1.Image = fondo.Bitmap;
                    // CvInvoke.cvResetImageROI(fondo);
                }
                if (subtype.ToString() == "/Text")
                {
                    //MessageBox.Show("Comentarios Post it detectado coor "+rect);
                    listBox2.Items.Add(contents + " " + page);
                    var aux_rect = rect.ToString().Split(',');
                    aux_rect[0] = aux_rect[0].Remove(0, 1);
                    aux_rect[0] = aux_rect[0].Replace(".", ",");
                    aux_rect[1] = aux_rect[1].Replace(".", ",");
                    int puntox1 = Convert.ToInt32(Convert.ToSingle(aux_rect[0]));
                    int puntoy1 = Convert.ToInt32(Convert.ToSingle(aux_rect[1]));
                    int nuevoX1 = (Convert.ToInt32(anchoImagen) * (puntox1 * 100 / Convert.ToInt32(anchoPDF))) / 100;
                    int nuevoY1 = Convert.ToInt32(altoImagen) - ((Convert.ToInt32(altoImagen) * (puntoy1 * 100 / Convert.ToInt32(altoPDF))) / 100);
                    //MessageBox.Show("Esto es punto x1 "+nuevoX1+ " y y1 "+nuevoY1);
                    //ROi debe ser del mismo tamaño que la imagen a pegar
                    Rectangle brect = new Rectangle(0, nuevoY1, icono.Width, icono.Height);
                    fondo.ROI = brect;
                    //final = auxImge.Copy();
                    CvInvoke.cvCopy(icono, fondo, IntPtr.Zero);
                    //pictureBox2.Image = fondo.Bitmap;


                    CvInvoke.cvResetImageROI(fondo);
                }

                //foreach (var algo in curAnnot.Keys)
                //{

                ////MessageBox.Show("Comentarios " + algo);
                // listBox2.Items.Add(algo);
                //}
                //int someType = MyCodeToGetAnAnnotsType(curAnnot);
                //if (someType == THIS_TYPE)
                //{

                //}
                //else if (someType == THAT_TYPE)
                //{
                //writeThatType(curAnnot);
                //}
            }
        }
Beispiel #25
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);
             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 #26
0
        private void PopulateSignatureNames()
        {
            if (acroForm == null)
            {
                return;
            }
            IList <Object[]> sorter = new List <Object[]>();

            foreach (KeyValuePair <String, PdfFormField> entry in acroForm.GetFormFields())
            {
                PdfFormField  field  = entry.Value;
                PdfDictionary merged = field.GetPdfObject();
                if (!PdfName.Sig.Equals(merged.Get(PdfName.FT)))
                {
                    continue;
                }
                PdfDictionary v = merged.GetAsDictionary(PdfName.V);
                if (v == null)
                {
                    continue;
                }
                PdfString contents = v.GetAsString(PdfName.Contents);
                if (contents == null)
                {
                    continue;
                }
                else
                {
                    contents.MarkAsUnencryptedObject();
                }
                PdfArray ro = v.GetAsArray(PdfName.ByteRange);
                if (ro == null)
                {
                    continue;
                }
                int rangeSize = ro.Size();
                if (rangeSize < 2)
                {
                    continue;
                }
                int length = ro.GetAsNumber(rangeSize - 1).IntValue() + ro.GetAsNumber(rangeSize - 2).IntValue();
                sorter.Add(new Object[] { entry.Key, new int[] { length, 0 } });
            }
            JavaCollectionsUtil.Sort(sorter, new SignatureUtil.SorterComparator());
            if (sorter.Count > 0)
            {
                try {
                    if (((int[])sorter[sorter.Count - 1][1])[0] == document.GetReader().GetFileLength())
                    {
                        totalRevisions = sorter.Count;
                    }
                    else
                    {
                        totalRevisions = sorter.Count + 1;
                    }
                }
                catch (System.IO.IOException) {
                }
                // TODO: add exception handling (at least some logger)
                for (int k = 0; k < sorter.Count; ++k)
                {
                    Object[] objs = sorter[k];
                    String   name = (String)objs[0];
                    int[]    p    = (int[])objs[1];
                    p[1] = k + 1;
                    sigNames.Put(name, p);
                    orderedSignatureNames.Add(name);
                }
            }
        }
Beispiel #27
0
 /**
  * Returns an entry from the image dictionary.
  * @param key a key
  * @return the value
  */
 public iTextSharp.text.pdf.PdfObject Get(PdfName key)
 {
     return(dictionary.Get(key));
 }
Beispiel #28
0
        protected internal virtual void CheckResources(PdfDictionary resources)
        {
            if (resources == null)
            {
                return;
            }
            PdfDictionary xObjects = resources.GetAsDictionary(PdfName.XObject);
            PdfDictionary shadings = resources.GetAsDictionary(PdfName.Shading);
            PdfDictionary patterns = resources.GetAsDictionary(PdfName.Pattern);

            if (xObjects != null)
            {
                foreach (PdfObject xObject in xObjects.Values())
                {
                    PdfStream xObjStream = (PdfStream)xObject;
                    PdfObject subtype    = null;
                    bool      isFlushed  = xObjStream.IsFlushed();
                    if (!isFlushed)
                    {
                        subtype = xObjStream.Get(PdfName.Subtype);
                    }
                    if (PdfName.Image.Equals(subtype) || isFlushed)
                    {
                        // if flushed still may be need to check colorspace in given context
                        CheckImage(xObjStream, resources.GetAsDictionary(PdfName.ColorSpace));
                    }
                    else
                    {
                        if (PdfName.Form.Equals(subtype))
                        {
                            CheckFormXObject(xObjStream);
                        }
                    }
                }
            }
            if (shadings != null)
            {
                foreach (PdfObject shading in shadings.Values())
                {
                    PdfDictionary shadingDict = (PdfDictionary)shading;
                    if (!IsAlreadyChecked(shadingDict))
                    {
                        CheckColorSpace(PdfColorSpace.MakeColorSpace(shadingDict.Get(PdfName.ColorSpace)), resources.GetAsDictionary
                                            (PdfName.ColorSpace), true, null);
                    }
                }
            }
            if (patterns != null)
            {
                foreach (PdfObject p in patterns.Values())
                {
                    if (p.IsStream())
                    {
                        PdfStream pStream = (PdfStream)p;
                        if (!IsAlreadyChecked(pStream))
                        {
                            CheckResources(pStream.GetAsDictionary(PdfName.Resources));
                        }
                    }
                }
            }
        }
Beispiel #29
0
 /**
  * Returns an entry from the image dictionary.
  * @param key a key
  * @return the value
  */
 public PdfObject Get(PdfName key)
 {
     return(dictionary.Get(key));
 }
Beispiel #30
0
        /**
         * Business logic that checks if a certain object is in conformance with PDF/X.
         * @param writer    the writer that is supposed to write the PDF/X file
         * @param key       the type of PDF ISO conformance that has to be checked
         * @param obj1      the object that is checked for conformance
         */
        public void CheckPdfIsoConformance(int key, Object obj1)
        {
            if (writer == null || !writer.IsPdfX())
            {
                return;
            }
            int conf = writer.PDFXConformance;

            switch (key)
            {
            case PdfIsoKeys.PDFISOKEY_COLOR:
                switch (conf)
                {
                case PdfWriter.PDFX1A2001:
                    if (obj1 is ExtendedColor)
                    {
                        ExtendedColor ec = (ExtendedColor)obj1;
                        switch (ec.Type)
                        {
                        case ExtendedColor.TYPE_CMYK:
                        case ExtendedColor.TYPE_GRAY:
                            return;

                        case ExtendedColor.TYPE_RGB:
                            throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed"));

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

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

                        case ExtendedColor.TYPE_PATTERN:
                            PatternColor pc = (PatternColor)ec;
                            CheckPdfIsoConformance(PdfIsoKeys.PDFISOKEY_COLOR, pc.Painter.DefaultColor);
                            break;
                        }
                    }
                    else if (obj1 is BaseColor)
                    {
                        throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed"));
                    }
                    break;
                }
                break;

            case PdfIsoKeys.PDFISOKEY_CMYK:
                break;

            case PdfIsoKeys.PDFISOKEY_RGB:
                if (conf == PdfWriter.PDFX1A2001)
                {
                    throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed"));
                }
                break;

            case PdfIsoKeys.PDFISOKEY_FONT:
                if (!((BaseFont)obj1).IsEmbedded())
                {
                    throw new PdfXConformanceException(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 PdfXConformanceException(MessageLocalization.GetComposedMessage("the.smask.key.is.not.allowed.in.images"));
                }
                switch (conf)
                {
                case PdfWriter.PDFX1A2001:
                    PdfObject cs = image.Get(PdfName.COLORSPACE);
                    if (cs == null)
                    {
                        return;
                    }
                    if (cs.IsName())
                    {
                        if (PdfName.DEVICERGB.Equals(cs))
                        {
                            throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.rgb.is.not.allowed"));
                        }
                    }
                    else if (cs.IsArray())
                    {
                        if (PdfName.CALRGB.Equals(((PdfArray)cs)[0]))
                        {
                            throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("colorspace.calrgb.is.not.allowed"));
                        }
                    }
                    break;
                }
                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 PdfXConformanceException(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 PdfXConformanceException(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 PdfXConformanceException(MessageLocalization.GetComposedMessage("transparency.is.not.allowed.ca.eq.1", v));
                }
                break;

            case PdfIsoKeys.PDFISOKEY_LAYER:
                throw new PdfXConformanceException(MessageLocalization.GetComposedMessage("layers.are.not.allowed"));
            }
        }
Beispiel #31
0
        public void CopyTaggedPdf23()
        {
            PdfReader     reader         = new PdfReader(SOURCE81);
            PdfDictionary structTreeRoot = VerifyIsDictionary(reader.Catalog.GetDirectObject(PdfName.STRUCTTREEROOT), NO_STRUCT_TREE_ROOT);
            PdfDictionary idTree         = VerifyIsDictionary(PdfStructTreeController.GetDirectObject(structTreeRoot.Get(PdfName.IDTREE)), NO_ID_TREE);

            Assert.IsTrue(idTree.hashMap.Count > 0, EMPTY_ID_TREE);
        }
        private PdfObject CleverPdfDictionaryClone(PdfDictionary dict) {
            PdfDictionary newDict;
            if (dict.IsStream()) {
                newDict = new PdfStream(emptyByteArray);
                newDict.Remove(PdfName.LENGTH);
            }
            else
                newDict = new PdfDictionary();

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

            return newDict;
        }
        /**
         * If the child of a structured element is a dictionary, we inspect the
         * child; we may also draw a tag.
         * 
         * @param k
         *            the child dictionary to inspect
         */
        virtual public void InspectChildDictionary(PdfDictionary k, bool inspectAttributes) {
            if (k == null)
                return;
            PdfName s = k.GetAsName(PdfName.S);
            if (s != null) {
                String tagN = PdfName.DecodeName(s.ToString());
			    String tag = FixTagName(tagN);
                outp.Write("<");
                outp.Write(tag);
                if (inspectAttributes) {
                    PdfDictionary a = k.GetAsDict(PdfName.A);
                    if (a != null) {
                        Dictionary<PdfName, PdfObject>.KeyCollection keys = a.Keys;
                        foreach (PdfName key in keys) {
                            outp.Write(' ');
                            PdfObject value = a.Get(key);
                            value = PdfReader.GetPdfObject(value);
                            outp.Write(XmlName(key));
                            outp.Write("=\"");
                            outp.Write(value.ToString());
                            outp.Write("\"");
                        }
                    }
                }
                outp.Write(">");
                PdfObject alt = k.Get(PdfName.ALT);
                if (alt != null && alt.ToString() != null) {
                    outp.Write("<alt><![CDATA[");
                    outp.Write(Regex.Replace(alt.ToString(), "[\\000]*", ""));
                    outp.Write("]]></alt>");
                }
                PdfDictionary dict = k.GetAsDict(PdfName.PG);
                if (dict != null)
                    ParseTag(tagN, k.GetDirectObject(PdfName.K), dict);
                InspectChild(k.GetDirectObject(PdfName.K));
                outp.Write("</");
                outp.Write(tag);
                outp.WriteLine(">");
            } else
                InspectChild(k.GetDirectObject(PdfName.K));
        }