public void CreatePdf(String filename)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(filename));
            Document    doc    = new Document(pdfDoc);

            doc.Add(new Paragraph("Hello World!"));

            // Create a signature form field
            PdfFormField field = PdfFormField.CreateSignature(pdfDoc,
                                                              new Rectangle(72, 632, 200, 100));

            field.SetFieldName(SIGNAME);
            field.SetPage(1);

            // Set the widget properties
            field.GetWidgets()[0].SetHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT).SetFlags(PdfAnnotation.PRINT);

            PdfDictionary mkDictionary = field.GetWidgets()[0].GetAppearanceCharacteristics();

            if (null == mkDictionary)
            {
                mkDictionary = new PdfDictionary();
            }

            PdfArray black = new PdfArray();

            black.Add(new PdfNumber(ColorConstants.BLACK.GetColorValue()[0]));
            black.Add(new PdfNumber(ColorConstants.BLACK.GetColorValue()[1]));
            black.Add(new PdfNumber(ColorConstants.BLACK.GetColorValue()[2]));
            mkDictionary.Put(PdfName.BC, black);

            PdfArray white = new PdfArray();

            white.Add(new PdfNumber(ColorConstants.WHITE.GetColorValue()[0]));
            white.Add(new PdfNumber(ColorConstants.WHITE.GetColorValue()[1]));
            white.Add(new PdfNumber(ColorConstants.WHITE.GetColorValue()[2]));
            mkDictionary.Put(PdfName.BG, white);

            field.GetWidgets()[0].SetAppearanceCharacteristics(mkDictionary);

            PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(field);

            Rectangle      rect    = new Rectangle(0, 0, 200, 100);
            PdfFormXObject xObject = new PdfFormXObject(rect);
            PdfCanvas      canvas  = new PdfCanvas(xObject, pdfDoc);

            canvas
            .SetStrokeColor(ColorConstants.BLUE)
            .SetFillColor(ColorConstants.LIGHT_GRAY)
            .Rectangle(0 + 0.5, 0 + 0.5, 200 - 0.5, 100 - 0.5)
            .FillStroke()
            .SetFillColor(ColorConstants.BLUE);
            new Canvas(canvas, rect).ShowTextAligned("SIGN HERE", 100, 50,
                                                     TextAlignment.CENTER, (float)(Math.PI / 180) * 25);

            // Note that Acrobat doesn't show normal appearance in the highlight mode.
            field.GetWidgets()[0].SetNormalAppearance(xObject.GetPdfObject());

            doc.Close();
        }
Beispiel #2
0
            public override void Draw(DrawContext drawContext)
            {
                base.Draw(drawContext);
                PdfFormField field = PdfFormField.CreateSignature(drawContext.GetDocument(), GetOccupiedAreaBBox());

                field.SetFieldName(name);
                field.GetWidgets()[0].SetHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT);
                field.GetWidgets()[0].SetFlags(PdfAnnotation.PRINT);
                PdfAcroForm.GetAcroForm(drawContext.GetDocument(), true).AddField(field);
            }
Beispiel #3
0
            public override void Draw(DrawContext drawContext)
            {
                base.Draw(drawContext);
                PdfFormField field = PdfFormField.CreateSignature(drawContext.GetDocument(), GetOccupiedAreaBBox());

                field.SetFieldName(name);
                if (Lock != null)
                {
                    field.Put(PdfName.Lock, this.Lock.MakeIndirect(drawContext.GetDocument()).GetPdfObject());
                }

                field.GetWidgets()[0].SetFlag(PdfAnnotation.PRINT);
                field.GetWidgets()[0].SetHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT);
                PdfAcroForm.GetAcroForm(drawContext.GetDocument(), true).AddField(field);
            }
