Exemplo n.º 1
0
        private static void ReadPDF(string pathToPDF)
        {
            // Read files in the choosen folder

            foreach (string file in Directory.EnumerateFiles(pdfFolderPath, "*.pdf"))
            {
                /*
                 * Read each pdf file in the folder
                 * Open the file
                 * Read all the fields with key
                 * Step 1: Read and Write File information
                 * Step 2: Read and write complexity
                 *
                 */
                PdfReader   pdfReader = new PdfReader(file);
                PdfDocument pdfDoc    = new PdfDocument(pdfReader);
                PdfAcroForm form      = PdfAcroForm.GetAcroForm(pdfDoc, true);

                var fields = form.GetFormFields();

                var output = "";
                foreach (var field in fields)
                {
                    output += $"{field.Key} - {field.Value.GetValue()}\n";
                }
                Console.WriteLine(output);
                pdfDoc.Close();

                // Write to excel
                WriteToExcel(null);
            }
        }
Exemplo n.º 2
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc);

            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
            IDictionary <String, PdfFormField> fields = form.GetFormFields();

            fields["Name"].SetValue("Jeniffer");
            fields["Company"].SetValue("iText's next customer");
            fields["Country"].SetValue("No Man's Land");
            form.FlattenFields();

            Table table = new Table(UnitValue.CreatePercentArray(new float[] { 1, 15 }));

            table.SetWidth(UnitValue.CreatePercentValue(80));
            table.AddHeaderCell("#");
            table.AddHeaderCell("description");
            for (int i = 1; i <= 150; i++)
            {
                table.AddCell(i.ToString());
                table.AddCell("test " + i);
            }

            // The custom renderer decreases the first page's area.
            // As a result, there is not overlapping between the table from acroform and the new one.
            doc.SetRenderer(new ExtraTableRenderer(doc));
            doc.Add(table);

            doc.Close();
        }
Exemplo n.º 3
0
        private byte[] fillFormFieldsInRow <T>(T rec)
        {
            //string logSnippet = "[PdfGenerator][fillFormFieldsInRow] => ";

            using (var memoryStream = new MemoryStream())
            {
                PdfReader pdfReader = new PdfReader(_pdfTemplateFileName,
                                                    new ReaderProperties().SetPassword(Encoding.ASCII.GetBytes(_password))); //Iput
                PdfWriter   pdfWriter = new PdfWriter(memoryStream);
                PdfDocument pdfDoc    = new PdfDocument(pdfReader, pdfWriter);
                PdfAcroForm pdfForm   = PdfAcroForm.GetAcroForm(pdfDoc, true);
                IDictionary <string, PdfFormField> pdfFormFields = pdfForm.GetFormFields();

                PropertyInfo[] properties = (PropertyInfo[])typeof(T).GetProperties()
                                            .Where(x => x.GetCustomAttributes(typeof(PdfFieldAttribute), true).Any());

                foreach (var prop in properties)
                {
                    var attribute = prop.GetCustomAttribute <PdfFieldAttribute>();

                    if (!pdfFormFields.TryGetValue(attribute.FieldName, out var pdfField))
                    {
                        continue;
                    }
                    pdfField.SetValue(prop.GetValue(rec)?.ToString() ?? String.Empty);
                }
                pdfForm.FlattenFields();
                pdfDoc.Close();
                return(memoryStream.ToArray());
            }
        }
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDocument = InitializeDocument(dest, SRC);

            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, false);

            // Here we handle radio buttons and checkboxes (Button fields type) but there are also other field types
            // which can be used as well, for example they are Text fields, Choice fields, Signature fields
            foreach (PdfFormField field in form.GetFormFields().Values)
            {
                if (field.GetFieldFlag(PdfButtonFormField.FF_RADIO))
                {
                    AddAttributes("rb", field, pdfDocument);
                }
                else
                {
                    // Checkbox existence should be checked by verifying if its field type is Btn and that a Push button
                    // and Radio flags are both clear
                    if (field.GetFormType().Equals(PdfName.Btn) && ((!field.GetFieldFlag(PdfButtonFormField.FF_RADIO)) && (!field
                                                                                                                           .GetFieldFlag(PdfButtonFormField.FF_PUSH_BUTTON))))
                    {
                        AddAttributes("cb", field, pdfDocument);
                    }
                }
            }

            form.FlattenFields();

            pdfDocument.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            // Initialize document
            Document    doc  = new Document(pdf);
            PdfAcroForm form = C04E02_JobApplication.AddAcroForm(doc);
            IDictionary <String, PdfFormField> fields = form.GetFormFields();
            PdfFormField toSet;

            fields.TryGetValue("name", out toSet);
            toSet.SetValue("James Bond");
            fields.TryGetValue("language", out toSet);
            toSet.SetValue("English");
            fields.TryGetValue("experience1", out toSet);
            toSet.SetValue("Off");
            fields.TryGetValue("experience2", out toSet);
            toSet.SetValue("Yes");
            fields.TryGetValue("experience3", out toSet);
            toSet.SetValue("Yes");
            fields.TryGetValue("shift", out toSet);
            toSet.SetValue("Any");
            fields.TryGetValue("info", out toSet);
            toSet.SetValue("I was 38 years old when I became an MI6 agent.");
            doc.Close();
        }
