Ejemplo n.º 1
0
        public virtual void AddFieldWithKidsTest()
        {
            PdfDocument  pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream()));
            PdfAcroForm  form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfFormField root   = PdfFormField.CreateEmptyField(pdfDoc);

            root.SetFieldName("root");
            PdfFormField child = PdfFormField.CreateEmptyField(pdfDoc);

            child.SetFieldName("child");
            root.AddKid(child);
            PdfTextFormField text1 = PdfFormField.CreateText(pdfDoc, new Rectangle(100, 700, 200, 20), "text1", "test"
                                                             );

            child.AddKid(text1);
            form.AddField(root);
            NUnit.Framework.Assert.AreEqual(3, form.GetFormFields().Count);
        }
Ejemplo n.º 2
0
        /// <exception cref="System.IO.IOException"/>
        private void AddCheckBox(PdfDocument pdfDoc, float fontSize, float yPos, float checkBoxW, PdfFormField checkBox
                                 )
        {
            PdfPage     page = pdfDoc.GetFirstPage();
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

            if (fontSize >= 0)
            {
                checkBox.SetFontSize(fontSize);
            }
            checkBox.SetBorderWidth(1);
            checkBox.SetBorderColor(ColorConstants.BLACK);
            form.AddField(checkBox, page);
            PdfCanvas canvas = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(50 + checkBoxW + 10, yPos).SetFontAndSize(PdfFontFactory.CreateFont
                                                                                                  (), 12).ShowText("okay?").EndText().RestoreState();
        }
