Exemple #1
0
        /// <summary>
        /// Remove the redaction annotations
        /// This method is called after the annotations are processed.
        /// </summary>
        private void RemoveRedactAnnots()
        {
            foreach (PdfRedactAnnotation annotation in redactAnnotations.Keys)
            {
                PdfPage page = annotation.GetPage();
                if (page != null)
                {
                    page.RemoveAnnotation(annotation);
                    PdfPopupAnnotation popup = annotation.GetPopup();
                    if (popup != null)
                    {
                        page.RemoveAnnotation(popup);
                    }
                }

                PdfCanvas canvas = new PdfCanvas(page);
                PdfStream redactRolloverAppearance = annotation.GetRedactRolloverAppearance();
                PdfString overlayText = annotation.GetOverlayText();
                Rectangle annotRect   = annotation.GetRectangle().ToRectangle();
                if (redactRolloverAppearance != null)
                {
                    DrawRolloverAppearance(canvas, redactRolloverAppearance, annotRect, redactAnnotations.Get(annotation));
                }
                else
                {
                    if (overlayText != null && !String.IsNullOrEmpty(overlayText.ToUnicodeString()))
                    {
                        DrawOverlayText(canvas, overlayText.ToUnicodeString(), annotRect, annotation.GetRepeat(), annotation.GetDefaultAppearance
                                            (), annotation.GetJustification());
                    }
                }
            }
        }
        public static List <string> GetHighlights(string pdfPath)
        {
            PdfReader pdfReader = new PdfReader(pdfPath);

            List <string> data = new List <string>();

            for (int i = 1; i <= pdfReader.NumberOfPages; i++)
            {
                var      page        = pdfReader.GetPageN(i);
                PdfArray annotations = page.GetAsArray(PdfName.ANNOTS);

                if (annotations != null)
                {
                    foreach (PdfObject annotationDict in annotations.ArrayList)
                    {
                        PdfDictionary annotation = (PdfDictionary)PdfReader.GetPdfObject(annotationDict);
                        PdfString     contents   = annotation.GetAsString(PdfName.CONTENTS);
                        // now use the String value of contents

                        if (contents != null)
                        {
                            data.Add(contents.ToUnicodeString());
                        }
                    }
                }
            }

            return(data);
        }
        public virtual String GetAttributeAsText(String attributeName)
        {
            PdfName   name    = PdfStructTreeRoot.ConvertRoleToPdfName(attributeName);
            PdfString attrVal = GetPdfObject().GetAsString(name);

            return(attrVal != null?attrVal.ToUnicodeString() : null);
        }
        private void AddChildToExistingParent(PdfDictionary fieldDic, ICollection <String> existingFields)
        {
            PdfDictionary parent = fieldDic.GetAsDictionary(PdfName.Parent);

            if (parent == null)
            {
                return;
            }
            PdfString parentName = parent.GetAsString(PdfName.T);

            if (parentName != null)
            {
                String name = parentName.ToUnicodeString();
                if (existingFields.Contains(name))
                {
                    PdfArray kids = parent.GetAsArray(PdfName.Kids);
                    kids.Add(fieldDic);
                }
                else
                {
                    parent.Put(PdfName.Kids, new PdfArray(fieldDic));
                    AddChildToExistingParent(parent, existingFields);
                }
            }
        }