Exemplo n.º 6
0
        public static void getPdfAcroFormFields(string input_file_path, string output_file_path)
        {
            //string src = @"C:\Users\timit\Source\Repos\tttimit\pdf_csharp\Pdf\1022.pdf";
            //string dest = @"C:\Users\timit\Source\Repos\tttimit\pdf_csharp\Pdf\Pdfout-1.pdf";

            PdfReader reader = new PdfReader(input_file_path);

            reader.SetUnethicalReading(true);
            PdfWriter   writer = new PdfWriter(output_file_path);
            PdfDocument pdfDoc = new PdfDocument(reader, writer);
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);

            IDictionary <string, PdfFormField> fields = form.GetFormFields();//这样获取的是没有顺序的数据

            string[] relationsCheckBox = { "ap.marital nev mar", "ap.marital div", "ap.marital sep", "ap.marital def", "ap.marital wid", "ap.marital eng", "ap.marital mar" };
            String[] toggleBtn         = { "ap.app", "ap.com dimia" };
            foreach (var key in fields.Keys)
            {
                PdfFormField value;
                if (fields.TryGetValue(key, out value))
                {
                    //Console.WriteLine("{0}={1}", key, value.GetValueAsString());
                    Console.WriteLine("{0}={1}", key, value);
                    //String[] states = fields[key].getAppearanceStates("checkbox");
                    //Console.WriteLine("value type {}", states);
                }
                else
                {
                    Console.WriteLine("{0} without value", key);
                }
            }
            //form.FlattenFields();
            pdfDoc.Close();
        }
Exemplo n.º 7
0
        public virtual byte[] CreatePartiallyFlattenedForm()
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream();
            PdfDocument           pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
            Document    doc  = new Document(pdfDoc);
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false);

            IDictionary <String, PdfFormField> fields = form.GetFormFields();

            fields["sunday_1"].SetValue("1");
            fields["sunday_2"].SetValue("2");
            fields["sunday_3"].SetValue("3");
            fields["sunday_4"].SetValue("4");
            fields["sunday_5"].SetValue("5");
            fields["sunday_6"].SetValue("6");

            // Add the fields, identified by name, to the list of fields to be flattened
            form.PartialFormFlattening("sunday_1");
            form.PartialFormFlattening("sunday_2");
            form.PartialFormFlattening("sunday_3");
            form.PartialFormFlattening("sunday_4");
            form.PartialFormFlattening("sunday_5");
            form.PartialFormFlattening("sunday_6");

            // Only the included above fields are flattened.
            // If no fields have been explicitly included, then all fields are flattened.
            form.FlattenFields();

            doc.Close();

            return(baos.ToArray());
        }
Exemplo n.º 8
0
        public static IDictionary <string, PdfFormField> DiscoverPDFFields(string pdf)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdf));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);

            return(form.GetFormFields());
        }