Ejemplo n.º 3
0
        public virtual void RealFontSizeRegenerateAppearanceTest()
        {
            String      sourceFilename = sourceFolder + "defaultAppearanceRealFontSize.pdf";
            String      destFilename   = destinationFolder + "realFontSizeRegenerateAppearance.pdf";
            PdfDocument pdfDoc         = new PdfDocument(new PdfReader(sourceFilename), new PdfWriter(destFilename));
            PdfAcroForm form           = PdfAcroForm.GetAcroForm(pdfDoc, true);

            form.GetField("fieldName").RegenerateField();
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(destFilename, sourceFolder + "cmp_realFontSizeRegenerateAppearance.pdf"
                                                                    , destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Ejemplo n.º 4
0
        public virtual void ButtonFieldTest02()
        {
            String      filename = destinationFolder + "buttonFieldTest02.pdf";
            PdfDocument pdfDoc   = new PdfDocument(new PdfReader(sourceFolder + "buttonFieldTest02_input.pdf"), new PdfWriter
                                                       (filename));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

            ((PdfButtonFormField)form.GetField("push")).SetImage(sourceFolder + "Desert.jpg");
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(filename, sourceFolder + "cmp_buttonFieldTest02.pdf", destinationFolder
                                                                    , "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Ejemplo n.º 5
0
        public virtual void SetGenerateAppearanceTest()
        {
            PdfDocument outputDoc = CreateDocument();
            PdfAcroForm acroForm  = PdfAcroForm.GetAcroForm(outputDoc, true);

            acroForm.SetNeedAppearances(false);
            acroForm.SetGenerateAppearance(true);
            bool   isModified           = acroForm.GetPdfObject().IsModified();
            bool   isReleaseForbidden   = acroForm.GetPdfObject().IsReleaseForbidden();
            bool   isGenerateAppearance = acroForm.IsGenerateAppearance();
            Object needAppearances      = acroForm.GetPdfObject().Get(PdfName.NeedAppearances);

            outputDoc.Close();
            NUnit.Framework.Assert.IsNull(needAppearances);
            NUnit.Framework.Assert.IsTrue(isGenerateAppearance);
            NUnit.Framework.Assert.IsTrue(isModified);
            NUnit.Framework.Assert.IsTrue(isReleaseForbidden);
        }
Ejemplo n.º 6
0
        public virtual void SetNeedAppearancesInPdf2Test()
        {
            PdfDocument outputDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream(), new WriterProperties().
                                                                  SetPdfVersion(PdfVersion.PDF_2_0)));

            outputDoc.AddNewPage();
            PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(outputDoc, true);

            acroForm.SetNeedAppearances(false);
            bool      isModified         = acroForm.GetPdfObject().IsModified();
            bool      isReleaseForbidden = acroForm.GetPdfObject().IsReleaseForbidden();
            PdfObject needAppearance     = acroForm.GetPdfObject().Get(PdfName.NeedAppearances);

            outputDoc.Close();
            NUnit.Framework.Assert.IsNull(needAppearance);
            NUnit.Framework.Assert.IsTrue(isModified);
            NUnit.Framework.Assert.IsTrue(isReleaseForbidden);
        }
Ejemplo n.º 7
0
        private static void PDFContentSearch(string[] files, Dictionary <string, string> dictionary, string source, string target, string projectPath, string backup)
        {
            foreach (String file in files)
            {
                Dictionary <String, String> dic = new Dictionary <String, string>();
                String newFilePath      = file.Replace(projectPath, "");
                String newDirectoryName = System.IO.Path.GetDirectoryName(newFilePath);
                if (!Directory.Exists(backup + newDirectoryName) && !newDirectoryName.Equals("\\"))
                {
                    Directory.CreateDirectory(backup + newDirectoryName);
                }
                String targetPath = backup + newFilePath;
                try
                {
                    System.IO.File.Copy(file, targetPath, true);
                    iText.Kernel.Pdf.PdfReader pdfReader = new PdfReader(file);
                    PdfWriter   pdfWriter   = new PdfWriter(targetPath);
                    PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);
                    PdfAcroForm pdfAcroForm = PdfAcroForm.GetAcroForm(pdfDocument, false);
                    IDictionary <String, PdfFormField> field = pdfAcroForm.GetFormFields();
                    foreach (String key in pdfAcroForm.GetFormFields().Keys)
                    {
                        if (key.Contains("DOB") || key.Contains("Date"))
                        {
                            if (!key.EndsWith(target))
                            {
                                dic.Add(key, key + target);
                            }
                        }
                    }
                    foreach (String field1 in dic.Keys)
                    {
                        pdfAcroForm.RenameField(field1, dic[field1]);
                    }

                    pdfDocument.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception occurred :" + ex);
                    continue;
                }
            }
        }
Ejemplo n.º 8
0
        public FileContentResult CostShareAgreementPdf(ProjectPersonPrimaryKey projectPersonPrimaryKey)
        {
            string blankCostSharePdfFilePath = BlankCostSharePdfFilePath();

            byte[] binaryContentsOfOutputPdfFile;
            string outputFileName;

            ProjectPerson landownerProjectPerson = projectPersonPrimaryKey.EntityObject;
            Person        landownerPerson        = landownerProjectPerson.Person;

            Check.Ensure(landownerProjectPerson.ProjectPersonRelationshipType == ProjectPersonRelationshipType.PrivateLandowner, $"Only expecting Landowner contacts here. {landownerProjectPerson.Person.FullNameFirstLast} is a {landownerProjectPerson.ProjectPersonRelationshipType} on Project {landownerProjectPerson.Project.DisplayName}.");

            using (var outputPdfFile = DisposableTempFile.MakeDisposableTempFileEndingIn(".pdf"))
            {
                PdfDocument pdf  = new PdfDocument(new PdfReader(blankCostSharePdfFilePath), new PdfWriter(outputPdfFile.FileInfo.FullName));
                PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
                IDictionary <String, PdfFormField> fields = form.GetFormFields();

                var landownerName = landownerPerson.FullNameFirstLast;
                outputFileName = $"CostShareAgreement-{landownerName.Replace(" ", "")}.pdf";

                fields.TryGetValue("Names", out var nameToSet);
                nameToSet?.SetValue(MakeEmptyStringForNullString(landownerName));

                fields.TryGetValue("Address1", out var address1);
                address1?.SetValue(MakeEmptyStringForNullString(landownerPerson.PersonAddress));

                fields.TryGetValue("Address2", out var address2);
                address2?.SetValue(MakeEmptyStringForNullString(string.Empty));

                fields.TryGetValue("PhoneNumber", out var phoneToSet);
                phoneToSet?.SetValue(MakeEmptyStringForNullString(landownerPerson.Phone));

                fields.TryGetValue("Email", out var emailToSet);
                emailToSet?.SetValue(MakeEmptyStringForNullString(landownerPerson.Email));

                form.FlattenFields();
                pdf.Close();

                binaryContentsOfOutputPdfFile = System.IO.File.ReadAllBytes(outputPdfFile.FileInfo.FullName);
            }

            return(File(binaryContentsOfOutputPdfFile, "application/pdf", outputFileName));
        }
Ejemplo n.º 9
0
        public static void FillOutPDF(string inputFile, string outputFile, Dictionary <String, String> inputFields)
        {
            PdfReader   reader = new PdfReader(inputFile);
            PdfWriter   writer = new PdfWriter(outputFile);
            PdfDocument pdfDoc = new PdfDocument(reader, writer);
            var         form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            var         fields = form.GetFormFields();

            foreach (var field in fields)
            {
                //Console.WriteLine(field.Key);
            }
            foreach (var keyValuePair in inputFields)
            {
                fields[keyValuePair.Key].SetValue(keyValuePair.Value);
            }
            form.FlattenFields();
            pdfDoc.Close();
        }
Ejemplo n.º 10
0
        public virtual void LongOptionWrappedIntoTwoLinesTest()
        {
            // TODO DEVSIX-4480 iText wraps the text into more than one line when generating listbox appearance
            String      outFileName = destinationFolder + "longOptionWrappedIntoTwoLinesTest.pdf";
            String      cmpFileName = sourceFolder + "cmp_longOptionWrappedIntoTwoLinesTest.pdf";
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));
            PdfAcroForm form        = PdfAcroForm.GetAcroForm(pdfDocument, true);
            String      shortOption = "Short option";
            String      longOption  = "Long long long long long long long option";

            String[]           options = new String[] { shortOption, longOption };
            Rectangle          rect    = new Rectangle(50, 650, 100, 100);
            PdfChoiceFormField choice  = PdfFormField.CreateList(pdfDocument, rect, "List", "Short option", options);

            form.AddField(choice);
            pdfDocument.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder
                                                                             ));
        }
