コード例 #1
0
 /// <summary>Sets the name indicating the field to be signed.</summary>
 /// <remarks>
 /// Sets the name indicating the field to be signed. The field can already be presented in the
 /// document but shall not be signed. If the field is not presented in the document, it will be created.
 /// </remarks>
 /// <param name="fieldName">The name indicating the field to be signed.</param>
 public virtual void SetFieldName(String fieldName)
 {
     if (fieldName != null)
     {
         if (fieldName.IndexOf('.') >= 0)
         {
             throw new ArgumentException(PdfException.FieldNamesCannotContainADot);
         }
         PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, true);
         if (acroForm.GetField(fieldName) != null)
         {
             PdfFormField field = acroForm.GetField(fieldName);
             if (!PdfName.Sig.Equals(field.GetFormType()))
             {
                 throw new ArgumentException(PdfException.FieldTypeIsNotASignatureFieldType);
             }
             if (field.GetValue() != null)
             {
                 throw new ArgumentException(PdfException.FieldAlreadySigned);
             }
             appearance.SetFieldName(fieldName);
             IList <PdfWidgetAnnotation> widgets = field.GetWidgets();
             if (widgets.Count > 0)
             {
                 PdfWidgetAnnotation widget = widgets[0];
                 appearance.SetPageRect(GetWidgetRectangle(widget));
                 appearance.SetPageNumber(GetWidgetPageNumber(widget));
             }
         }
         this.fieldName = fieldName;
     }
 }
コード例 #2
0
        /// <summary>Get the page number associated to the provided widget.</summary>
        /// <param name="widget">PdfWidgetAnnotation from which to extract the page number</param>
        /// <returns>page number</returns>
        protected internal virtual int GetWidgetPageNumber(PdfWidgetAnnotation widget)
        {
            int           pageNumber = 0;
            PdfDictionary pageDict   = widget.GetPdfObject().GetAsDictionary(PdfName.P);

            if (pageDict != null)
            {
                pageNumber = document.GetPageNumber(pageDict);
            }
            else
            {
                for (int i = 1; i <= document.GetNumberOfPages(); i++)
                {
                    PdfPage page = document.GetPage(i);
                    if (!page.IsFlushed())
                    {
                        if (page.ContainsAnnotation(widget))
                        {
                            pageNumber = i;
                            break;
                        }
                    }
                }
            }
            return(pageNumber);
        }
コード例 #3
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);

            IDictionary <String, PdfFormField> fields = form.GetFormFields();
            PdfFormField        field            = fields["timezone2"];
            PdfWidgetAnnotation widgetAnnotation = field.GetWidgets()[0];
            PdfArray            annotationRect   = widgetAnnotation.GetRectangle();

            // Change value of the right coordinate (index 2 corresponds with right coordinate)
            annotationRect.Set(2, new PdfNumber(annotationRect.GetAsNumber(2).FloatValue() - 10f));

            pdfDoc.Close();
        }
コード例 #4
0
        internal void RemoveAnnotation(PdfWidgetAnnotation widget)
        {
            var kids = Elements.GetArray(Keys.Kids);

            if (kids != null)
            {
                for (var i = 0; i < kids.Elements.Count; i++)
                {
                    var kid = kids.Elements.GetObject(i);
                    if (kid != null && kid.ObjectID == widget.ObjectID)
                    {
                        kids.Elements.RemoveAt(i);
                    }
                }
            }
            Annotations.Elements.Remove(widget);
        }
コード例 #5
0
 public virtual void AnnotationCheckTest04()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         PdfPage page        = doc.AddNewPage();
         Rectangle rect      = new Rectangle(100, 650, 400, 100);
         PdfAnnotation annot = new PdfWidgetAnnotation(rect);
         annot.SetContents(new PdfString(""));
         annot.SetFlag(PdfAnnotation.PRINT);
         page.AddAnnotation(annot);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.EVERY_ANNOTATION_SHALL_HAVE_AT_LEAST_ONE_APPEARANCE_DICTIONARY))
     ;
 }