Exemplo n.º 9
0
        // Set pdf form value, and save as a new pdf.
        // Important: It is only for this project.
        // A better way is using Dictionary to modify multiple form fields
        public void SetFieldValue(string fieldkey, string fieldvalue, string newpdfname)
        {
            // Get pdf reader from current pdf
            // and init a new pdf writer
            PdfReader inputReader = new PdfReader(inputPdfFile);
            var       outfile     = newpdfname;
            var       writer      = new PdfWriter(outfile);
            var       indoc       = new PdfDocument(inputReader, writer);

            // Get form fields
            PdfAcroForm form    = PdfAcroForm.GetAcroForm(indoc, false);
            var         fields1 = form.GetFormFields();

            // Set Value by key name
            if (fields1.Keys.Contains(fieldkey))
            {
                fields1[fieldkey].SetValue(fieldvalue, true);
            }
            else
            {
                throw new NullReferenceException("Wrong field key name");
            }
            indoc.Close();
            writer.Close();
        }
Exemplo n.º 10
0
        // Get fields key/type/currentvalue from current pdf and return a dict
        public List <Dictionary <string, object> > GetFieldsInfo()
        {
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(this.GetPdfDocument(), false);
            var         fields = form.GetFormFields();
            var         ret    = new List <Dictionary <string, object> >();

            foreach (var fkey in fields.Keys)
            {
                var field = fields[fkey];
                if (field.GetFormType() != null)
                {
                    var insDic = new Dictionary <string, object> {
                        { "key", fkey.Replace(' ', '.') },
                        { "pdfformkey", fkey },
                        { "formtype", field.GetFormType().ToString() },
                        { "type", field.GetType().ToString() },
                        { "defaultvalue", field.GetValue() == null?null:field.GetValueAsString() },
                        { "rule", "string" },
                    };
                    var state = field.GetAppearanceStates();
                    //field.GetPdfObject().GetAsString(PdfName.DA);
                    if (state.Length > 0)
                    {
                        insDic.Add("state", string.Join(',', state));
                    }
                    ret.Add(insDic);
                }
            }
            return(ret);
        }
        public virtual void CreatePdf(String dest1, String dest2)
        {
            PdfDocument destPdfDocument = new PdfDocument(new PdfWriter(dest1));
            //Smart mode
            PdfDocument destPdfDocumentSmartMode = new PdfDocument(new PdfWriter(dest2).SetSmartMode(true));

            using (StreamReader sr = File.OpenText(DATA))
            {
                String line;
                bool   headerLine = true;
                int    i          = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    if (headerLine)
                    {
                        headerLine = false;
                        continue;
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PdfDocument           sourcePdfDocument = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    //Read fields
                    PdfAcroForm     form      = PdfAcroForm.GetAcroForm(sourcePdfDocument, true);
                    StringTokenizer tokenizer = new StringTokenizer(line, ";");
                    IDictionary <String, PdfFormField> fields = form.GetFormFields();
                    //Fill out fields
                    PdfFormField toSet;
                    fields.TryGetValue("name", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("abbr", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("capital", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("city", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("population", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("surface", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("timezone1", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("timezone2", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    fields.TryGetValue("dst", out toSet);
                    toSet.SetValue(tokenizer.NextToken());
                    //Flatten fields
                    form.FlattenFields();
                    sourcePdfDocument.Close();
                    sourcePdfDocument = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    //Copy pages
                    sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocument, null);
                    sourcePdfDocument.CopyPagesTo(1, sourcePdfDocument.GetNumberOfPages(), destPdfDocumentSmartMode,
                                                  null);
                    sourcePdfDocument.Close();
                }
            }

            destPdfDocument.Close();
            destPdfDocumentSmartMode.Close();
        }
Exemplo n.º 12
0
        public byte[] GenerateAttestationMineur(PdfAttestationMineur values)
        {
            var          filePath = Path.Combine(_env.ContentRootPath, $"PDF/attesation_mineur_fillable.pdf");
            MemoryStream stream   = new MemoryStream();

            //var filePath = "/PDF/integration_coach_fillable.pdf";
            //var savePath = "/PDF/saved/toSave.pdf";

            PdfDocument pdf  = new PdfDocument(new PdfReader(filePath), new PdfWriter(stream));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false);

            var fields = form.GetFormFields();

            foreach (PdfFormField field in fields.Values)
            {
                field.SetFontSize(12);
            }

            fields["name"].SetValue($"{values.FistName} {values.LastName}");
            fields["address"].SetValue($"{values.AddressLine1}\n{values.AddressLine2}");
            fields["city"].SetValue(values.City);
            fields["postal-code"].SetValue(values.PostalCode);
            fields["email"].SetValue(values.Email);
            fields["phone"].SetValue(values.Phone);
            fields["made-at"].SetValue(values.MadeAt);
            fields["made-date"].SetValue(values.MadeDate);

            PdfAcroForm.GetAcroForm(pdf, false).FlattenFields();

            pdf.Close();

            return(stream.ToArray());
        }
        public IEnumerable <PDFField> GetPDFFields(string filePath, string prefix)
        {
            using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath)))
            {
                PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false);

                List <PDFField> pdfFields = new List <PDFField>();


                form.GetFormFields().AsParallel().ForAll(
                    f =>
                {
                    lock (this)      //Prevent threads from trying to write at same time.
                    {
                        if (f.Key.StartsWith(prefix))
                        {
                            pdfFields.Add(

                                new PDFField()
                            {
                                Name  = f.Key,
                                Value = String.Empty
                            }
                                );
                        }
                    }
                }

                    );

                return(pdfFields);
            }
        }
Exemplo n.º 14
0
        public virtual void FormFillingAppend_form_filled_Test()
        {
            String             srcFilename = sourceFolder + "Form_Empty.pdf";
            String             temp        = destinationFolder + "temp_filled.pdf";
            String             filename    = destinationFolder + "formFillingAppend_form_filled.pdf";
            StampingProperties props       = new StampingProperties();

            props.UseAppendMode();
            PdfDocument doc  = new PdfDocument(new PdfReader(srcFilename), new PdfWriter(temp), props);
            PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true);

            foreach (PdfFormField field in form.GetFormFields().Values)
            {
                field.SetValue("Different");
            }
            doc.Close();
            Flatten(temp, filename);
            new FileInfo(temp).Delete();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(filename, sourceFolder + "cmp_formFillingAppend_form_filled.pdf"
                                                                    , destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Exemplo n.º 15
0
        public static List <string> GetFieldNames(string src)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);

            return(form.GetFormFields().Keys.ToList());
        }
Exemplo n.º 16
0
        public FileStreamResult Annotate(int id)
        {
            string tempFile = GetTempFilePath();

            using (PdfReader reader = new PdfReader(GetFilePath()))
            {
                reader.SetUnethicalReading(true);
                using (PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(tempFile)))
                {
                    PdfAcroForm pdfForm = PdfAcroForm.GetAcroForm(pdfDoc, true);
                    //var list = pdfForm.GetPdfObject().Values();

                    foreach (var de in pdfForm.GetFormFields())
                    {
                        var           formField = de.Value;
                        PdfAnnotation text      = PdfAnnotation.MakeAnnotation(formField.GetPdfObject()); //, PdfAnnotation.(){ , new Rectangle(200f, 250f, 300f, 350f), "Fox", "The fox is quick", true, "Comment");
                        if (text != null)
                        {
                            text.s(new PdfString(de.Key));
                        }
                        //fields.Add(new PdfFormField() { Name = de.Key, Value = formField.GetValueAsString() });
                    }
                    pdfDoc.Close();
                }
            }

            return(new FileStreamResult(new FileStream(tempFile, FileMode.Open), "application/pdf"));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Fills the  pdf document with the properties of the loaded model
        /// </summary>
        /// <param name="pdfDocument">Output pdf document</param>
        public virtual void Fill(PdfDocument pdfDocument)
        {
            // get the form inside the pdf
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);
            // get all fields from the form
            IDictionary <string, PdfFormField> fields = form.GetFormFields();

            // gets the model properties/fields definition
            var modelDefinitions = GetPropertyOrFields();

            foreach (var definition in modelDefinitions)
            {
                var value = definition.GetValue(_model);
                // if no value was inferred based on definition, skip definition
                if (!((value?.Count ?? 0) > 0))
                {
                    continue;
                }
                foreach (var b in value)
                {
                    fields.SetField(b.Key, b.Value.ToString());
                }
            }

            // Only add the fields that were setten
            form.FlattenFields();
            // Closes and saves the pdf
            pdfDocument.Close();
        }