Ejemplo n.º 11
0
        public virtual void CustomizedRadiobuttonFieldTest()
        {
            String             file     = "customizedRadiobuttonFieldTest.pdf";
            String             filename = destinationFolder + file;
            PdfDocument        pdfDoc   = new PdfDocument(new PdfWriter(filename));
            PdfAcroForm        form     = PdfAcroForm.GetAcroForm(pdfDoc, true);
            Rectangle          rect1    = new Rectangle(36, 700, 20, 20);
            Rectangle          rect2    = new Rectangle(36, 680, 20, 20);
            PdfButtonFormField group2   = PdfFormField.CreateRadioGroup(pdfDoc, "TestGroup2", "1");

            PdfFormField.CreateRadioButton(pdfDoc, rect1, group2, "1").SetBorderWidth(2).SetBorderColor(ColorConstants
                                                                                                        .RED).SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetVisibility(PdfFormField.VISIBLE);
            PdfFormField.CreateRadioButton(pdfDoc, rect2, group2, "2").SetBorderWidth(2).SetBorderColor(ColorConstants
                                                                                                        .RED).SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetVisibility(PdfFormField.VISIBLE);
            form.AddField(group2);
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(filename, sourceFolder + "cmp_" + file, destinationFolder
                                                                             , "diff_"));
        }