Beispiel #4
0
        public virtual void BorderStyleInCreatedFormFieldsTest()
        {
            String outPdf = destinationFolder + "borderStyleInCreatedFormFields.pdf";
            String cmpPdf = sourceFolder + "cmp_borderStyleInCreatedFormFields.pdf";

            using (PdfDocument doc = new PdfDocument(new PdfWriter(outPdf))) {
                PdfAcroForm  form       = PdfAcroForm.GetAcroForm(doc, true);
                PdfFormField formField1 = PdfTextFormField.CreateText(doc, new Rectangle(100, 600, 100, 50), "firstField",
                                                                      "Hello, iText!");
                formField1.GetWidgets()[0].SetBorderStyle(PdfAnnotation.STYLE_BEVELED);
                formField1.SetBorderWidth(2).SetBorderColor(ColorConstants.BLUE);
                PdfFormField formField2 = PdfTextFormField.CreateText(doc, new Rectangle(100, 500, 100, 50), "secondField"
                                                                      , "Hello, iText!");
                formField2.GetWidgets()[0].SetBorderStyle(PdfAnnotation.STYLE_UNDERLINE);
                formField2.SetBorderWidth(2).SetBorderColor(ColorConstants.BLUE);
                PdfFormField formField3 = PdfTextFormField.CreateText(doc, new Rectangle(100, 400, 100, 50), "thirdField",
                                                                      "Hello, iText!");
                formField3.GetWidgets()[0].SetBorderStyle(PdfAnnotation.STYLE_INSET);
                formField3.SetBorderWidth(2).SetBorderColor(ColorConstants.BLUE);
                form.AddField(formField1);
                form.AddField(formField2);
                form.AddField(formField3);
                form.FlattenFields();
            }
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder));
        }
 private static void AddAttributes(String attributeValue, PdfFormField pdfFormField, PdfDocument pdfDocument)
 {
     foreach (PdfWidgetAnnotation widget in pdfFormField.GetWidgets())
     {
         PdfDictionary pdfObject = widget.GetPage().GetPdfObject();
         int           i         = widget.GetPdfObject().GetAsNumber(PdfName.StructParent).IntValue();
         PdfObjRef     objRef    = pdfDocument.GetStructTreeRoot().FindObjRefByStructParentIndex(pdfObject, i);
         if (objRef != null)
         {
             TagTreePointer p = pdfDocument.GetTagStructureContext().CreatePointerForStructElem((PdfStructElem)objRef.GetParent());
             IList <PdfStructureAttributes> attributes = p.GetProperties().GetAttributesList();
             bool printFieldAttrFound = false;
             foreach (PdfStructureAttributes attribute in attributes)
             {
                 if (attribute.GetAttributeAsEnum("O").Equals("PrintField"))
                 {
                     printFieldAttrFound = true;
                     break;
                 }
             }
             if (!printFieldAttrFound)
             {
                 p.GetProperties().AddAttributes(new PdfStructureAttributes("PrintField").AddEnumAttribute("Role", attributeValue));
             }
         }
         else
         {
             Console.Out.WriteLine("The object reference couldn't be found.");
             return;
         }
     }
 }
Beispiel #6
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;
     }
 }
Beispiel #7
0
        public virtual void TextStartsAfterFieldBorderTest()
        {
            // TODO DEVSIX-4809 text in form filed with borders must start after border
            String outPdf = destinationFolder + "textStartsAfterFieldBorderTest.pdf";
            String cmpPdf = sourceFolder + "cmp_textStartsAfterFieldBorderTest.pdf";

            using (PdfDocument doc = new PdfDocument(new PdfWriter(outPdf))) {
                PdfAcroForm  form           = PdfAcroForm.GetAcroForm(doc, true);
                PdfFormField insetFormField = PdfTextFormField.CreateText(doc, new Rectangle(90, 600, 200, 100), "insetFormField"
                                                                          );
                insetFormField.GetWidgets()[0].SetBorderStyle(PdfName.I);
                insetFormField.SetBorderWidth(15f).SetBorderColor(DeviceRgb.RED).SetValue("Text after border").RegenerateField
                    ();
                PdfFormField solidFormField = PdfTextFormField.CreateText(doc, new Rectangle(300, 600, 200, 100), "solidFormField"
                                                                          );
                solidFormField.GetWidgets()[0].SetBorderStyle(PdfName.S);
                solidFormField.SetBorderWidth(15f).SetBorderColor(DeviceRgb.RED).SetValue("Text after border").RegenerateField
                    ();
                PdfFormField underlineFormField = PdfTextFormField.CreateText(doc, new Rectangle(90, 450, 200, 100), "underlineFormField"
                                                                              );
                underlineFormField.GetWidgets()[0].SetBorderStyle(PdfName.U);
                underlineFormField.SetBorderWidth(15f).SetBorderColor(DeviceRgb.RED).SetValue("Text after border").RegenerateField
                    ();
                PdfFormField simpleFormField = PdfTextFormField.CreateText(doc, new Rectangle(300, 450, 200, 100), "formField1"
                                                                           );
                simpleFormField.SetBorderWidth(15f);
                simpleFormField.SetValue("Text after border").RegenerateField();
                form.AddField(insetFormField);
                form.AddField(solidFormField);
                form.AddField(underlineFormField);
                form.AddField(simpleFormField);
            }
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_"
                                                                             ));
        }