Exemplo n.º 18
0
        public virtual void FillFormWithDefaultResourcesUpdateFont()
        {
            String      outPdf = destinationFolder + "fillFormWithDefaultResourcesUpdateFont.pdf";
            String      cmpPdf = sourceFolder + "cmp_fillFormWithDefaultResourcesUpdateFont.pdf";
            PdfWriter   writer = new PdfWriter(outPdf);
            PdfReader   reader = new PdfReader(sourceFolder + "formWithDefaultResources.pdf");
            PdfDocument pdfDoc = new PdfDocument(reader, writer);
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            IDictionary <String, PdfFormField> fields = form.GetFormFields();
            PdfFormField field = fields.Get("Text1");

            // TODO DEVSIX-2016: the font in /DR of AcroForm dict is not updated, even though /DA field is updated.
            field.SetFont(PdfFontFactory.CreateFont(StandardFonts.COURIER));
            field.SetValue("New value size must be 8, but with different font.");
            new Canvas(new PdfCanvas(pdfDoc.GetFirstPage()), pdfDoc, new Rectangle(30, 500, 500, 200)).Add(new Paragraph
                                                                                                               ("The text font after modification it via PDF viewer (e.g. Acrobat) shall be preserved."));
            pdfDoc.Close();
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_");

            if (errorMessage != null)
            {
                NUnit.Framework.Assert.Fail(errorMessage);
            }
        }