Ejemplo n.º 12
0
        public virtual void FormFieldTest02()
        {
            String           filename = destinationFolder + "formFieldTest02.pdf";
            PdfDocument      pdfDoc   = new PdfDocument(new PdfWriter(filename));
            PdfAcroForm      form     = PdfAcroForm.GetAcroForm(pdfDoc, true);
            Rectangle        rect     = new Rectangle(210, 490, 150, 22);
            PdfTextFormField field    = PdfFormField.CreateText(pdfDoc, rect, "fieldName", "some value");

            form.AddField(field);
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(filename, sourceFolder + "cmp_formFieldTest02.pdf", destinationFolder
                                                                    , "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Ejemplo n.º 13
0
        public virtual void CheckBoxToggleTest02()
        {
            String       srcPdf   = sourceFolder + "checkBoxToggledOn.pdf";
            String       outPdf   = destinationFolder + "checkBoxToggleTest02.pdf";
            String       cmpPdf   = sourceFolder + "cmp_checkBoxToggleTest02.pdf";
            PdfDocument  pdfDoc   = new PdfDocument(new PdfReader(srcPdf), new PdfWriter(outPdf));
            PdfAcroForm  form     = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfFormField checkBox = form.GetField("cb_fs_6_7_7");

            checkBox.SetValue("Off", false);
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
        private void GeneratePDF(IDictionary <string, string> mappingWithActuals, PdfWriter pdfWriter)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(TemplateForm), pdfWriter);
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            IDictionary <string, PdfFormField> fields = form.GetFormFields();
            PdfFormField toSet;

            foreach (var item in mappingWithActuals)
            {
                var success = fields.TryGetValue(item.Key, out toSet);
                if (success)
                {
                    {
                        toSet.SetValue(item.Value);
                    }
                }
            }
            pdfDoc.Close();
        }
Ejemplo n.º 15
0
        private string FillAndSavePdf(UserDraft userDraft, InstructionDraft instructionDraft, string instructionPath)
        {
            try
            {
                using var reader = new PdfReader(_templateFilePath);
                using var writer = new PdfWriter(instructionPath);
                using var pdf    = new PdfDocument(reader, writer);

                var form = PdfAcroForm.GetAcroForm(pdf, true);
                var doc  = new Document(pdf);

                form.SetGenerateAppearance(true);

                form.GetField("deviceName").SetValue(instructionDraft.Device.Name);
                form.GetField("deviceChief").SetValue(instructionDraft.Device.Chief?.FullName ?? string.Empty);
                form.GetField("onlyFor").SetValue(instructionDraft.OnlyFor ?? string.Empty);
                form.GetField("notFor").SetValue(instructionDraft.ExceptFor ?? string.Empty);
                form.GetField("instructor").SetValue(instructionDraft.Instructor.FullName);
                form.GetField("instructed").SetValue(userDraft.FullName);
                form.GetField("instructionDate").SetValue(DateTime.Today.ToString("d", CultureInfo.CurrentCulture));

                //var signatureImage = PositionImage(form, "instructorSignature", instructionDraft.Instructor.Signature);
                //var instructedImage = PositionImage(form, "instructedSignature", userDraft.Signature);

                //doc.Add(signatureImage);
                //doc.Add(instructedImage);
                form.RemoveField("instructorSignature");
                form.RemoveField("instructedSignature");
                doc.Close();
                pdf.Close();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Instruction pdf could not be filled or saved.");
                if (File.Exists(instructionPath))
                {
                    File.Delete(instructionPath);
                }
                return(null);
            }

            return(instructionPath);
        }
Ejemplo n.º 16
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();
        }
Ejemplo n.º 17
0
        /// <exception cref="System.IO.IOException"/>
        public virtual void CreatePdf(String dest)
        {
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

            pdf.SetDefaultPageSize(PageSize.A4);
            Document doc = new Document(pdf);

            Paragraph title = new Paragraph("Application for employment").SetTextAlignment(TextAlignment.CENTER).SetFontSize(16);

            doc.Add(title);

            PdfAcroForm      form      = PdfAcroForm.GetAcroForm(doc.GetPdfDocument(), true);
            PdfTextFormField nameField = PdfTextFormField.CreateText(doc.GetPdfDocument(), new Rectangle(99, 753, 425, 15), "name", "");

            nameField.SetRequired(true);
            form.AddField(nameField);

            doc.Close();
        }