Beispiel #8
0
        /// <summary>Applies the default field properties.</summary>
        /// <param name="inputField">the input field</param>
        internal virtual void ApplyDefaultFieldProperties(PdfFormField inputField)
        {
            inputField.GetWidgets()[0].SetHighlightMode(PdfAnnotation.HIGHLIGHT_NONE);
            inputField.SetBorderWidth(0);
            TransparentColor color = GetPropertyAsTransparentColor(Property.FONT_COLOR);

            if (color != null)
            {
                inputField.SetColor(color.GetColor());
            }
        }
        private void SetFooter(PdfFormField toSet, iText.Kernel.Pdf.PdfDocument pdfDoc, int pagina, List <PdfConfiguratie> footerTeksten)
        {
            toSet.SetValue("");

            var afmetingen = toSet.GetWidgets().SelectMany(f => f.GetRectangle()).ToArray();
            var x          = (int)Convert.ToDouble(afmetingen[0].ToString().Replace(".", ","));
            var y          = (int)Convert.ToDouble(afmetingen[1].ToString().Replace(".", ","));
            var wWidth     = (int)Convert.ToDouble(afmetingen[2].ToString().Replace(".", ","));
            var wHeigth    = (int)Convert.ToDouble(afmetingen[3].ToString().Replace(".", ","));

            Document d           = new Document(pdfDoc);
            var      footerTekst = footerTeksten.FirstOrDefault();

            if (footerTekst == null)
            {
                return;
            }
            var paragraaf = new Paragraph(footerTekst.Value);

            paragraaf.SetFontSize(14);
            var styleBold = new Style();

            styleBold.SetBold();
            paragraaf.AddStyle(styleBold);
            var bottom = y + wHeigth - GetParagraafHeight(paragraaf, d, wWidth) * 2;

            paragraaf.SetFixedPosition(pagina, x, bottom, wWidth);
            d.Add(paragraaf);

            footerTekst = footerTeksten.Skip(1).FirstOrDefault();
            if (footerTekst == null)
            {
                return;
            }
            var paragraaf2 = new Paragraph(footerTekst.Value);

            paragraaf2.SetFontSize(12);
            bottom -= GetParagraafHeight(paragraaf2, d, wWidth);
            paragraaf2.SetFixedPosition(pagina, x, bottom, wWidth);
            d.Add(paragraaf2);

            footerTekst = footerTeksten.Skip(2).FirstOrDefault();
            if (footerTekst == null)
            {
                return;
            }
            var paragraaf3 = new Paragraph(footerTekst.Value);

            paragraaf3.SetFontSize(14);
            bottom -= GetParagraafHeight(paragraaf3, d, wWidth);
            paragraaf3.SetFixedPosition(pagina, x, bottom, wWidth);
            d.Add(paragraaf3);
        }
Beispiel #10
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();
        }
Beispiel #11
0
        public virtual void DashedBorderWithBackgroundTest()
        {
            String outPdf = destinationFolder + "dashedBorderWithBackground.pdf";
            String cmpPdf = sourceFolder + "cmp_dashedBorderWithBackground.pdf";

            using (PdfDocument doc = new PdfDocument(new PdfWriter(outPdf))) {
                PdfAcroForm  form      = PdfAcroForm.GetAcroForm(doc, true);
                PdfFormField formField = PdfTextFormField.CreateText(doc, new Rectangle(100, 600, 200, 100), "formField");
                formField.GetWidgets()[0].SetBorderStyle(PdfName.D);
                formField.SetBorderWidth(3f).SetBorderColor(DeviceRgb.RED).SetBackgroundColor(DeviceRgb.GREEN);
                formField.RegenerateField();
                form.AddField(formField);
            }
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder));
        }
Beispiel #12
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument  pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfAcroForm  form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfFormField button = form.CopyField("Test");
            PdfArray     rect   = button.GetWidgets()[0].GetRectangle();

            // Increase value of the right coordinate (index 2 corresponds with right coordinate)
            rect.Set(2, new PdfNumber(rect.GetAsNumber(2).FloatValue() + 172));

            button.SetValue("Print Amended");
            form.ReplaceField("Test", button);

            pdfDoc.Close();
        }
Beispiel #13
0
        public int GetAllignedFontSizeForMultiLines <T>(T detail, int defaultFontSize = 9)
        {
            IDictionary <String, PdfFormField> fields = _form.GetFormFields();

            Type type = detail.GetType();

            PropertyInfo[] properties     = type.GetProperties();
            int            targetFontsize = 0;

            foreach (PropertyInfo property in properties)
            {
                PdfFormField       toSet;
                PdfActionAttribute required = property.GetCustomAttribute <PdfActionAttribute>();

                if (fields.TryGetValue(property.Name, out toSet))
                {
                    var value = property.GetValue(detail, null);
                    if (!string.IsNullOrWhiteSpace(value?.ToString()))
                    {
                        if (required != null && required.Action.Equals(ActionFlag.MultiLines))
                        {
                            PdfFormField field    = fields[property.Name];
                            PdfArray     position = field.GetWidgets().First().GetRectangle();
                            float        width    = (float)(position.GetAsNumber(2).GetValue() - position.GetAsNumber(0).GetValue());
                            float        height   = (float)(position.GetAsNumber(3).GetValue() - position.GetAsNumber(1).GetValue());

                            PdfFontAttribute pdfFont = property.GetCustomAttribute <PdfFontAttribute>();
                            var font = pdfFont?.Type != null
                                ? PdfFontFactory.CreateRegisteredFont(pdfFont.Type)
                                : PdfFontFactory.CreateRegisteredFont(DefaultFont);

                            int latestTargetFontSize = GetFontSizeFittingMultiLinesInAcroForm(value.ToString(), width, height, font, defaultFontSize);
                            if (targetFontsize == 0)
                            {
                                targetFontsize = latestTargetFontSize;
                            }
                            else
                            {
                                targetFontsize = targetFontsize > latestTargetFontSize
                                    ? latestTargetFontSize
                                    : targetFontsize;
                            }
                        }
                    }
                }
            }
            return(targetFontsize);
        }
        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();
        }
        private int GetInfo(String character, PdfAcroForm form, String name)
        {
            PdfFormField field       = form.GetField(name);
            PdfFont      font        = field.GetFont();
            FontMetrics  fontMetrics = font.GetFontProgram().GetFontMetrics();
            float        fontSize    = field.GetFontSize();

            if (fontSize == 0)
            {
                return(1000);
            }

            Rectangle rectangle = field.GetWidgets()[0].GetRectangle().ToRectangle();

            // Factor here is a leading value. We calculate it by subtracting lower left corner value from
            // the upper right corner value of the glyph bounding box
            float factor = (fontMetrics.GetBbox()[3] - fontMetrics.GetBbox()[1]) / 1000f;

            int rows    = (int)Math.Round(rectangle.GetHeight() / (fontSize * factor) + 0.5f);
            int columns = (int)Math.Round(rectangle.GetWidth() / font.GetWidth(character, fontSize) + 0.5f);

            return(rows * columns);
        }