Exemple #5
0
        public virtual void CustomDestinationPrefixTest()
        {
            IDictionary <String, int?> priorityMappings = new Dictionary <String, int?>();

            priorityMappings.Put("p", 1);
            OutlineHandler outlineHandler = new OutlineHandler().PutAllTagPriorityMappings(priorityMappings);

            outlineHandler.SetDestinationNamePrefix("prefix-");
            NUnit.Framework.Assert.AreEqual("prefix-", outlineHandler.GetDestinationNamePrefix());
            ProcessorContext context = new ProcessorContext(new ConverterProperties().SetOutlineHandler(outlineHandler
                                                                                                        ));

            context.Reset(new PdfDocument(new PdfWriter(new MemoryStream())));
            IElementNode elementNode = new JsoupElementNode(new iText.StyledXmlParser.Jsoup.Nodes.Element(iText.StyledXmlParser.Jsoup.Parser.Tag
                                                                                                          .ValueOf(TagConstants.P), TagConstants.P));
            IDictionary <String, String> styles = new Dictionary <String, String>();

            styles.Put(CssConstants.WHITE_SPACE, CssConstants.NORMAL);
            styles.Put(CssConstants.TEXT_TRANSFORM, CssConstants.LOWERCASE);
            // Styles are required in the constructor of the PTagWorker class
            elementNode.SetStyles(styles);
            outlineHandler.AddOutlineAndDestToDocument(new PTagWorker(elementNode, context), elementNode, context);
            PdfOutline pdfOutline = context.GetPdfDocument().GetOutlines(false).GetAllChildren()[0];

            NUnit.Framework.Assert.AreEqual("p1", pdfOutline.GetTitle());
            PdfString pdfStringDest = (PdfString)pdfOutline.GetDestination().GetPdfObject();

            NUnit.Framework.Assert.AreEqual("prefix-1", pdfStringDest.ToUnicodeString());
        }
        private LineSegment GetUnscaledBaselineWithOffset(float yOffset)
        {
            // we need to correct the width so we don't have an extra character and word spaces at the end.  The extra character and word spaces
            // are important for tracking relative text coordinate systems, but should not be part of the baseline
            String unicodeStr             = @string.ToUnicodeString();
            float  correctedUnscaledWidth = GetUnscaledWidth() - (gs.GetCharSpacing() + (unicodeStr.Length > 0 && unicodeStr
                                                                                         [unicodeStr.Length - 1] == ' ' ? gs.GetWordSpacing() : 0)) * (gs.GetHorizontalScaling() / 100f);

            return(new LineSegment(new Vector(0, yOffset, 1), new Vector(correctedUnscaledWidth, yOffset, 1)));
        }
        private static string Tostr(PdfString pdfstr)
        {
            string strRet = null;

            if (pdfstr != null)
            {
                strRet = pdfstr.ToUnicodeString();
            }
            return(strRet);
        }
Exemple #8
0
        /**
         * Deletes redact annotations from the page and substitutes them with either OverlayText or RO object if it's needed.
         */
        private void DeleteRedactAnnots(int pageNum)
        {
            HashSet2 <String> indirRefs;

            redactAnnotIndirRefs.TryGetValue(pageNum, out indirRefs);

            if (indirRefs == null || indirRefs.Count == 0)
            {
                return;
            }

            PdfReader      reader      = pdfStamper.Reader;
            PdfContentByte canvas      = pdfStamper.GetOverContent(pageNum);
            PdfDictionary  pageDict    = reader.GetPageN(pageNum);
            PdfArray       annotsArray = pageDict.GetAsArray(PdfName.ANNOTS);

            // j is for access annotRect (i can be decreased, so we need to store additional index,
            // indicating current position in ANNOTS array in case if we don't remove anything
            for (int i = 0, j = 0; i < annotsArray.Size; ++i, ++j)
            {
                PdfIndirectReference annotIndRef = annotsArray.GetAsIndirectObject(i);
                PdfDictionary        annotDict   = annotsArray.GetAsDict(i);

                if (indirRefs.Contains(annotIndRef.ToString()) || indirRefs.Contains(GetParentIndRefStr(annotDict)))
                {
                    PdfStream formXObj    = annotDict.GetAsStream(PdfName.RO);
                    PdfString overlayText = annotDict.GetAsString(PdfName.OVERLAYTEXT);

                    if (FillCleanedArea && formXObj != null)
                    {
                        PdfArray  rectArray = annotDict.GetAsArray(PdfName.RECT);
                        Rectangle annotRect = new Rectangle(rectArray.GetAsNumber(0).FloatValue,
                                                            rectArray.GetAsNumber(1).FloatValue,
                                                            rectArray.GetAsNumber(2).FloatValue,
                                                            rectArray.GetAsNumber(3).FloatValue);

                        InsertFormXObj(canvas, pageDict, formXObj, clippingRects[j], annotRect);
                    }
                    else if (FillCleanedArea && overlayText != null && overlayText.ToUnicodeString().Length > 0)
                    {
                        DrawOverlayText(canvas, clippingRects[j], overlayText,
                                        annotDict.GetAsString(PdfName.DA),
                                        annotDict.GetAsNumber(PdfName.Q),
                                        annotDict.GetAsBoolean(PdfName.REPEAT));
                    }

                    annotsArray.Remove(i--); // array size is changed, so we need to decrease i
                }
            }

            if (annotsArray.Size == 0)
            {
                pageDict.Remove(PdfName.ANNOTS);
            }
        }
Exemple #9
0
        private String GetPropertyAsString(PdfName name)
        {
            PdfString text   = properties.GetAsString(name);
            String    result = null;

            if (text != null)
            {
                result = text.ToUnicodeString();
            }
            return(result);
        }