Exemplo n.º 19
0
        public virtual void FlattenReadOnly()
        {
            //Logging is expected since there are duplicate field names
            //isReadOnly should be true after DEVSIX-2156
            PdfWriter   writer      = new PdfWriter(new MemoryStream());
            PdfDocument pdfDoc      = new PdfDocument(writer);
            PdfReader   reader      = new PdfReader(sourceFolder + "readOnlyForm.pdf");
            PdfDocument pdfInnerDoc = new PdfDocument(reader);

            pdfInnerDoc.CopyPagesTo(1, pdfInnerDoc.GetNumberOfPages(), pdfDoc, new PdfPageFormCopier());
            pdfInnerDoc.Close();
            reader      = new PdfReader(sourceFolder + "readOnlyForm.pdf");
            pdfInnerDoc = new PdfDocument(reader);
            pdfInnerDoc.CopyPagesTo(1, pdfInnerDoc.GetNumberOfPages(), pdfDoc, new PdfPageFormCopier());
            pdfInnerDoc.Close();
            PdfAcroForm form       = PdfAcroForm.GetAcroForm(pdfDoc, false);
            bool        isReadOnly = true;

            foreach (PdfFormField field in form.GetFormFields().Values)
            {
                isReadOnly = (isReadOnly && field.IsReadOnly());
            }
            pdfDoc.Close();
            NUnit.Framework.Assert.IsFalse(isReadOnly);
        }
Exemplo n.º 20
0
        public virtual void ManipulatePdf(String src, String dest)
        {
            //Initialize PDF document
            PdfDocument pdf  = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
            IDictionary <String, PdfFormField> fields = form.GetFormFields();
            PdfFormField toSet;

            fields.TryGetValue("name", out toSet);
            toSet.SetValue("James Bond");
            fields.TryGetValue("language", out toSet);
            toSet.SetValue("English");
            fields.TryGetValue("experience1", out toSet);
            toSet.SetValue("Off");
            fields.TryGetValue("experience2", out toSet);
            toSet.SetValue("Yes");
            fields.TryGetValue("experience3", out toSet);
            toSet.SetValue("Yes");
            fields.TryGetValue("shift", out toSet);
            toSet.SetValue("Any");
            fields.TryGetValue("info", out toSet);
            toSet.SetValue("I was 38 years old when I became an MI6 agent.");
            form.FlattenFields();
            pdf.Close();
        }