Ejemplo n.º 18
0
        public virtual void CreatePDF(String dest)
        {
            // Create a pdf document along with a Document (default root layout element) instance
            PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest));
            Document    document    = new Document(pdfDocument);

            PdfAcroForm form = PdfAcroForm.GetAcroForm(document.GetPdfDocument(), true);

            PdfFont font = PdfFontFactory.CreateFont(FONTS_FOLDER + "NotoSansBengali-Regular.ttf",
                                                     PdfEncodings.IDENTITY_H);

            // Embed entire font without any subsetting. Please note that without subset it's impossible to edit a form field
            // with the predefined font
            font.SetSubset(false);

            // সুরে মিললে সুর হবে
            String line1 =
                "\u09B8\u09C1\u09B0\u09C7\u0020\u09AE\u09BF\u09B2\u09B2\u09C7\u0020\u09B8\u09C1\u09B0\u0020\u09B9"
                + "\u09AC\u09C7";

            // সুরে
            String line2 = "\u09B8\u09C1\u09B0\u09C7";

            // িললে
            String line3 = "\u09AE\u09BF\u09B2\u09B2\u09C7";

            // Initialize the array with 3 lines of text. These lines will be used as combo box options
            String[] comboText = new String[] { line1, line2, line3 };

            // Create a form field and apply the properties on it
            PdfFormField formField = PdfTextFormField.CreateComboBox(document.GetPdfDocument(),
                                                                     new Rectangle(50, 750, 150, 15), "test", line1, comboText);

            formField
            .SetBorderWidth(1)
            .SetJustification(1)
            .SetFont(font)
            .SetFontSizeAutoScale();

            form.AddField(formField);

            document.Close();
        }
Ejemplo n.º 19
0
        public virtual void PdfA1DocWithPdfA1ButtonFieldTest()
        {
            String name     = "pdfA1DocWithPdfA1ButtonField";
            String fileName = destinationFolder + name + ".pdf";
            String cmp      = sourceFolder + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ButtonField.pdf";
            Stream @is      = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B;
            PdfADocument         pdfDoc           = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom"
                                                                                                                                    , "", "http://www.color.org", "sRGB IEC61966-2.1", @is));
            PdfAcroForm  form       = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfFormField emptyField = PdfFormField.CreateEmptyField(pdfDoc, conformanceLevel).SetFieldName("empty");

            emptyField.AddKid(PdfFormField.CreateButton(pdfDoc, new Rectangle(36, 756, 20, 20), PdfAnnotation.PRINT, conformanceLevel
                                                        ).SetFieldName("button").SetValue("hello"));
            form.AddField(emptyField);
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(fileName, cmp, destinationFolder));
            NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(fileName));
        }