Exemple #10
0
 virtual public String DecodeStringToUnicode(PdfString ps)
 {
     if (ps.IsHexWriting())
     {
         return(PdfEncodings.ConvertToString(ps.GetBytes(), "UnicodeBigUnmarked"));
     }
     else
     {
         return(ps.ToUnicodeString());
     }
 }
Exemple #11
0
        public virtual String GetActualText()
        {
            PdfString actualText = properties.GetAsString(PdfName.ActualText);
            String    result     = null;

            if (actualText != null)
            {
                result = actualText.ToUnicodeString();
            }
            return(result);
        }
        private static DateTime?ToDate(PdfString pdfstr)
        {
            string strRet = null;

            if (pdfstr != null)
            {
                strRet = pdfstr.ToUnicodeString();

                return(PdfDate.Decode(strRet));
            }
            return(null);
        }
        /// <summary>gets the /Name of the person signing the document.</summary>
        /// <returns>name of the person signing the document.</returns>
        public virtual String GetName()
        {
            PdfString nameStr  = GetPdfObject().GetAsString(PdfName.Name);
            PdfName   nameName = GetPdfObject().GetAsName(PdfName.Name);

            if (nameStr != null)
            {
                return(nameStr.ToUnicodeString());
            }
            else
            {
                return(nameName != null?nameName.GetValue() : null);
            }
        }
        private void CopyParentFormField(PdfPage toPage, IDictionary <String, PdfFormField> fieldsTo, PdfAnnotation
                                         annot, PdfFormField parentField)
        {
            PdfString parentName = parentField.GetFieldName();

            if (!fieldsTo.ContainsKey(parentName.ToUnicodeString()))
            {
                PdfFormField field = CreateParentFieldCopy(annot.GetPdfObject(), documentTo);
                PdfArray     kids  = field.GetKids();
                field.GetPdfObject().Remove(PdfName.Kids);
                formTo.AddField(field, toPage);
                field.GetPdfObject().Put(PdfName.Kids, kids);
            }
            else
            {
                PdfFormField field = MakeFormField(annot.GetPdfObject());
                if (field == null)
                {
                    return;
                }
                PdfString fieldName = field.GetFieldName();
                if (fieldName != null)
                {
                    PdfFormField existingField = fieldsTo.Get(fieldName.ToUnicodeString());
                    if (existingField != null)
                    {
                        PdfFormField mergedField = MergeFieldsWithTheSameName(field);
                        formTo.GetFormFields().Put(mergedField.GetFieldName().ToUnicodeString(), mergedField);
                    }
                    else
                    {
                        HashSet <String> existingFields = new HashSet <String>();
                        GetAllFieldNames(formTo.GetFields(), existingFields);
                        AddChildToExistingParent(annot.GetPdfObject(), existingFields, fieldsTo);
                    }
                }
                else
                {
                    if (!parentField.GetKids().Contains(field.GetPdfObject()))
                    {
                        HashSet <String> existingFields = new HashSet <String>();
                        GetAllFieldNames(formTo.GetFields(), existingFields);
                        AddChildToExistingParent(annot.GetPdfObject(), existingFields);
                    }
                }
            }
        }
Exemple #15
0
 private void GetAllFieldNames(PdfArray fields, ICollection <String> existingFields)
 {
     foreach (PdfObject field in fields)
     {
         PdfDictionary dic  = (PdfDictionary)field;
         PdfString     name = dic.GetAsString(PdfName.T);
         if (name != null)
         {
             existingFields.Add(name.ToUnicodeString());
         }
         PdfArray kids = dic.GetAsArray(PdfName.Kids);
         if (kids != null)
         {
             GetAllFieldNames(kids, existingFields);
         }
     }
 }