Exemplo n.º 21
0
 private static void discover(Conf conf)
 {
     try
     {
         PdfReader   pdfReader = new PdfReader(conf.source_path);
         PdfDocument doc       = new PdfDocument(pdfReader);
         PdfAcroForm form      = PdfAcroForm.GetAcroForm(doc, false);
         if (form == null)
         {
             Console.WriteLine("Document has no form");
             return;
         }
         Console.WriteLine("Type\tName\t\t\tValue");
         Console.WriteLine("------\t-----\t\t\t------");
         foreach (KeyValuePair <string, PdfFormField> kvp in form.GetFormFields())
         {
             if (kvp.Value != null && kvp.Value.GetFormType() != null)
             {
                 string val       = kvp.Value.GetValueAsString();
                 string fieldtype = kvp.Value.GetFormType().ToString() ?? "";
                 Console.WriteLine("{0}\t{1}\t\t\t{2}", fieldtype, kvp.Key, val);
             }
         }
     }
     catch (Exception e)
     {
         string message = conf.debug ? e.Message + Environment.NewLine + e.StackTrace : "Error discovering";
         new MessageBag("error", message).PrintErrors();
     }
 }
        public virtual void ManipulatePdf(String src, String dest)
        {
            //Initialize PDF document
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            IDictionary <String, PdfFormField> fields = form.GetFormFields();

            fields["name"].SetValue("James Bond").SetBackgroundColor(ColorConstants.ORANGE);
            fields["language"].SetValue("English");
            fields["experience1"].SetValue("Yes");
            fields["experience2"].SetValue("Yes");
            fields["experience3"].SetValue("Yes");
            IList <PdfObject> options = new List <PdfObject>();

            options.Add(new PdfString("Any"));
            options.Add(new PdfString("8.30 am - 12.30 pm"));
            options.Add(new PdfString("12.30 pm - 4.30 pm"));
            options.Add(new PdfString("4.30 pm - 8.30 pm"));
            options.Add(new PdfString("8.30 pm - 12.30 am"));
            options.Add(new PdfString("12.30 am - 4.30 am"));
            options.Add(new PdfString("4.30 am - 8.30 am"));
            PdfArray arr = new PdfArray(options);

            fields["shift"].SetOptions(arr);
            fields["shift"].SetValue("Any");
            PdfFont courier = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            fields["info"].SetValue("I was 38 years old when I became an MI6 agent.", courier, 7f);
            pdfDoc.Close();
        }
Exemplo n.º 23
0
        public virtual void FormFlatteningTest_DefaultAppearanceGeneration_Rot90()
        {
            String srcFilePattern = "FormFlatteningDefaultAppearance_90_";
            String destPattern    = "FormFlatteningDefaultAppearance_90_";

            for (int i = 0; i < 360; i += 90)
            {
                String      src  = sourceFolder + srcFilePattern + i + ".pdf";
                String      dest = destinationFolder + destPattern + i + "_flattened.pdf";
                String      cmp  = sourceFolder + "cmp_" + srcFilePattern + i + ".pdf";
                PdfDocument doc  = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
                PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true);
                foreach (PdfFormField field in form.GetFormFields().Values)
                {
                    field.SetValue("Test");
                }
                form.FlattenFields();
                doc.Close();
                CompareTool compareTool  = new CompareTool();
                String      errorMessage = compareTool.CompareByContent(dest, cmp, destinationFolder, "diff_");
                if (errorMessage != null)
                {
                    NUnit.Framework.Assert.Fail(errorMessage);
                }
            }
        }
Exemplo n.º 24
0
        public virtual void FormFlatteningTest_DefaultAppearanceGeneration_Rot()
        {
            String srcFilePatternPattern = "FormFlatteningDefaultAppearance_{0}_";
            String destPatternPattern    = "FormFlatteningDefaultAppearance_{0}_";

            String[] rotAngle = new String[] { "0", "90", "180", "270" };
            foreach (String angle in rotAngle)
            {
                String srcFilePattern = MessageFormatUtil.Format(srcFilePatternPattern, angle);
                String destPattern    = MessageFormatUtil.Format(destPatternPattern, angle);
                for (int i = 0; i < 360; i += 90)
                {
                    String      src  = sourceFolder + srcFilePattern + i + ".pdf";
                    String      dest = destinationFolder + destPattern + i + "_flattened.pdf";
                    String      cmp  = sourceFolder + "cmp_" + srcFilePattern + i + ".pdf";
                    PdfDocument doc  = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
                    PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, true);
                    foreach (PdfFormField field in form.GetFormFields().Values)
                    {
                        field.SetValue("Test");
                    }
                    form.FlattenFields();
                    doc.Close();
                    NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(dest, cmp, destinationFolder, "diff_"));
                }
            }
        }