コード例 #6
0
        public virtual void AnnotationCheckTest03()
        {
            String       outPdf = destinationFolder + "pdfA2b_annotationCheckTest03.pdf";
            String       cmpPdf = cmpFolder + "cmp_pdfA2b_annotationCheckTest03.pdf";
            PdfWriter    writer = new PdfWriter(outPdf);
            Stream       @is    = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfADocument doc    = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", ""
                                                                                                              , "http://www.color.org", "sRGB IEC61966-2.1", @is));
            PdfPage       page  = doc.AddNewPage();
            Rectangle     rect  = new Rectangle(100, 100, 0, 0);
            PdfAnnotation annot = new PdfWidgetAnnotation(rect);

            annot.SetContents(new PdfString(""));
            annot.SetFlag(PdfAnnotation.PRINT);
            page.AddAnnotation(annot);
            doc.Close();
            CompareResult(outPdf, cmpPdf);
        }
コード例 #7
0
 public virtual void AnnotationCheckTest06()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         PdfPage page        = doc.AddNewPage();
         Rectangle rect      = new Rectangle(100, 100, 100, 100);
         PdfAnnotation annot = new PdfWidgetAnnotation(rect);
         annot.SetFlag(PdfAnnotation.PRINT);
         annot.SetNormalAppearance(new PdfDictionary());
         page.AddAnnotation(annot);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.APPEARANCE_DICTIONARY_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_STREAM_VALUE))
     ;
 }
コード例 #8
0
 public virtual void AnnotationCheckTest06()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         PdfPage page        = doc.AddNewPage();
         Rectangle rect      = new Rectangle(100, 100, 100, 100);
         PdfAnnotation annot = new PdfWidgetAnnotation(rect);
         annot.SetFlag(PdfAnnotation.PRINT);
         annot.SetNormalAppearance(new PdfDictionary());
         page.AddAnnotation(annot);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.TypeOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.AppearanceDictionaryShallContainOnlyTheNKeyWithStreamValue));
     ;
 }
コード例 #9
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument         pdfDoc           = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfAcroForm         form             = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfFormField        field            = form.GetField("Name");
            PdfWidgetAnnotation widgetAnnotation = field.GetWidgets()[0];
            PdfArray            annotationRect   = widgetAnnotation.GetRectangle();

            // Change value of the right coordinate (index 2 corresponds with right coordinate)
            annotationRect.Set(2, new PdfNumber(annotationRect.GetAsNumber(2).FloatValue() + 20f));

            String value = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
                           "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

            field.SetValue(value);
            form.GetField("Company").SetValue(value);

            pdfDoc.Close();
        }
コード例 #10
0
 public virtual void AnnotationCheckTest08()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         PdfPage page        = doc.AddNewPage();
         Rectangle rect      = new Rectangle(100, 650, 400, 100);
         Rectangle formRect  = new Rectangle(400, 100);
         PdfAnnotation annot = new PdfWidgetAnnotation(rect);
         annot.SetContents(new PdfString(""));
         annot.SetFlags(PdfAnnotation.PRINT);
         annot.GetPdfObject().Put(PdfName.FT, PdfName.Btn);
         annot.SetNormalAppearance(CreateAppearance(doc, formRect));
         page.AddAnnotation(annot);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.InstanceOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.APPEARANCE_DICTIONARY_OF_WIDGET_SUBTYPE_AND_BTN_FIELD_TYPE_SHALL_CONTAIN_ONLY_THE_N_KEY_WITH_DICTIONARY_VALUE))
     ;
 }
コード例 #11
0
 public virtual void AnnotationCheckTest08()
 {
     NUnit.Framework.Assert.That(() => {
         PdfWriter writer = new PdfWriter(new ByteArrayOutputStream());
         Stream @is       = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
         PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", ""
                                                                                                        , "http://www.color.org", "sRGB IEC61966-2.1", @is));
         PdfPage page        = doc.AddNewPage();
         Rectangle rect      = new Rectangle(100, 650, 400, 100);
         Rectangle formRect  = new Rectangle(400, 100);
         PdfAnnotation annot = new PdfWidgetAnnotation(rect);
         annot.SetContents(new PdfString(""));
         annot.SetFlags(PdfAnnotation.PRINT);
         annot.GetPdfObject().Put(PdfName.FT, PdfName.Btn);
         annot.SetNormalAppearance(CreateAppearance(doc, formRect));
         page.AddAnnotation(annot);
         doc.Close();
     }
                                 , NUnit.Framework.Throws.TypeOf <PdfAConformanceException>().With.Message.EqualTo(PdfAConformanceException.AppearanceDictionaryOfWidgetSubtypeAndBtnFieldTypeShallContainOnlyTheNKeyWithDictionaryValue));
     ;
 }