Exemple #16
0
        /// <summary>Highlights the options.</summary>
        /// <remarks>
        /// Highlights the options. If this method is used for Combo box, the first value in input array
        /// will be the field value
        /// </remarks>
        /// <param name="optionValues">Array of options to be highlighted</param>
        /// <returns>
        /// current
        /// <see cref="PdfChoiceFormField"/>
        /// </returns>
        public virtual iText.Forms.Fields.PdfChoiceFormField SetListSelected(String[] optionValues)
        {
            PdfArray options = GetOptions();
            PdfArray indices = new PdfArray();
            PdfArray values  = new PdfArray();

            foreach (String element in optionValues)
            {
                for (int index = 0; index < options.Size(); index++)
                {
                    PdfObject option = options.Get(index);
                    PdfString value  = null;
                    if (option.IsString())
                    {
                        value = (PdfString)option;
                    }
                    else
                    {
                        if (option.IsArray())
                        {
                            value = (PdfString)((PdfArray)option).Get(1);
                        }
                    }
                    if (value != null && value.ToUnicodeString().Equals(element))
                    {
                        indices.Add(new PdfNumber(index));
                        values.Add(value);
                    }
                }
            }
            if (indices.Size() > 0)
            {
                SetIndices(indices);
                if (values.Size() == 1)
                {
                    Put(PdfName.V, values.Get(0));
                }
                else
                {
                    Put(PdfName.V, values);
                }
            }
            RegenerateField();
            return(this);
        }
        private void CopyField(PdfPage toPage, IDictionary <String, PdfFormField> fieldsFrom, IDictionary <String, PdfFormField
                                                                                                           > fieldsTo, PdfAnnotation currentAnnot)
        {
            PdfDictionary parent = currentAnnot.GetPdfObject().GetAsDictionary(PdfName.Parent);

            if (parent != null)
            {
                PdfFormField parentField = GetParentField(parent, documentTo);
                if (parentField == null)
                {
                    return;
                }
                PdfString parentName = parentField.GetFieldName();
                if (parentName == null)
                {
                    return;
                }
                CopyParentFormField(toPage, fieldsTo, currentAnnot, parentField);
            }
            else
            {
                PdfString annotName       = currentAnnot.GetPdfObject().GetAsString(PdfName.T);
                String    annotNameString = null;
                if (annotName != null)
                {
                    annotNameString = annotName.ToUnicodeString();
                }
                if (annotNameString != null && fieldsFrom.ContainsKey(annotNameString))
                {
                    PdfFormField field = MakeFormField(currentAnnot.GetPdfObject());
                    if (field == null)
                    {
                        return;
                    }
                    if (fieldsTo.Get(annotNameString) != null)
                    {
                        field = MergeFieldsWithTheSameName(field);
                    }
                    // Form may be already added to the page. PdfAcroForm will take care about it.
                    formTo.AddField(field, toPage);
                    field.UpdateDefaultAppearance();
                }
            }
        }
        private void AddChildToExistingParent(PdfDictionary fieldDic, ICollection <String> existingFields, IDictionary
                                              <String, PdfFormField> fieldsTo)
        {
            PdfDictionary parent = fieldDic.GetAsDictionary(PdfName.Parent);

            if (parent == null)
            {
                return;
            }
            PdfString parentName = parent.GetAsString(PdfName.T);

            if (parentName != null)
            {
                String name = parentName.ToUnicodeString();
                if (existingFields.Contains(name))
                {
                    PdfArray kids = parent.GetAsArray(PdfName.Kids);
                    foreach (PdfObject kid in kids)
                    {
                        if (((PdfDictionary)kid).Get(PdfName.T).Equals(fieldDic.Get(PdfName.T)))
                        {
                            PdfFormField kidField = MakeFormField(kid);
                            PdfFormField field    = MakeFormField(fieldDic);
                            if (kidField == null || field == null)
                            {
                                continue;
                            }
                            fieldsTo.Put(kidField.GetFieldName().ToUnicodeString(), kidField);
                            PdfFormField mergedField = MergeFieldsWithTheSameName(field);
                            formTo.GetFormFields().Put(mergedField.GetFieldName().ToUnicodeString(), mergedField);
                            return;
                        }
                    }
                    kids.Add(fieldDic);
                }
                else
                {
                    parent.Put(PdfName.Kids, new PdfArray(fieldDic));
                    AddChildToExistingParent(parent, existingFields);
                }
            }
        }
        private void CopyField(PdfPage toPage, IDictionary <String, PdfFormField> fieldsFrom, IDictionary <String, PdfFormField
                                                                                                           > fieldsTo, PdfAnnotation currentAnnot)
        {
            PdfDictionary parent = currentAnnot.GetPdfObject().GetAsDictionary(PdfName.Parent);

            if (parent != null)
            {
                PdfFormField parentField = GetParentField(parent, documentTo);
                PdfString    parentName  = parentField.GetFieldName();
                if (parentName == null)
                {
                    return;
                }
                CopyParentFormField(toPage, fieldsTo, currentAnnot, parentField);
            }
            else
            {
                PdfString annotName       = currentAnnot.GetPdfObject().GetAsString(PdfName.T);
                String    annotNameString = null;
                if (annotName != null)
                {
                    annotNameString = annotName.ToUnicodeString();
                }
                if (annotNameString != null && fieldsFrom.ContainsKey(annotNameString))
                {
                    PdfFormField field = fieldsTo.Get(annotNameString);
                    if (field == null)
                    {
                        formTo.AddField(PdfFormField.MakeFormField(currentAnnot.GetPdfObject(), documentTo), null);
                    }
                    else
                    {
                        CopyExistingField(toPage, currentAnnot);
                    }
                }
            }
        }
        private IList <String> OptionsToUnicodeNames()
        {
            PdfArray       options = GetOptions();
            IList <String> optionsToUnicodeNames = new List <String>(options.Size());

            for (int index = 0; index < options.Size(); index++)
            {
                PdfObject option = options.Get(index);
                PdfString value  = null;
                if (option.IsString())
                {
                    value = (PdfString)option;
                }
                else
                {
                    if (option.IsArray())
                    {
                        value = (PdfString)((PdfArray)option).Get(1);
                    }
                }
                optionsToUnicodeNames.Add(value != null ? value.ToUnicodeString() : null);
            }
            return(optionsToUnicodeNames);
        }