Beispiel #16
0
        public virtual void FormFieldBordersTest()
        {
            String outPdf = destinationFolder + "formFieldBorders.pdf";
            String cmpPdf = sourceFolder + "cmp_formFieldBorders.pdf";

            using (PdfDocument doc = new PdfDocument(new PdfWriter(outPdf))) {
                PdfAcroForm  form        = PdfAcroForm.GetAcroForm(doc, true);
                PdfFormField simpleField = PdfTextFormField.CreateText(doc, new Rectangle(300, 300, 200, 100), "simpleField"
                                                                       );
                simpleField.RegenerateField();
                PdfFormField insetField = PdfTextFormField.CreateText(doc, new Rectangle(50, 600, 200, 100), "insetField");
                insetField.GetWidgets()[0].SetBorderStyle(PdfName.I);
                insetField.SetBorderWidth(3f).SetBorderColor(DeviceRgb.RED).RegenerateField();
                PdfFormField underlineField = PdfTextFormField.CreateText(doc, new Rectangle(300, 600, 200, 100), "underlineField"
                                                                          );
                underlineField.GetWidgets()[0].SetBorderStyle(PdfName.U);
                underlineField.SetBorderWidth(3f).SetBorderColor(DeviceRgb.RED).RegenerateField();
                PdfFormField solidField = PdfTextFormField.CreateText(doc, new Rectangle(50, 450, 200, 100), "solidField");
                solidField.GetWidgets()[0].SetBorderStyle(PdfName.S);
                solidField.SetBorderWidth(3f).SetBorderColor(DeviceRgb.RED).RegenerateField();
                PdfFormField dashField = PdfTextFormField.CreateText(doc, new Rectangle(300, 450, 200, 100), "dashField");
                dashField.GetWidgets()[0].SetBorderStyle(PdfName.D);
                dashField.SetBorderWidth(3f).SetBorderColor(DeviceRgb.RED).RegenerateField();
                PdfFormField beveledField = PdfTextFormField.CreateText(doc, new Rectangle(50, 300, 200, 100), "beveledField"
                                                                        );
                beveledField.GetWidgets()[0].SetBorderStyle(PdfName.B);
                beveledField.SetBorderWidth(3f).SetBorderColor(DeviceRgb.RED).RegenerateField();
                form.AddField(simpleField);
                form.AddField(insetField);
                form.AddField(underlineField);
                form.AddField(solidField);
                form.AddField(dashField);
                form.AddField(beveledField);
            }
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder));
        }