Ejemplo n.º 20
0
        public virtual void PdfA1DocWithPdfA1ComboBoxFieldTest()
        {
            String  name     = "pdfA1DocWithPdfA1ComboBoxField";
            String  fileName = destinationFolder + name + ".pdf";
            String  cmp      = sourceFolder + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ComboBoxField.pdf";
            PdfFont fontCJK  = PdfFontFactory.CreateFont(sourceFolder + "NotoSansCJKtc-Light.otf", PdfEncodings.IDENTITY_H
                                                         , true);
            Stream @is = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read);
            PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B;
            PdfADocument         pdfDoc           = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom"
                                                                                                                                    , "", "http://www.color.org", "sRGB IEC61966-2.1", @is));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

            form.AddField(PdfFormField.CreateComboBox(pdfDoc, new Rectangle(156, 616, 70, 70), "combo", "用", new String
                                                      [] { "用", "规", "表" }, fontCJK, conformanceLevel));
            pdfDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(fileName, cmp, destinationFolder));
            NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(fileName));
        }
        public virtual void FormFlatteningTest01()
        {
            String      srcFilename = sourceFolder + "formFlatteningSource.pdf";
            String      filename    = destinationFolder + "formFlatteningTest01.pdf";
            PdfDocument doc         = new PdfDocument(new PdfReader(new FileStream(srcFilename, FileMode.Open, FileAccess.Read
                                                                                   )), new PdfWriter(new FileStream(filename, FileMode.Create)));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true);

            form.FlattenFields();
            doc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(filename, sourceFolder + "cmp_formFlatteningTest01.pdf"
                                                                    , destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Ejemplo n.º 22
0
        public void ManipulatePdf(
            String DEST,
            String USERNAME,
            String COMMENT)
        {
            // If pdf is locked or you dont know the password use below commented lines
            //PdfReader reader = new PdfReader(PDFSRC).SetUnethicalReading(true);
            //PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest));

            PdfDocument pdfDoc = new PdfDocument(new PdfReader(PDFSRC), new PdfWriter(DEST));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);

            form.GetField("userid").SetValue("  " + USERNAME);
            form.GetField("reqdate").SetValue("20201015");
            // form.GetField("justify").SetValue(COMMENT);
            form.GetField("optinfo").SetValue(COMMENT);

            pdfDoc.Close();
        }
Ejemplo n.º 23
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

            PdfFormField personal = PdfFormField.CreateEmptyField(pdfDoc);

            personal.SetFieldName("personal");
            PdfTextFormField name = PdfFormField.CreateText(pdfDoc,
                                                            new Rectangle(36, 760, 108, 30), "name", "");

            personal.AddKid(name);
            PdfTextFormField password = PdfFormField.CreateText(pdfDoc,
                                                                new Rectangle(150, 760, 300, 30), "password", "");

            personal.AddKid(password);
            PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(personal, pdfDoc.GetFirstPage());

            pdfDoc.Close();
        }
Ejemplo n.º 24
0
        internal static void ValidateTemplateForSignedDeferredResult(String output, String sigFieldName, PdfName filter
                                                                     , PdfName subFilter, int estimatedSize)
        {
            PdfDocument outDocument   = new PdfDocument(new PdfReader(output));
            PdfObject   outSigDictObj = PdfAcroForm.GetAcroForm(outDocument, false).GetField(sigFieldName).GetValue();

            NUnit.Framework.Assert.IsTrue(outSigDictObj.IsDictionary());
            PdfDictionary outSigDict = (PdfDictionary)outSigDictObj;
            PdfArray      byteRange  = outSigDict.GetAsArray(PdfName.ByteRange);

            NUnit.Framework.Assert.IsNotNull(byteRange);
            NUnit.Framework.Assert.IsTrue(byteRange.Size() == 4);
            NUnit.Framework.Assert.AreEqual(filter, outSigDict.GetAsName(PdfName.Filter));
            NUnit.Framework.Assert.AreEqual(subFilter, outSigDict.GetAsName(PdfName.SubFilter));
            PdfString outSigContents = outSigDict.GetAsString(PdfName.Contents);

            NUnit.Framework.Assert.IsTrue(outSigContents.IsHexWriting());
            NUnit.Framework.Assert.AreEqual(new byte[estimatedSize], outSigContents.GetValueBytes());
        }
Ejemplo n.º 25
0
        public virtual void FormFieldTaggingTest07()
        {
            String      outFileName = destinationFolder + "taggedPdfWithForms07.pdf";
            String      cmpFileName = sourceFolder + "cmp_taggedPdfWithForms07.pdf";
            PdfWriter   writer      = new PdfWriter(outFileName);
            PdfReader   reader      = new PdfReader(sourceFolder + "taggedDocWithFields.pdf");
            PdfDocument pdfDoc      = new PdfDocument(reader, writer);
            // Original document is already tagged, so there is no need to mark it as tagged again
            //        pdfDoc.setTagged();
            PdfAcroForm        acroForm   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfButtonFormField pushButton = PdfFormField.CreatePushButton(pdfDoc, new Rectangle(36, 650, 40, 20), "push"
                                                                          , "Capcha");
            TagTreePointer tagPointer = pdfDoc.GetTagStructureContext().GetAutoTaggingPointer();

            tagPointer.MoveToKid(PdfName.Div);
            acroForm.AddField(pushButton);
            pdfDoc.Close();
            CompareOutput(outFileName, cmpFileName);
        }