コード例 #12
0
 protected internal PdfTextFormField(PdfWidgetAnnotation widget, PdfDocument pdfDocument)
     : base(widget, pdfDocument)
 {
 }
コード例 #13
0
        /// <summary>This is the first method to be called when using external signatures.</summary>
        /// <remarks>
        /// This is the first method to be called when using external signatures. The general sequence is:
        /// preClose(), getDocumentBytes() and close().
        /// <p>
        /// <CODE>exclusionSizes</CODE> must contain at least
        /// the <CODE>PdfName.CONTENTS</CODE> key with the size that it will take in the
        /// document. Note that due to the hex string coding this size should be byte_size*2+2.
        /// </remarks>
        /// <param name="exclusionSizes">
        /// Map with names and sizes to be excluded in the signature
        /// calculation. The key is a PdfName and the value an Integer. At least the /Contents must be present
        /// </param>
        /// <exception cref="System.IO.IOException">on error</exception>
        protected internal virtual void PreClose(IDictionary <PdfName, int?> exclusionSizes)
        {
            if (preClosed)
            {
                throw new PdfException(PdfException.DocumentAlreadyPreClosed);
            }
            // TODO: add mergeVerification functionality
            preClosed = true;
            PdfAcroForm   acroForm   = PdfAcroForm.GetAcroForm(document, true);
            SignatureUtil sgnUtil    = new SignatureUtil(document);
            String        name       = GetFieldName();
            bool          fieldExist = sgnUtil.DoesSignatureFieldExist(name);

            acroForm.SetSignatureFlags(PdfAcroForm.SIGNATURE_EXIST | PdfAcroForm.APPEND_ONLY);
            PdfSigFieldLockDictionary fieldLock = null;

            if (cryptoDictionary == null)
            {
                throw new PdfException(PdfException.NoCryptoDictionaryDefined);
            }
            cryptoDictionary.GetPdfObject().MakeIndirect(document);
            if (fieldExist)
            {
                PdfSignatureFormField sigField = (PdfSignatureFormField)acroForm.GetField(fieldName);
                sigField.Put(PdfName.V, cryptoDictionary.GetPdfObject());
                fieldLock = sigField.GetSigFieldLockDictionary();
                if (fieldLock == null && this.fieldLock != null)
                {
                    this.fieldLock.GetPdfObject().MakeIndirect(document);
                    sigField.Put(PdfName.Lock, this.fieldLock.GetPdfObject());
                    fieldLock = this.fieldLock;
                }
                sigField.Put(PdfName.P, document.GetPage(appearance.GetPageNumber()).GetPdfObject());
                sigField.Put(PdfName.V, cryptoDictionary.GetPdfObject());
                PdfObject obj   = sigField.GetPdfObject().Get(PdfName.F);
                int       flags = 0;
                if (obj != null && obj.IsNumber())
                {
                    flags = ((PdfNumber)obj).IntValue();
                }
                flags |= PdfAnnotation.LOCKED;
                sigField.Put(PdfName.F, new PdfNumber(flags));
                PdfDictionary ap = new PdfDictionary();
                ap.Put(PdfName.N, appearance.GetAppearance().GetPdfObject());
                sigField.Put(PdfName.AP, ap);
                sigField.SetModified();
            }
            else
            {
                PdfWidgetAnnotation widget = new PdfWidgetAnnotation(appearance.GetPageRect());
                widget.SetFlags(PdfAnnotation.PRINT | PdfAnnotation.LOCKED);
                PdfSignatureFormField sigField = PdfFormField.CreateSignature(document);
                sigField.SetFieldName(name);
                sigField.Put(PdfName.V, cryptoDictionary.GetPdfObject());
                sigField.AddKid(widget);
                if (this.fieldLock != null)
                {
                    this.fieldLock.GetPdfObject().MakeIndirect(document);
                    sigField.Put(PdfName.Lock, this.fieldLock.GetPdfObject());
                    fieldLock = this.fieldLock;
                }
                int pagen = appearance.GetPageNumber();
                widget.SetPage(document.GetPage(pagen));
                PdfDictionary ap = widget.GetAppearanceDictionary();
                if (ap == null)
                {
                    ap = new PdfDictionary();
                    widget.Put(PdfName.AP, ap);
                }
                ap.Put(PdfName.N, appearance.GetAppearance().GetPdfObject());
                acroForm.AddField(sigField, document.GetPage(pagen));
                if (acroForm.GetPdfObject().IsIndirect())
                {
                    acroForm.SetModified();
                }
                else
                {
                    //Acroform dictionary is a Direct dictionary,
                    //for proper flushing, catalog needs to be marked as modified
                    document.GetCatalog().SetModified();
                }
            }
            exclusionLocations = new Dictionary <PdfName, PdfLiteral>();
            PdfLiteral lit = new PdfLiteral(80);

            exclusionLocations[PdfName.ByteRange] = lit;
            cryptoDictionary.Put(PdfName.ByteRange, lit);
            foreach (KeyValuePair <PdfName, int?> entry in exclusionSizes)
            {
                PdfName key = entry.Key;
                lit = new PdfLiteral((int)entry.Value);
                exclusionLocations[key] = lit;
                cryptoDictionary.Put(key, lit);
            }
            if (certificationLevel > 0)
            {
                AddDocMDP(cryptoDictionary);
            }
            if (fieldLock != null)
            {
                AddFieldMDP(cryptoDictionary, fieldLock);
            }
            if (signatureEvent != null)
            {
                signatureEvent.GetSignatureDictionary(cryptoDictionary);
            }
            if (certificationLevel > 0)
            {
                // add DocMDP entry to root
                PdfDictionary docmdp = new PdfDictionary();
                docmdp.Put(PdfName.DocMDP, cryptoDictionary.GetPdfObject());
                document.GetCatalog().Put(PdfName.Perms, docmdp);
                document.GetCatalog().SetModified();
            }
            cryptoDictionary.GetPdfObject().Flush(false);
            document.Close();
            range = new long[exclusionLocations.Count * 2];
            long byteRangePosition = exclusionLocations.Get(PdfName.ByteRange).GetPosition();

            exclusionLocations.JRemove(PdfName.ByteRange);
            int idx = 1;

            foreach (PdfLiteral lit1 in exclusionLocations.Values)
            {
                long n = lit1.GetPosition();
                range[idx++] = n;
                range[idx++] = lit1.GetBytesCount() + n;
            }
            iText.IO.Util.JavaUtil.Sort(range, 1, range.Length - 1);
            for (int k = 3; k < range.Length - 2; k += 2)
            {
                range[k] -= range[k - 1];
            }
            if (tempFile == null)
            {
                bout = temporaryOS.ToArray();
                range[range.Length - 1] = bout.Length - range[range.Length - 2];
                MemoryStream    bos = new MemoryStream();
                PdfOutputStream os  = new PdfOutputStream(bos);
                os.Write('[');
                for (int k_1 = 0; k_1 < range.Length; ++k_1)
                {
                    os.WriteLong(range[k_1]).Write(' ');
                }
                os.Write(']');
                System.Array.Copy(bos.ToArray(), 0, bout, (int)byteRangePosition, bos.Length);
            }
            else
            {
                try {
                    raf = FileUtil.GetRandomAccessFile(tempFile);
                    long len = raf.Length;
                    range[range.Length - 1] = len - range[range.Length - 2];
                    MemoryStream    bos = new MemoryStream();
                    PdfOutputStream os  = new PdfOutputStream(bos);
                    os.Write('[');
                    for (int k_1 = 0; k_1 < range.Length; ++k_1)
                    {
                        os.WriteLong(range[k_1]).Write(' ');
                    }
                    os.Write(']');
                    raf.Seek(byteRangePosition);
                    raf.Write(bos.ToArray(), 0, (int)bos.Length);
                }
                catch (System.IO.IOException e) {
                    try {
                        raf.Close();
                    }
                    catch (Exception) {
                    }
                    try {
                        tempFile.Delete();
                    }
                    catch (Exception) {
                    }
                    throw;
                }
            }
        }