Exemplo n.º 25
0
        // ********************************************************************
        // Fct:     ReadTestFields
        //
        // Descr:   Reads the test fields an returns the content to the Infobox
        //
        // Owner:   erst
        // ********************************************************************
        public static void ReadTestFields(Form1 frm, String src)
        {
            try
            {
                PdfDocument scrPdf = new PdfDocument(new PdfReader(src));
                PdfAcroForm form   = PdfAcroForm.GetAcroForm(scrPdf, true);
                IDictionary <String, PdfFormField> fields = form.GetFormFields();

                foreach (var field in fields)
                {
                    frm.InfoText = "Key: " + field.Key;                                                   // ist der Name des Feldes
                    PdfFormField PdfField = field.Value;
                    frm.InfoText = ";       Value: " + PdfField.GetValueAsString() + Environment.NewLine; // ist der Inhalt des Feldes

                    scrPdf.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
        }
Exemplo n.º 26
0
        // ********************************************************************
        // Fct:     ReadAnnot
        //
        // Descr:   -
        //
        // Owner:   erst
        // ********************************************************************
        public static void ReadAnnot(String src, String dest)
        {
            try
            {
                PdfDocument ScrPdf = new PdfDocument(new PdfReader(src));
                //PdfDocument DestPdf = new PdfDocument(new PdfWriter(dest));

                PdfPage page = ScrPdf.GetFirstPage();

                PdfAcroForm form = PdfAcroForm.GetAcroForm(ScrPdf, true);

                IDictionary <String, PdfFormField> fields = form.GetFormFields();

                foreach (var field in fields)
                {
                    string       str      = field.Key;                   // ist der name des Feldes
                    PdfFormField PdfField = field.Value;
                    string       str2     = PdfField.GetValueAsString(); // ist der Inhalt des Feldes
                }


                // DestPdf.Close();
                ScrPdf.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
        }
Exemplo n.º 27
0
        public virtual void CreatePDF(String dest)
        {
            // Create a new pdf based on the resource one
            PdfDocument pdfDocument = new PdfDocument(new PdfReader(RESOURCE_FOLDER + INPUT_FILE),
                                                      new PdfWriter(dest));

            PdfFont font = PdfFontFactory.CreateFont(FONTS_FOLDER + "NotoNaskhArabic-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 text = "\u0641\u064A\u0020\u0627\u0644\u0642\u064A\u0627\u0645\u0020\u0628\u0646\u0634\u0627\u0637";

            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);

            // Set needAppearance value to false in order to hide the text of the form fields
            form.SetNeedAppearances(false);

            // Update the value and some other properties of all the pdf document's form fields
            foreach (KeyValuePair <String, PdfFormField> entry in form.GetFormFields())
            {
                PdfFormField field = entry.Value;
                field.SetValue(text);
                field.SetFont(font).SetJustification(2);
            }

            pdfDocument.Close();
        }
Exemplo n.º 28
0
        public 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 checkedField   = fields[CHECKED_FIELD_NAME];
            PdfFormField uncheckedField = fields[UNCHECKED_FIELD_NAME];

            // Get array of possible values of the checkbox
            String[] states = checkedField.GetAppearanceStates();

            // See all possible values in the console
            foreach (String state in states)
            {
                Console.Write(state + "; ");
            }

            // Search and set checked state to the previously unchecked checkbox and vice versa
            foreach (String state in states)
            {
                if (state.Equals(CHECKED_STATE_VALUE))
                {
                    uncheckedField.SetValue(state);
                }
                else if (state.Equals(UNCHECKED_STATE_VALUE))
                {
                    checkedField.SetValue(state);
                }
            }

            pdfDoc.Close();
        }
        public string[] GetKeyTemplateKeys()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(TemplateForm));
            PdfAcroForm form   = PdfAcroForm.GetAcroForm(pdfDoc, true);
            IDictionary <string, PdfFormField> fields = form.GetFormFields();

            return(fields.Keys.ToArray());
        }
Exemplo n.º 30
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;
                }
            }
        }