Beispiel #17
0
        public void FillImageInAcroForm <T>(T detail)
        {
            IDictionary <String, PdfFormField> fields = _form.GetFormFields();

            Type type = detail.GetType();

            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                PdfFormField       toSet;
                PdfActionAttribute required = property.GetCustomAttribute <PdfActionAttribute>();

                if (required != null &&
                    (required.Action.Equals(ActionFlag.Ignore) ||
                     required.Action.Equals(ActionFlag.MultiLines)))
                {
                    continue;
                }

                if (fields.TryGetValue(property.Name, out toSet))
                {
                    var          value = property.GetValue(detail, null);
                    PdfFormField field = fields[property.Name];
                    if (!string.IsNullOrWhiteSpace(value?.ToString()))
                    {
                        var widgets = field.GetWidgets();
                        if (widgets == null || widgets.Count == 0)
                        {
                            throw new ArgumentNullException($"no widgets to the field");
                        }

                        PdfArray position = widgets.First().GetRectangle();

                        PdfPage page = field.GetWidgets().First().GetPage();
                        if (page == null)
                        {
                            throw new ArgumentNullException(
                                      $"field widget annotation is not associated with any page");
                        }
                        int pageNum = _pdfDoc.GetPageNumber(page);

                        float width  = (float)(position.GetAsNumber(2).GetValue() - position.GetAsNumber(0).GetValue());
                        float height = (float)(position.GetAsNumber(3).GetValue() - position.GetAsNumber(1).GetValue());

                        Image image = new Image(ImageDataFactory.Create(File.ReadAllBytes(value.ToString())));
                        image.ScaleToFit(width, height);

                        float startX = (float)position.GetAsNumber(0).GetValue();
                        float startY = (float)position.GetAsNumber(1).GetValue();

                        PdfFontAttribute pdfFont = property.GetCustomAttribute <PdfFontAttribute>();
                        if (pdfFont != null)
                        {
                            ImagePositionAdjustification(pdfFont.Justification, width, height, image.GetImageScaledWidth(), image.GetImageScaledHeight(),
                                                         (float)position.GetAsNumber(0).GetValue(), (float)position.GetAsNumber(1).GetValue(), out startX, out startY);
                        }

                        image.SetFixedPosition(pageNum, startX, startY);
                        _form.RemoveField(field.GetFieldName().ToString());
                        _doc.Add(image);
                    }
                    else
                    {
                        if (required != null)
                        {
                            if (required.Action.Equals(ActionFlag.Required))
                            {
                                throw new ArgumentNullException($"No {property.Name} image found");
                            }
                            if (required.Action.Equals(ActionFlag.Optional))
                            {
                                _form.RemoveField(field.GetFieldName().ToString());
                                continue;
                            }
                            if (required.Action.Equals(ActionFlag.NotAvailable))
                            {
                                toSet.SetValue("N/A").SetFontSizeAutoScale().SetReadOnly(true);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>Constructs appearance (top-level) for a signature.</summary>
        /// <remarks>
        /// Constructs appearance (top-level) for a signature.
        /// <p>
        /// Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A>
        /// for further details.
        /// </remarks>
        /// <returns>a top-level signature appearance</returns>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual PdfFormXObject GetAppearance()
        {
            PdfCanvas canvas;

            if (IsInvisible())
            {
                PdfFormXObject appearance = new PdfFormXObject(new Rectangle(0, 0));
                appearance.MakeIndirect(document);
                return(appearance);
            }
            if (n0 == null && !reuseAppearance)
            {
                CreateBlankN0();
            }
            if (n2 == null)
            {
                n2 = new PdfFormXObject(rect);
                n2.MakeIndirect(document);
                String text;
                if (layer2Text == null)
                {
                    StringBuilder buf = new StringBuilder();
                    buf.Append("Digitally signed by ");
                    String name = null;
                    CertificateInfo.X500Name x500name = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate);
                    if (x500name != null)
                    {
                        name = x500name.GetField("CN");
                        if (name == null)
                        {
                            name = x500name.GetField("E");
                        }
                    }
                    if (name == null)
                    {
                        name = "";
                    }
                    buf.Append(name).Append('\n');
                    buf.Append("Date: ").Append(SignUtils.DateToString(signDate));
                    if (reason != null)
                    {
                        buf.Append('\n').Append(reasonCaption).Append(reason);
                    }
                    if (location != null)
                    {
                        buf.Append('\n').Append(locationCaption).Append(location);
                    }
                    text = buf.ToString();
                }
                else
                {
                    text = layer2Text;
                }
                if (image != null)
                {
                    if (imageScale == 0)
                    {
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, rect.GetWidth(), 0, 0, rect.GetHeight(), 0, 0);
                    }
                    else
                    {
                        float usableScale = imageScale;
                        if (imageScale < 0)
                        {
                            usableScale = Math.Min(rect.GetWidth() / image.GetWidth(), rect.GetHeight() / image.GetHeight());
                        }
                        float w = image.GetWidth() * usableScale;
                        float h = image.GetHeight() * usableScale;
                        float x = (rect.GetWidth() - w) / 2;
                        float y = (rect.GetHeight() - h) / 2;
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, w, 0, 0, h, x, y);
                    }
                }
                PdfFont font;
                if (layer2Font == null)
                {
                    font = PdfFontFactory.CreateFont();
                }
                else
                {
                    font = layer2Font;
                }
                float     size          = layer2FontSize;
                Rectangle dataRect      = null;
                Rectangle signatureRect = null;
                if (renderingMode == PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION || renderingMode == PdfSignatureAppearance.RenderingMode
                    .GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null)
                {
                    if (rect.GetHeight() > rect.GetWidth())
                    {
                        signatureRect = new Rectangle(MARGIN, rect.GetHeight() / 2, rect.GetWidth() - 2 * MARGIN, rect.GetHeight()
                                                      / 2);
                        dataRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() / 2 - 2 * MARGIN);
                    }
                    else
                    {
                        // origin is the bottom-left
                        signatureRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() / 2 - 2 * MARGIN, rect.GetHeight() - 2 * MARGIN
                                                      );
                        dataRect = new Rectangle(rect.GetWidth() / 2 + MARGIN / 2, MARGIN, rect.GetWidth() / 2 - MARGIN, rect.GetHeight
                                                     () - 2 * MARGIN);
                    }
                }
                else
                {
                    if (renderingMode == PdfSignatureAppearance.RenderingMode.GRAPHIC)
                    {
                        if (signatureGraphic == null)
                        {
                            throw new InvalidOperationException();
                        }
                        /*MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")*/
                        signatureRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() - 2 * MARGIN);
                    }
                    else
                    {
                        // take all space available
                        dataRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() * (1 - TOP_SECTION
                                                                                                                   ) - 2 * MARGIN);
                    }
                }
                switch (renderingMode)
                {
                case PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION: {
                    String signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("CN");
                    if (signedBy == null)
                    {
                        signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("E");
                    }
                    if (signedBy == null)
                    {
                        signedBy = "";
                    }
                    canvas = new PdfCanvas(n2, document);
                    Paragraph paragraph = new Paragraph(signedBy).SetFont(font).SetFontSize(layer2FontSize).SetMargin(0).SetMultipliedLeading
                                              (0.9f);
                    new iText.Layout.Canvas(canvas, document, signatureRect).Add(paragraph);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION: {
                    if (signatureGraphic == null)
                    {
                        throw new InvalidOperationException();
                    }
                    /*MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")*/
                    float imgWidth = signatureGraphic.GetWidth();
                    if (imgWidth == 0)
                    {
                        imgWidth = signatureRect.GetWidth();
                    }
                    float imgHeight = signatureGraphic.GetHeight();
                    if (imgHeight == 0)
                    {
                        imgHeight = signatureRect.GetHeight();
                    }
                    float multiplierH = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier  = Math.Min(multiplierH, multiplierW);
                    imgWidth  *= multiplier;
                    imgHeight *= multiplier;
                    float x = signatureRect.GetRight() - imgWidth;
                    float y = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth, 0, 0, imgHeight, x, y);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC: {
                    float imgWidth_1 = signatureGraphic.GetWidth();
                    if (imgWidth_1 == 0)
                    {
                        imgWidth_1 = signatureRect.GetWidth();
                    }
                    float imgHeight_1 = signatureGraphic.GetHeight();
                    if (imgHeight_1 == 0)
                    {
                        imgHeight_1 = signatureRect.GetHeight();
                    }
                    float multiplierH_1 = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW_1 = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier_1  = Math.Min(multiplierH_1, multiplierW_1);
                    imgWidth_1  *= multiplier_1;
                    imgHeight_1 *= multiplier_1;
                    float x_1 = signatureRect.GetLeft() + (signatureRect.GetWidth() - imgWidth_1) / 2;
                    float y_1 = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight_1) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth_1, 0, 0, imgHeight_1, x_1, y_1);
                    break;
                }
                }
                if (renderingMode != PdfSignatureAppearance.RenderingMode.GRAPHIC)
                {
                    canvas = new PdfCanvas(n2, document);
                    Paragraph paragraph_1 = new Paragraph(text).SetFont(font).SetFontSize(layer2FontSize).SetMargin(0).SetMultipliedLeading
                                                (0.9f);
                    new iText.Layout.Canvas(canvas, document, dataRect).Add(paragraph_1);
                }
            }
            int       rotation = document.GetPage(page).GetRotation();
            Rectangle rotated  = new Rectangle(rect);

            if (topLayer == null)
            {
                topLayer = new PdfFormXObject(rotated);
                topLayer.MakeIndirect(document);
                float scale = Math.Min(rect.GetWidth(), rect.GetHeight()) * 0.9f;
                float x     = (rect.GetWidth() - scale) / 2;
                float y     = (rect.GetHeight() - scale) / 2;
                scale /= 100;
                canvas = new PdfCanvas(topLayer, document);
                if (rotation == 90)
                {
                    canvas.ConcatMatrix(0, 1, -1, 0, rect.GetHeight(), 0);
                }
                else
                {
                    if (rotation == 180)
                    {
                        canvas.ConcatMatrix(-1, 0, 0, -1, rect.GetWidth(), rect.GetHeight());
                    }
                    else
                    {
                        if (rotation == 270)
                        {
                            canvas.ConcatMatrix(0, -1, 1, 0, 0, rect.GetWidth());
                        }
                    }
                }
                if (reuseAppearance)
                {
                    PdfAcroForm    acroForm = PdfAcroForm.GetAcroForm(document, true);
                    PdfFormField   field    = acroForm.GetField(fieldName);
                    PdfStream      stream   = field.GetWidgets()[0].GetAppearanceDictionary().GetAsStream(PdfName.N);
                    PdfFormXObject xobj     = new PdfFormXObject(stream);
                    if (stream != null)
                    {
                        topLayer.GetResources().AddForm(xobj, new PdfName("n0"));
                        PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                        canvas1.AddXObject(xobj, 1, 0, 0, 1, 0, 0);
                    }
                    else
                    {
                        reuseAppearance = false;
                        if (n0 == null)
                        {
                            CreateBlankN0();
                        }
                    }
                }
                if (!reuseAppearance)
                {
                    topLayer.GetResources().AddForm(n0, new PdfName("n0"));
                    PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                    canvas1.AddXObject(n0, 1, 0, 0, 1, 0, 0);
                }
                topLayer.GetResources().AddForm(n2, new PdfName("n2"));
                PdfCanvas canvas1_1 = new PdfCanvas(topLayer, document);
                canvas1_1.AddXObject(n2, 1, 0, 0, 1, 0, 0);
            }
            PdfFormXObject napp = new PdfFormXObject(rotated);

            napp.MakeIndirect(document);
            napp.GetResources().AddForm(topLayer, new PdfName("FRM"));
            canvas = new PdfCanvas(napp, document);
            canvas.AddXObject(topLayer, 0, 0);
            return(napp);
        }