コード例 #14
0
 /// <summary>Get the rectangle associated to the provided widget.</summary>
 /// <param name="widget">PdfWidgetAnnotation to extract the rectangle from</param>
 /// <returns>Rectangle</returns>
 protected internal virtual Rectangle GetWidgetRectangle(PdfWidgetAnnotation widget)
 {
     return(widget.GetRectangle().ToRectangle());
 }
コード例 #15
0
 private void FixAcroFields(PdfAcroField.PdfAcroFieldCollection formFields, PdfImportedObjectTable importedObjectTable)
 {
     for (var i = 0; i < formFields.Elements.Count; i++)
     {
         var field = formFields[i];
         if (field.Owner != _document)
         {
             field._document = _document;
         }
         field.Reference.Document = _document;
         if (field.ObjectID.IsEmpty || !_document._irefTable.Contains(field.ObjectID))
         {
             _document._irefTable.Add(field);
         }
         //// fix the /P entry for Field-Annotations
         //var fieldPage = field.Elements.GetDictionary(PdfAcroField.Keys.Page);
         //if (fieldPage != null && fieldPage.Owner != _document)
         //{
         //    var importedPage = importedObjectTable.Contains(fieldPage.ObjectID) ? importedObjectTable[fieldPage.ObjectID] : null;
         //    if (importedPage != null)
         //    {
         //        field.Elements.SetReference(PdfAcroField.Keys.Page, importedPage.Value);
         //        Debug.WriteLine(String.Format("Fixed page of '{0}' ({1}) -> {2} = {3}", field.FullyQualifiedName, field.ObjectID, fieldPage.ObjectID, importedPage.ObjectID));
         //    }
         //    else
         //        Debug.WriteLine(String.Format("Can't fix page of '{0}' ({1}), imported page not found", field.FullyQualifiedName, field.ObjectID));
         //}
         // Annotations are "partly" imported, we need to fix the /P entry
         for (var a = 0; a < field.Annotations.Elements.Count; a++)
         {
             var widget = field.Annotations.Elements[a];
             if (widget != null)
             {
                 // the owner has to be fixed as well...
                 // Note: it was observed that some objects referenced by the widget were still owned by the imported document, but that seems to be fixed on saving...
                 if (widget.Owner != _document)
                 {
                     if (_document._irefTable.Contains(widget.ObjectID))
                     {
                         widget._document          = _document;
                         widget.Reference.Document = _document;
                         if (!_document._irefTable.Contains(widget.ObjectID))
                         {
                             _document._irefTable.Add(widget);
                         }
                     }
                     else
                     {
                         // this was never needed during debugging, we leave it here just in case...
                         var importedWidget = ImportClosure(importedObjectTable, _document, widget) as PdfDictionary;
                         if (importedWidget != null)
                         {
                             widget = new PdfWidgetAnnotation(importedWidget);
                         }
                     }
                     FixDocumentRef(widget, importedObjectTable);
                 }
                 var widgetPage = widget.Page;
                 if (widgetPage != null && widgetPage.Owner != _document)
                 {
                     var importedPage = importedObjectTable.Contains(widgetPage.ObjectID) ? importedObjectTable[widgetPage.ObjectID] : null;
                     if (importedPage != null)
                     {
                         widget.Elements.SetReference(PdfAnnotation.Keys.Page, importedPage.Value);
                         Debug.WriteLine(String.Format("Fixed page of Widget '{0}' ({1}) -> {2} = {3}", field.FullyQualifiedName, field.ObjectID, widgetPage.ObjectID, importedPage.ObjectID));
                         var ip = importedPage.Value as PdfPage;
                         // the widget is a PdfWidgetAnnotation, but the "real" object may be something else (e.g. a PdfGenericField), so we check the referenced object instead
                         if (ip != null && !ip.Annotations.Elements.Contains(widget.Reference))
                         {
                             ip.Annotations.Elements.Add(widget.Reference.Value);
                         }
                     }
                 }
                 else if (widgetPage is PdfPage)
                 {
                     // add widget to the pages' annotations if not already present
                     if (!((PdfPage)widgetPage).Annotations.Elements.Contains(widget.Reference))
                     {
                         ((PdfPage)widgetPage).Annotations.Elements.Add(widget);
                     }
                 }
             }
         }
         if (field.HasKids)
         {
             FixAcroFields(field.Fields, importedObjectTable);
         }
     }
 }