Exemple #21
0
        private IDictionary <String, IList> ParseDAParam(PdfString DA)
        {
            IDictionary <String, IList> commandArguments = new Dictionary <String, IList>();
            PdfTokenizer tokeniser = new PdfTokenizer(new RandomAccessFileOrArray(new RandomAccessSourceFactory().CreateSource
                                                                                      (DA.ToUnicodeString().GetBytes(Encoding.UTF8))));
            IList currentArguments = new ArrayList();

            while (tokeniser.NextToken())
            {
                if (tokeniser.GetTokenType() == PdfTokenizer.TokenType.Other)
                {
                    String key = tokeniser.GetStringValue();
                    if ("RG".Equals(key) || "G".Equals(key) || "K".Equals(key))
                    {
                        key = "StrokeColor";
                    }
                    else
                    {
                        if ("rg".Equals(key) || "g".Equals(key) || "k".Equals(key))
                        {
                            key = "FillColor";
                        }
                    }
                    commandArguments.Put(key, currentArguments);
                    currentArguments = new ArrayList();
                }
                else
                {
                    switch (tokeniser.GetTokenType())
                    {
                    case PdfTokenizer.TokenType.Number: {
                        currentArguments.Add(new PdfNumber(System.Convert.ToSingle(tokeniser.GetStringValue(), System.Globalization.CultureInfo.InvariantCulture
                                                                                   )));
                        break;
                    }

                    case PdfTokenizer.TokenType.Name: {
                        currentArguments.Add(new PdfName(tokeniser.GetStringValue()));
                        break;
                    }

                    default: {
                        currentArguments.Add(tokeniser.GetStringValue());
                        break;
                    }
                    }
                }
            }
            return(commandArguments);
        }
Exemple #22
0
        private void DrawOverlayText(PdfContentByte canvas, IList <Rectangle> textRectangles, PdfString overlayText,
                                     PdfString otDA, PdfNumber otQ, PdfBoolean otRepeat)
        {
            ColumnText ct = new ColumnText(canvas);

            ct.SetLeading(0, 1.2F);
            ct.UseAscender = true;

            String otStr = overlayText.ToUnicodeString();

            canvas.SaveState();
            IDictionary <string, IList <object> > parsedDA = ParseDAParam(otDA);

            Font font = null;

            if (parsedDA.ContainsKey(STROKE_COLOR))
            {
                IList <object> strokeColorArgs = parsedDA[STROKE_COLOR];
                SetStrokeColor(canvas, strokeColorArgs);
            }

            if (parsedDA.ContainsKey(FILL_COLOR))
            {
                IList <object> fillColorArgs = parsedDA[FILL_COLOR];
                SetFillColor(canvas, fillColorArgs);
            }

            if (parsedDA.ContainsKey("Tf"))
            {
                IList <object> tfArgs = parsedDA["Tf"];
                font = RetrieveFontFromAcroForm((PdfName)tfArgs[0], (PdfNumber)tfArgs[1]);
            }

            foreach (Rectangle textRect in textRectangles)
            {
                ct.SetSimpleColumn(textRect);

                if (otQ != null)
                {
                    ct.Alignment = otQ.IntValue;
                }

                Phrase otPhrase;

                if (font != null)
                {
                    otPhrase = new Phrase(otStr, font);
                }
                else
                {
                    otPhrase = new Phrase(otStr);
                }

                float y = ct.YLine;

                if (otRepeat != null && otRepeat.BooleanValue)
                {
                    int status = ct.Go(true);

                    while (!ColumnText.HasMoreText(status))
                    {
                        otPhrase.Add(otStr);
                        ct.SetText(otPhrase);
                        ct.YLine = y;
                        status   = ct.Go(true);
                    }
                }

                ct.SetText(otPhrase);
                ct.YLine = y;
                ct.Go();
            }

            canvas.RestoreState();
        }