Beispiel #19
0
        public void FillU3DImageInAcroForm <T>(T detail)
        {
            IDictionary <String, PdfFormField> fields = _form.GetFormFields();

            Type type = detail.GetType();

            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                PdfFormField       toSet;
                PdfActionAttribute required = property.GetCustomAttribute <PdfActionAttribute>();
                if (fields.TryGetValue(property.Name, out toSet))
                {
                    var          value = property.GetValue(detail, null)?.ToString();
                    PdfFormField field = fields[property.Name];
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        var widgets = field.GetWidgets();
                        if (widgets == null || widgets.Count == 0)
                        {
                            throw new ArgumentNullException($"no widgets to the field");
                        }

                        PdfArray position = widgets.First().GetRectangle();

                        PdfPage page = field.GetWidgets().First().GetPage();
                        if (page == null)
                        {
                            throw new ArgumentNullException(
                                      $"field widget annotation is not associated with any page");
                        }
                        int   pageNum = _pdfDoc.GetPageNumber(page);
                        float width   = (float)(position.GetAsNumber(2).GetValue() -
                                                position.GetAsNumber(0).GetValue());
                        float height = (float)(position.GetAsNumber(3).GetValue() -
                                               position.GetAsNumber(1).GetValue());

                        var u3DInfo = new U3DInfo
                        {
                            Height  = height,
                            Width   = width,
                            X       = (float)position.GetAsNumber(0).GetValue(),
                            Y       = (float)position.GetAsNumber(1).GetValue(),
                            Page    = pageNum,
                            U3DFile = value
                        };
                        _u3DInfos.Add(u3DInfo);

                        _form.RemoveField(field.GetFieldName().ToString());
                    }
                    else
                    {
                        if (required != null)
                        {
                            if (required.Action.Equals(ActionFlag.Required))
                            {
                                throw new ArgumentNullException($"No {property.Name} image found");
                            }
                            if (required.Action.Equals(ActionFlag.Optional))
                            {
                                _form.RemoveField(field.GetFieldName().ToString());
                                continue;
                            }
                            if (required.Action.Equals(ActionFlag.NotAvailable))
                            {
                                toSet.SetValue("N/A").SetFontSizeAutoScale().SetReadOnly(true);
                            }
                        }
                    }
                }
            }

            // close the target pdf first:
            _pdfDoc?.Close();

            using (var helper = new U3DImageHelper(TargetFile))
            {
                foreach (var u3DInfo in _u3DInfos)
                {
                    helper.AddU3DImage(u3DInfo);
                }
            }

            // reopen the target pdf:
            _temporaryFile = Path.Combine(Path.GetDirectoryName(TargetFile), $"temp_{DateTime.Now.Ticks}.pdf");
            File.Move(TargetFile, _temporaryFile);
            Init(TargetFile, _temporaryFile);
        }