Ejemplo n.º 26
0
        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)
            {
                return;
            }
            //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);
            IDictionary <String, PdfFormField> fieldsFrom = formFrom.GetFormFields();

            if (fieldsFrom.Count <= 0)
            {
                return;
            }
            IDictionary <String, PdfFormField> fieldsTo = formTo.GetFormFields();
            IList <PdfAnnotation> annots = toPage.GetAnnotations();

            foreach (PdfAnnotation annot in annots)
            {
                if (!annot.GetSubtype().Equals(PdfName.Widget))
                {
                    continue;
                }
                CopyField(toPage, fieldsFrom, fieldsTo, annot);
            }
        }
Ejemplo n.º 27
0
        public virtual void CopyFieldsTest13()
        {
            String            srcFilename       = sourceFolder + "copyFields13.pdf";
            String            destFilename      = destinationFolder + "copyFields13.pdf";
            PdfDocument       srcDoc            = new PdfDocument(new PdfReader(srcFilename));
            PdfDocument       destDoc           = new PdfDocument(new PdfWriter(destFilename));
            PdfPageFormCopier pdfPageFormCopier = new PdfPageFormCopier();

            for (int i = 0; i < 1; ++i)
            {
                srcDoc.CopyPagesTo(1, 1, destDoc, pdfPageFormCopier);
            }
            PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(destDoc, false);

            acroForm.GetField("text").SetValue("Text!");
            destDoc.Close();
            srcDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destFilename, sourceFolder + "cmp_copyFields13.pdf"
                                                                             , destinationFolder, "diff_"));
        }
Ejemplo n.º 28
0
        private static void FixFieldNamesPDF(string pdf)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdf), new PdfWriter(@"output\3100_new.pdf"));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            var         fields = form.GetFormFields();
            var         lines  = fields.Select(kvp => kvp.Key); //Grab PDF Fields from document

            //int count = 0;
            foreach (var l in lines)  //Iterate through the fields to build the set value map
            {
                //Console.WriteLine($"public string {l.Replace(" ",string.Empty).Replace(".",string.Empty)} {{ get; set; }}");
                if (l.Contains("Year", StringComparison.OrdinalIgnoreCase))
                {
                    //form.GetFormFields().Put($"EffectiveDate{count}", f);
                    //fields[l].SetFieldName($"EffectiveDate{count}");
                    //count++;
                }
            }
            pdfDoc.Close();
        }
Ejemplo n.º 29
0
        public virtual void AutoScaleFontSizeInFormFields()
        {
            String       outPdf = destinationFolder + "autoScaleFontSizeInFormFields.pdf";
            String       cmpPdf = sourceFolder + "cmp_autoScaleFontSizeInFormFields.pdf";
            PdfWriter    writer = new PdfWriter(outPdf);
            PdfDocument  pdfDoc = new PdfDocument(writer);
            PdfAcroForm  form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            PdfFormField field  = PdfFormField.CreateText(pdfDoc, new Rectangle(36, 786, 80, 20), "name", "TestValueAndALittleMore"
                                                          );

            form.AddField(field.SetFontSizeAutoScale());
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Ejemplo n.º 30
0
        public IEnumerable <PdfFormField> GetFields(int id)
        {
            List <PdfFormField> fields = new List <PdfFormField>();

            using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(GetFilePath())))
            {
                PdfAcroForm pdfForm = PdfAcroForm.GetAcroForm(pdfDoc, false);

                foreach (var de in pdfForm.GetFormFields())
                {
                    var formField = de.Value;
                    fields.Add(new PdfFormField()
                    {
                        Name = de.Key, Value = formField.GetValueAsString()
                    });
                }
            }

            return(fields);
        }