Exemple #23
0
        public FlowDocument Get_Highlighted_Text(string filenamePath)
        {
            FlowDocument doc = new FlowDocument();
            int          pageTo;
            bool         hasAnnot = false;

            try
            {
                using (PdfReader reader = new PdfReader(filenamePath))
                {
                    PdfDocument pdfDoc = new PdfDocument(reader);
                    pageTo = pdfDoc.GetNumberOfPages();
                    for (int i = 1; i <= pageTo; i++)
                    {
                        PdfPage page = pdfDoc.GetPage(i);
                        IList <iText.Kernel.Pdf.Annot.PdfAnnotation> annots = page.GetAnnotations();

                        if (annots.Count > 0)
                        {
                            hasAnnot = true;
                            Paragraph paragraph = new Paragraph();

                            paragraph.Inlines.Clear();
                            paragraph.Inlines.Add("------- Page:");
                            paragraph.Inlines.Add($"{i.ToString()}");
                            paragraph.Inlines.Add($"-------{Environment.NewLine}");
                            doc.Blocks.Add(paragraph);

                            foreach (iText.Kernel.Pdf.Annot.PdfAnnotation annot in annots)

                            {
                                Paragraph paragraph_annot = new Paragraph();
                                //Get Annotation from PDF File
                                PdfString annot_Text = annot.GetContents();
                                PdfName   subType    = annot.GetSubtype();
                                if (annot_Text != null)
                                {
                                    paragraph_annot.Inlines.Add(new Run($"{subType.GetValue()}")
                                    {
                                        FontWeight = FontWeights.Bold
                                    });
                                    paragraph_annot.Inlines.Add($":{Environment.NewLine}");
                                    paragraph_annot.Inlines.Add($"{annot_Text.ToUnicodeString()}{Environment.NewLine}");
                                    doc.Blocks.Add(paragraph_annot);
                                }
                            }
                        }
                    }
                    if (hasAnnot)
                    {
                        FileInfo  file            = new FileInfo(filenamePath);
                        Paragraph paragraph_title = new Paragraph();
                        paragraph_title.Inlines.Add(new Run(file.Name)
                        {
                            FontWeight = FontWeights.Bold
                        });
                        doc.Blocks.InsertBefore(doc.Blocks.FirstBlock, paragraph_title);
                    }
                    else
                    {
                        FileInfo  file            = new FileInfo(filenamePath);
                        Paragraph paragraph_title = new Paragraph();
                        paragraph_title.Inlines.Add($"There are no highlights or comments in: {Environment.NewLine} {file.Name}");
                        doc.Blocks.Add(paragraph_title);
                    }
                    //MessageBox.Show(annot_string);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return(doc);
        }
Exemple #24
0
        /// <summary>Verifies a signature.</summary>
        /// <remarks>
        /// Verifies a signature. Further verification can be done on the returned
        /// <see cref="PdfPKCS7"/>
        /// object.
        /// </remarks>
        /// <param name="name">the signature field name</param>
        /// <param name="provider">the provider or null for the default provider</param>
        /// <returns>PdfPKCS7 object to continue the verification</returns>
        public virtual PdfPKCS7 VerifySignature(String name)
        {
            PdfDictionary v = GetSignatureDictionary(name);

            if (v == null)
            {
                return(null);
            }
            try {
                PdfName   sub      = v.GetAsName(PdfName.SubFilter);
                PdfString contents = v.GetAsString(PdfName.Contents);
                PdfPKCS7  pk       = null;
                if (sub.Equals(PdfName.Adbe_x509_rsa_sha1))
                {
                    PdfString cert = v.GetAsString(PdfName.Cert);
                    if (cert == null)
                    {
                        cert = v.GetAsArray(PdfName.Cert).GetAsString(0);
                    }
                    pk = new PdfPKCS7(PdfEncodings.ConvertToBytes(contents.GetValue(), null), cert.GetValueBytes());
                }
                else
                {
                    pk = new PdfPKCS7(PdfEncodings.ConvertToBytes(contents.GetValue(), null), sub);
                }
                UpdateByteRange(pk, v);
                PdfString str = v.GetAsString(PdfName.M);
                if (str != null)
                {
                    pk.SetSignDate(PdfDate.Decode(str.ToString()));
                }
                PdfObject obj = v.Get(PdfName.Name);
                if (obj != null)
                {
                    if (obj.IsString())
                    {
                        pk.SetSignName(((PdfString)obj).ToUnicodeString());
                    }
                    else
                    {
                        if (obj.IsName())
                        {
                            pk.SetSignName(((PdfName)obj).GetValue());
                        }
                    }
                }
                str = v.GetAsString(PdfName.Reason);
                if (str != null)
                {
                    pk.SetReason(str.ToUnicodeString());
                }
                str = v.GetAsString(PdfName.Location);
                if (str != null)
                {
                    pk.SetLocation(str.ToUnicodeString());
                }
                return(pk);
            }
            catch (Exception e) {
                throw new PdfException(e);
            }
        }
        public virtual String GetReason()
        {
            PdfString reasonStr = GetPdfObject().GetAsString(PdfName.Reason);

            return(reasonStr != null?reasonStr.ToUnicodeString() : null);
        }
 public virtual void Copy(PdfPage fromPage, PdfPage toPage)
 {
     if (documentFrom != fromPage.GetDocument())
     {
         documentFrom = fromPage.GetDocument();
         formFrom     = PdfAcroForm.GetAcroForm(documentFrom, false);
     }
     if (documentTo != toPage.GetDocument())
     {
         documentTo = toPage.GetDocument();
         formTo     = PdfAcroForm.GetAcroForm(documentTo, true);
     }
     if (formFrom != null)
     {
         //duplicate AcroForm dictionary
         IList <PdfName> excludedKeys = new List <PdfName>();
         excludedKeys.Add(PdfName.Fields);
         excludedKeys.Add(PdfName.DR);
         PdfDictionary dict = formFrom.GetPdfObject().CopyTo(documentTo, excludedKeys, false);
         formTo.GetPdfObject().MergeDifferent(dict);
     }
     if (formFrom != null)
     {
         IDictionary <String, PdfFormField> fieldsFrom = formFrom.GetFormFields();
         if (fieldsFrom.Count > 0)
         {
             IDictionary <String, PdfFormField> fieldsTo = formTo.GetFormFields();
             IList <PdfAnnotation> annots = toPage.GetAnnotations();
             foreach (PdfAnnotation annot in annots)
             {
                 if (annot.GetSubtype().Equals(PdfName.Widget))
                 {
                     PdfDictionary parent = annot.GetPdfObject().GetAsDictionary(PdfName.Parent);
                     if (parent != null)
                     {
                         PdfFormField parentField = GetParentField(parent, documentTo);
                         PdfString    parentName  = parentField.GetFieldName();
                         if (parentName == null)
                         {
                             continue;
                         }
                         if (!fieldsTo.ContainsKey(parentName.ToUnicodeString()))
                         {
                             PdfFormField field = CreateParentFieldCopy(annot.GetPdfObject(), documentTo);
                             PdfArray     kids  = field.GetKids();
                             field.GetPdfObject().Remove(PdfName.Kids);
                             formTo.AddField(field, toPage);
                             field.GetPdfObject().Put(PdfName.Kids, kids);
                         }
                         else
                         {
                             PdfFormField field     = PdfFormField.MakeFormField(annot.GetPdfObject(), documentTo);
                             PdfString    fieldName = field.GetFieldName();
                             if (fieldName != null)
                             {
                                 PdfFormField existingField = fieldsTo.Get(fieldName.ToUnicodeString());
                                 if (existingField != null)
                                 {
                                     PdfFormField clonedField = PdfFormField.MakeFormField(field.GetPdfObject().Clone().MakeIndirect(documentTo
                                                                                                                                     ), documentTo);
                                     toPage.GetPdfObject().GetAsArray(PdfName.Annots).Add(clonedField.GetPdfObject());
                                     toPage.RemoveAnnotation(annot);
                                     MergeFieldsWithTheSameName(clonedField);
                                 }
                                 else
                                 {
                                     HashSet <String> existingFields = new HashSet <String>();
                                     GetAllFieldNames(formTo.GetFields(), existingFields);
                                     AddChildToExistingParent(annot.GetPdfObject(), existingFields);
                                 }
                             }
                             else
                             {
                                 if (!parentField.GetKids().Contains(field.GetPdfObject()))
                                 {
                                     HashSet <String> existingFields = new HashSet <String>();
                                     GetAllFieldNames(formTo.GetFields(), existingFields);
                                     AddChildToExistingParent(annot.GetPdfObject(), existingFields);
                                 }
                             }
                         }
                     }
                     else
                     {
                         PdfString annotName       = annot.GetPdfObject().GetAsString(PdfName.T);
                         String    annotNameString = null;
                         if (annotName != null)
                         {
                             annotNameString = annotName.ToUnicodeString();
                         }
                         if (annotNameString != null && fieldsFrom.ContainsKey(annotNameString))
                         {
                             PdfFormField field = fieldsTo.Get(annotNameString);
                             if (field != null)
                             {
                                 PdfDictionary clonedAnnot = (PdfDictionary)annot.GetPdfObject().Clone().MakeIndirect(documentTo);
                                 toPage.GetPdfObject().GetAsArray(PdfName.Annots).Add(clonedAnnot);
                                 toPage.RemoveAnnotation(annot);
                                 field = MergeFieldsWithTheSameName(PdfFormField.MakeFormField(clonedAnnot, toPage.GetDocument()));
                                 logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.DOCUMENT_ALREADY_HAS_FIELD, annotNameString
                                                                      ));
                                 PdfArray kids = field.GetKids();
                                 if (kids != null)
                                 {
                                     field.GetPdfObject().Remove(PdfName.Kids);
                                     formTo.AddField(field, toPage);
                                     field.GetPdfObject().Put(PdfName.Kids, kids);
                                 }
                                 else
                                 {
                                     formTo.AddField(field, toPage);
                                 }
                             }
                             else
                             {
                                 formTo.AddField(PdfFormField.MakeFormField(annot.GetPdfObject(), documentTo), null);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
        /// <summary>Gets the string defining the namespace name.</summary>
        /// <returns>
        /// a
        /// <see cref="System.String"/>
        /// defining the namespace name (conventionally a uniform
        /// resource identifier, or URI).
        /// </returns>
        public virtual String GetNamespaceName()
        {
            PdfString ns = GetPdfObject().GetAsString(PdfName.NS);

            return(ns != null?ns.ToUnicodeString() : null);
        }
Exemple #28
0
 protected override void CheckLayer(PdfWriter writer, int key, Object obj1)
 {
     if (obj1 is IPdfOCG)
     {
     }
     else if (obj1 is PdfOCProperties)
     {
         PdfOCProperties      properties  = (PdfOCProperties)obj1;
         List <PdfDictionary> configsList = new List <PdfDictionary>();
         PdfDictionary        d           = properties.GetAsDict(PdfName.D);
         if (d != null)
         {
             configsList.Add(d);
         }
         PdfArray configs = properties.GetAsArray(PdfName.CONFIGS);
         if (configs != null)
         {
             for (int i = 0; i < configs.Size; i++)
             {
                 PdfDictionary config = configs.GetAsDict(i);
                 if (config != null)
                 {
                     configsList.Add(config);
                 }
             }
         }
         HashSet2 <PdfObject> ocgs      = new HashSet2 <PdfObject>();
         PdfArray             ocgsArray = properties.GetAsArray(PdfName.OCGS);
         if (ocgsArray != null)
         {
             for (int i = 0; i < ocgsArray.Size; i++)
             {
                 ocgs.Add(ocgsArray[i]);
             }
         }
         HashSet2 <String>    names = new HashSet2 <String>();
         HashSet2 <PdfObject> order = new HashSet2 <PdfObject>();
         foreach (PdfDictionary config in configsList)
         {
             PdfString name = config.GetAsString(PdfName.NAME);
             if (name == null)
             {
                 throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("optional.content.configuration.dictionary.shall.contain.name.entry"));
             }
             String name1 = name.ToUnicodeString();
             if (names.Contains(name1))
             {
                 throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("value.of.name.entry.shall.be.unique.amongst.all.optional.content.configuration.dictionaries"));
             }
             names.Add(name1);
             if (config.Contains(PdfName.AS))
             {
                 throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("the.as.key.shall.not.appear.in.any.optional.content.configuration.dictionary"));
             }
             PdfArray orderArray = config.GetAsArray(PdfName.ORDER);
             if (orderArray != null)
             {
                 fillOrderRecursively(orderArray, order);
             }
         }
         if (order.Count != ocgs.Count)
         {
             throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("order.array.shall.contain.references.to.all.ocgs"));
         }
         ocgs.RetainAll(order);
         if (order.Count != ocgs.Count)
         {
             throw new PdfAConformanceException(MessageLocalization.GetComposedMessage("order.array.shall.contain.references.to.all.ocgs"));
         }
     }
     else
     {
     }
 }
Exemple #29
0
 private String ToUnicodeString(PdfString pdfString)
 {
     return(pdfString != null?pdfString.ToUnicodeString() : null);
 }
        /// <summary>Gets the /Location entry value.</summary>
        /// <returns>physical location of signing.</returns>
        public virtual String GetLocation()
        {
            PdfString locationStr = GetPdfObject().GetAsString(PdfName.Location);

            return(locationStr != null?locationStr.ToUnicodeString() : null);
        }