Beispiel #20
0
        private void VerticalJustificationInAcroForm <T>(PdfFormField field, T detail, string propertyName, PdfFont pdfFont, PdfFontAttribute pdfFontAttribute)
        {
            var widgets = field.GetWidgets();

            if (widgets == null || widgets.Count == 0)
            {
                throw new ArgumentNullException($"no widgets to the field");
            }

            PdfArray position = widgets.First().GetRectangle();

            PdfPage page = field.GetWidgets().First().GetPage();

            if (page == null)
            {
                throw new ArgumentNullException(
                          $"field widget annotation is not associated with any page");
            }
            int pageNum = _pdfDoc.GetPageNumber(page);

            float width  = (float)(position.GetAsNumber(2).GetValue() - position.GetAsNumber(0).GetValue());
            float height = (float)(position.GetAsNumber(3).GetValue() - position.GetAsNumber(1).GetValue());
            float llx    = (float)position.GetAsNumber(0).GetValue();
            float lly    = (float)position.GetAsNumber(1).GetValue();
            float urx    = (float)position.GetAsNumber(2).GetValue();
            float ury    = (float)position.GetAsNumber(3).GetValue();

            Rectangle rect = new Rectangle(llx, lly, width, height);

            PdfCanvas canvas = new PdfCanvas(_pdfDoc, pageNum);

            canvas.SetLineWidth(0f).Rectangle(rect);

            string textValue = null;
            Type   type      = detail.GetType();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.Name == propertyName)
                {
                    textValue = property.GetValue(detail, null).ToString();
                }
            }
            if (string.IsNullOrWhiteSpace(textValue))
            {
                return;
            }

            float verticalAdjustment = 0;
            var   text = new Text(textValue);

            if (pdfFont != null)
            {
                text.SetFont(pdfFont);
                text.SetFontColor(pdfFontAttribute.Color);
                if (pdfFontAttribute.Size != 0)
                {
                    text.SetFontSize(pdfFontAttribute.Size);
                }

                verticalAdjustment = (pdfFont.GetWidth(textValue, pdfFontAttribute.Size) / (urx - llx)) * pdfFont.GetAscent(textValue, pdfFontAttribute.Size);
            }

            Paragraph p = new Paragraph(text);

            if (pdfFontAttribute.Justification == PdfTextAlignment.CenterLeft ||
                pdfFontAttribute.Justification == PdfTextAlignment.BottomLeft)
            {
                p.SetTextAlignment(iText.Layout.Properties.TextAlignment.LEFT);
            }
            if (pdfFontAttribute.Justification == PdfTextAlignment.CenterMiddle ||
                pdfFontAttribute.Justification == PdfTextAlignment.BottomMiddle)
            {
                p.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
            }
            if (pdfFontAttribute.Justification == PdfTextAlignment.CenterRight ||
                pdfFontAttribute.Justification == PdfTextAlignment.BottomRight)
            {
                p.SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
            }

            // set line space
            p.SetMultipliedLeading(1);

            if (pdfFontAttribute.Justification == PdfTextAlignment.CenterLeft ||
                pdfFontAttribute.Justification == PdfTextAlignment.CenterMiddle ||
                pdfFontAttribute.Justification == PdfTextAlignment.CenterRight)
            {
                new Canvas(canvas, _pdfDoc, rect)
                .Add(p.SetFixedPosition(llx, (ury + lly) / 2 - verticalAdjustment, urx - llx));
            }

            if (pdfFontAttribute.Justification == PdfTextAlignment.BottomLeft ||
                pdfFontAttribute.Justification == PdfTextAlignment.BottomMiddle ||
                pdfFontAttribute.Justification == PdfTextAlignment.BottomRight)
            {
                new Canvas(canvas, _pdfDoc, rect).Add(p);
            }

            _form.RemoveField(field.GetFieldName().ToString());
        }
        public ActionResult <PdfScanResult> Get(string pdfCode)
        {
            if (string.IsNullOrEmpty(pdfCode))
            {
                return(BadRequest());
            }

            var templateFilePath = $"{pdfCode}.pdf";

            if (!string.IsNullOrEmpty(_pdfFilesOptions.TemplatePath))
            {
                templateFilePath = $"{_pdfFilesOptions.TemplatePath}{Path.DirectorySeparatorChar}{templateFilePath}";
            }

            if (!System.IO.File.Exists(templateFilePath))
            {
                return(NotFound());
            }

            using PdfReader reader = new PdfReader(templateFilePath);
            reader.SetUnethicalReading(true);
            using PdfDocument pdf = new PdfDocument(reader);

            var scanPages = new PdfScanPage[pdf.GetNumberOfPages()];
            var result    = new PdfScanResult {
                PdfCode = pdfCode,
                Pages   = new List <PdfScanPage>(pdf.GetNumberOfPages())
            };

            //PdfPage pdfPage = pdf.GetPage(1);
            //PdfFormXObject pdfPageCopy = pdfPage.CopyAsFormXObject(pdf);
            //Image pageImage = new Image(pdfPageCopy);
            //ImageData b = new ImageData();
            //PdfImageXObject a = new PdfImageXObject()

            var form   = PdfAcroForm.GetAcroForm(pdf, false);
            var fields = form.GetFormFields();

            foreach (string field in fields.Keys)
            {
                PdfFormField formField = form.GetField(field);
                if (formField.IsReadOnly())
                {
                    continue;
                }

                var pdfValue = formField.GetValue();
                if (formField.GetWidgets() == null)
                {
                    continue;
                }
                if (formField.GetWidgets().Count <= 0)
                {
                    continue;
                }

                bool isButton = (formField is PdfButtonFormField);
                bool isText   = (formField is PdfTextFormField);

                if (!isText && !isButton)
                {
                    continue;
                }

                var page       = formField.GetWidgets().First().GetPage();
                var pageNumber = pdf.GetPageNumber(page);

                PdfScanPage scanPage = scanPages[pageNumber - 1];
                if (scanPage == null)
                {
                    scanPage = new PdfScanPage {
                        Number     = pageNumber,
                        FormFields = new List <PdfScanFormField>()
                    };
                }

                double minLowerLeftX  = double.MaxValue;
                double minLowerLeftY  = double.MaxValue;
                double maxUpperRightX = 0;
                double maxUpperRightY = 0;
                foreach (var widget in formField.GetWidgets())
                {
                    var rectangle = widget.GetRectangle();
                    if (rectangle == null)
                    {
                        continue;
                    }
                    if (rectangle.Size() < 4)
                    {
                        continue;
                    }

                    // API links explanations:
                    //https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-find-absolute-position-and-dimension-field
                    //https://itextpdf.com/en/resources/faq/technical-support/itext-7/how-show-image-text-field-position
                    var lowerLeftX  = rectangle.GetAsNumber(0).GetValue(); //lower left position x
                    var lowerLeftY  = rectangle.GetAsNumber(1).GetValue(); //lower left position y
                    var upperRightX = rectangle.GetAsNumber(2).GetValue(); //upper right position x
                    var upperRightY = rectangle.GetAsNumber(3).GetValue(); //upper right position y

                    if (minLowerLeftX > lowerLeftX)
                    {
                        minLowerLeftX = lowerLeftX;
                    }
                    if (minLowerLeftY > lowerLeftY)
                    {
                        minLowerLeftY = lowerLeftY;
                    }

                    if (maxUpperRightX < upperRightX)
                    {
                        maxUpperRightX = upperRightX;
                    }
                    if (maxUpperRightY < upperRightY)
                    {
                        maxUpperRightY = upperRightY;
                    }
                }

                var scanFormField = new PdfScanFormField
                {
                    Name     = field,
                    Position = new Position
                    {
                        X = minLowerLeftX,
                        Y = minLowerLeftY
                    },
                    Size = new Size
                    {
                        Width  = maxUpperRightX - minLowerLeftX,
                        Height = maxUpperRightY - minLowerLeftY
                    }
                };

                scanPage.FormFields.Add(scanFormField);
                scanPages[pageNumber - 1] = scanPage;
            }

            result.Pages = scanPages.Where(sp => sp != null).ToList();
            return(Ok(result));
        }