Exemplo n.º 1
0
        static void set_field(AcroFields form, string field_key, string value)
        {
            switch (form.GetFieldType(field_key))
            {
            case AcroFields.FIELD_TYPE_CHECKBOX:
            case AcroFields.FIELD_TYPE_RADIOBUTTON:
            //bool v;
            //if (bool.TryParse(value, out v))
            //    value = !v ? "false" : "true";
            //else
            //{
            //    int i;
            //    if (int.TryParse(value, out i))
            //        value = i == 0 ? "false" : "true";
            //    else
            //        value = string.IsNullOrEmpty(value) ? "false" : "true";
            //}
            //form.SetField(field_key, value);
            //break;
            case AcroFields.FIELD_TYPE_COMBO:
            case AcroFields.FIELD_TYPE_LIST:
            case AcroFields.FIELD_TYPE_NONE:
            case AcroFields.FIELD_TYPE_PUSHBUTTON:
            case AcroFields.FIELD_TYPE_SIGNATURE:
            case AcroFields.FIELD_TYPE_TEXT:
                form.SetField(field_key, value);
                break;

            default:
                throw new Exception("Unknown option: " + form.GetFieldType(field_key));
            }
        }
Exemplo n.º 2
0
        public byte[] FillInFields(Dictionary <string, string> formFields)
        {
            if (string.IsNullOrEmpty(this._location.Trim()))
            {
                return(null);
            }
            byte[]       fileBytes;
            MemoryStream memStream = new MemoryStream();

            PdfReader  reader  = new PdfReader(this._location);
            PdfStamper stamper = new PdfStamper(reader, memStream);

            var        layers = stamper.GetPdfLayers();
            AcroFields fields = stamper.AcroFields;

            fields.GenerateAppearances = true;

            foreach (var name in formFields.Keys)
            {
                var type = fields.GetFieldType(name);

                if (type == AcroFields.FIELD_TYPE_CHECKBOX)
                {
                    //fields.SetField(name, formFields[name].ToLower() == "true" ? "Yes" : "Off");
                }
                else
                {
                    fields.SetField(name, formFields[name]);
                }
            }
            stamper.Close();
            fileBytes = memStream.ToArray();

            return(fileBytes);
        }
Exemplo n.º 3
0
        public static byte[] fill_template(byte[] templateFile, List <FormElement> elements)
        {
            using (MemoryStream output = new MemoryStream())
                using (PdfReader pdfReader = new PdfReader(templateFile))
                    using (PdfStamper stamper = new PdfStamper(pdfReader, output))
                    {
                        //without this line of code, farsi fonts would not be visible
                        stamper.AcroFields.AddSubstitutionFont(GetFont().BaseFont);

                        AcroFields form = stamper.AcroFields;
                        form.GenerateAppearances = true;

                        elements.Where(e => !string.IsNullOrEmpty(e.Name) && form.Fields.ContainsKey(e.Name))
                        .ToList().ForEach(e =>
                        {
                            switch (form.GetFieldType(e.Name))
                            {
                            case AcroFields.FIELD_TYPE_TEXT:
                            case AcroFields.FIELD_TYPE_COMBO:
                            case AcroFields.FIELD_TYPE_RADIOBUTTON:
                                form.SetField(e.Name, e.Type == FormElementTypes.Numeric ? e.FloatValue.ToString() : e.TextValue);
                                break;

                            case AcroFields.FIELD_TYPE_CHECKBOX:
                                form.SetField(e.Name, e.BitValue.HasValue && e.BitValue.Value ? "Yes" : "Off");
                                break;

                            case AcroFields.FIELD_TYPE_LIST:
                                form.SetListOption(e.Name,
                                                   e.TextValue.Split('~').Select(t => t.Trim()).Where(t => !string.IsNullOrEmpty(t)).ToArray(), null);
                                form.SetField(e.Name, null);
                                break;

                            case AcroFields.FIELD_TYPE_PUSHBUTTON:
                                break;

                            case AcroFields.FIELD_TYPE_SIGNATURE:
                                break;
                            }
                        });

                        //by doing this, the form will not be editable anymore
                        stamper.FormFlattening = true;

                        //to make a specific field not editable
                        //stamper.PartialFormFlattening("[field_name]");

                        stamper.Close();
                        pdfReader.Close();

                        return(output.GetBuffer());
                    }
        }
Exemplo n.º 4
0
        /// <summary>
        /// METODO 1: ricerca di un acrofield generico per name,
        /// l’oggetto ritornato deve indicare il tipo di acrofield(checkbox, textbox, signaturefield, radiobutton).
        /// </summary>
        /// <param name="fieldName">Field name</param>
        /// <returns>Field name</returns>
        public int GetAcrofieldType(string fieldName)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException(fieldName);
            }

            //Getting fields
            AcroFields form = reader.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a checkbox/radiobutton/signature/text withe the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                (
                                    form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_CHECKBOX ||
                                    form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_RADIOBUTTON ||
                                    form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_SIGNATURE ||
                                    form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_TEXT
                                )
                                )
                         .Select(kvp => form.GetFieldType(kvp.Key))?.FirstOrDefault();

            //If field not found (default is 0), throw an exception
            if (result == 0)
            {
                throw new FieldNotFoundException(fieldName);
            }

            //Returning the field's type
            return((int)result);
        }
Exemplo n.º 5
0
        /// <summary>
        /// METODO 3: Sostituire un acrofield di tipo signature con un acrofield di tipo checkbox
        /// Locking for a checkbox and checking it
        /// </summary>
        /// <param name="fieldName">string Name of the signaturefield to substitute</param>
        public void SubstituteSignature(string fieldName)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException(fieldName);
            }

            //Getting fields
            AcroFields form = reader.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a signatureBox with the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_SIGNATURE
                                )
                         .Select(kvp => new { kvp.Key, Position = form.GetFieldPositions(kvp.Key) })
                         ?.FirstOrDefault();

            //Checking if the query had results
            if (result == null)
            {
                throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_SIGNATURE);
            }

            //Removing field
            form.RemoveField(result.Key);

            //Creating new checkbox with signaturefield's coordinates
            //Note: We're replacing the first occurrence
            RadioCheckField checkbox = new RadioCheckField(stamper.Writer, result.Position[0].position, "i_was_a_signature_field", "Yes")
            {
                //Setting look
                CheckType       = RadioCheckField.TYPE_CHECK,
                Checked         = true,
                BorderWidth     = BaseField.BORDER_WIDTH_THIN,
                BorderColor     = BaseColor.BLACK,
                BackgroundColor = BaseColor.WHITE
            };

            //Adding checbox in signaturefield's page
            stamper.AddAnnotation(checkbox.CheckField, result.Position[0].page);
        }
 //Read all 'Form values/keys' from an existing multi-page PDF document
 public void ReadPDFformDataPageWise()
 {
 PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
 AcroFields form = reader.AcroFields;
 try
 {
 for (int page = 1; page <= reader.NumberOfPages; page++)
 {
     foreach (KeyValuePair<string, AcroFields.Item> kvp in form.Fields)
     {
         switch (form.GetFieldType(kvp.Key))
         {
             case AcroFields.FIELD_TYPE_CHECKBOX:
             case AcroFields.FIELD_TYPE_COMBO:
             case AcroFields.FIELD_TYPE_LIST:
             case AcroFields.FIELD_TYPE_RADIOBUTTON:
             case AcroFields.FIELD_TYPE_NONE:
             case AcroFields.FIELD_TYPE_PUSHBUTTON:
             case AcroFields.FIELD_TYPE_SIGNATURE:
             case AcroFields.FIELD_TYPE_TEXT:
                 int fileType = form.GetFieldType(kvp.Key);
                 string fieldValue = form.GetField(kvp.Key);
                 string translatedFileName = form.GetTranslatedFieldName(kvp.Key);
                 break;
         }
     }
 }
 }
 catch
 {
 }
 finally
 {
     reader.Close();
 }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Constructor AcroField based.
        /// Create a field 'image' of the matching field in the PDF form.
        /// </summary>
        /// <param name="fields">Field hashset of PDF form</param>
        /// <param name="field">Field reference</param>
        public TemplateField(AcroFields fields, KeyValuePair <String, iTextSharp.text.pdf.AcroFields.Item> field)
        {
            int _nType = fields.GetFieldType(field.Key);
            TemplateFieldType _ftType = (TemplateFieldType)(_nType);

            this.Name = field.Key;
            this.Type = _ftType;

            if (_ftType == TemplateFieldType.Checkbox)
            {
                string[] _rgsStates = fields.GetAppearanceStates(field.Key);
                this.OnValue  = _rgsStates[1];
                this.OffValue = _rgsStates[0];
            }
        }
Exemplo n.º 8
0
        private static AcroFieldProperties GetAcroFieldProperties(AcroFields pdfForm, string acroFieldName, int pageNumber)
        {
            IList <AcroFields.FieldPosition> position = pdfForm.GetFieldPositions(acroFieldName);

            return(new AcroFieldProperties {
                Name = acroFieldName,
                Type = pdfForm.GetFieldType(acroFieldName),
                SelectOptions = pdfForm.GetSelectOptions(acroFieldName),
                Text = pdfForm.GetTextProperties(acroFieldName),
                PageNumber = pageNumber,
                LeftPos = position[0].position.Left,
                BottomPos = position[0].position.Bottom,
                RightPos = position[0].position.Right,
                TopPos = position[0].position.Top
            });
        }
        /// <summary>
        /// Set font family and font size on all text fields for consistency
        /// </summary>
        /// <param name="stamperFields">
        /// PdfStamper.AcroFields - so we can set the form field value here.
        /// </param>
        /// <param name="family">BaseFont</param>
        /// <param name="size">Desired size</param>
        public static void SetTemplateFont(AcroFields stamperFields, BaseFont family, float size)
        {
            // ignore everything except text fields
            var textFields = stamperFields.Fields.Keys
                             .Where(x => stamperFields.GetFieldType(x) == AcroFields.FIELD_TYPE_TEXT &&
                                    GetFontSize(stamperFields, x) != 0f
                                    )
                             .ToDictionary(k => k);

            Console.WriteLine(string.Join(" :: ", textFields.Keys.ToArray()));

            foreach (var key in textFields.Keys)
            {
                stamperFields.SetFieldProperty(key, "textfont", family, null);
                stamperFields.SetFieldProperty(key, "textsize", size, null);
            }
        }
Exemplo n.º 10
0
        public static byte[] SetFields(byte[] pdfFile, IFormContentProvider contentProvider)
        {
            var        pr   = new PdfReader(pdfFile);
            var        ims  = new MemoryStream();
            var        ps   = new PdfStamper(pr, ims);
            AcroFields flds = ps.AcroFields;

            foreach (DictionaryEntry entry in flds.Fields)
            {
                string fieldName = entry.Key.ToString();
                var    type      = (FieldTypes)flds.GetFieldType(fieldName);
                switch (type)
                {
                case FieldTypes.Text:
                    string value   = null;
                    string display = null;
                    contentProvider.PopulateTextField(fieldName, out value, out display);
                    if (value != null)
                    {
                        flds.SetField(fieldName, value);
                    }
                    break;

                case FieldTypes.List:
                    string[] exportValues  = null;
                    string[] displayValues = null;
                    string[] selected      = null;
                    contentProvider.PopulateListField(fieldName, out exportValues, out displayValues, out selected);
                    if (exportValues != null)
                    {
                        flds.SetListOption(fieldName, exportValues, displayValues);
                    }
                    if (selected != null)
                    {
                        flds.SetListSelection(fieldName, selected);
                    }
                    break;

                default:
                    break;
                }
            }
            ps.Close();
            return(ims.ToArray());
        }
Exemplo n.º 11
0
        /// <summary>
        /// METODO 4: Selezionare un acrofield di tipo radiobutton
        /// Selecting a radiobutton acrofield
        /// </summary>
        /// <param name="fieldName">string Name of the radiobutton to select</param>
        /// <param name="valueToSelect">string Value to select</param>
        public void SelectRadiobutton(string fieldName, string valueToSelect)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException("fieldName");
            }

            if (valueToSelect == null)
            {
                throw new ArgumentNullException("valueToSelect");
            }

            //Getting forms
            AcroFields form = stamper.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a radiobutton with the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_RADIOBUTTON)
                         .Select(kvp => new { kvp.Key, States = form.GetAppearanceStates(kvp.Key) })
                         ?.FirstOrDefault();

            //Checking if the query had results
            if (result == null)
            {
                throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_RADIOBUTTON);
            }

            //Checking if value to select exists
            if (!result.States.Contains(valueToSelect))
            {
                throw new RadiobuttonValueNotFoundException(fieldName, valueToSelect);
            }

            //Setting the value
            form.SetField(form.GetTranslatedFieldName(result.Key), valueToSelect);
        }
        private void ValidateFitSingleLineText(AcroFields acroFields, string fieldName)
        {
            if (acroFields.GetFieldType(fieldName) != AcroFields.FIELD_TYPE_TEXT)
            {
                throw new InvalidOperationException(string.Format(
                                                        "field [{0}] is not a TextField",
                                                        fieldName
                                                        ));
            }

            if (IsMultiLine(acroFields, fieldName))
            {
                throw new InvalidOperationException(string.Format(
                                                        "only single line TextField is allowed; field [{0}] is multiline.",
                                                        fieldName
                                                        ));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///	METODO 2: Flaggare un acrofield di tipo checkbox
        /// Looking for a checkbox and checking it
        /// </summary>
        /// <param name="fieldName">string Name of the checkbox to check</param>
        /// <returns>bool Operation result</returns>
        public void FlagCheckbox(string fieldName)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException(fieldName);
            }

            //Getting forms
            AcroFields form = stamper.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a checkbox with the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_CHECKBOX
                                )
                         .Select(kvp =>
                                 new {
                kvp.Key,
                Name   = form.GetTranslatedFieldName(kvp.Key),
                Values = form.GetAppearanceStates(form.GetTranslatedFieldName(kvp.Key))
            })
                         ?.FirstOrDefault();

            //Checking if the query had results
            if (result == null)
            {
                throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_CHECKBOX);
            }

            //If the box isn't checked, we check it
            if (form.GetField(result.Key).Equals(result.Values[0]) || form.GetField(result.Key).Length == 0)
            {
                //Changing state and returning true (in case of error it returns false)
                form.SetField(result.Name, result.Values[1]);
            }
        }
Exemplo n.º 14
0
        private string verifyExistingSignatureField(String sigField)
        {
            AcroFields form = this.document.AcroFields;

            foreach (string key in form.Fields.Keys)
            {
                if (key.IndexOf(sigField) > 0)
                {
                    if (form.GetFieldType(key) == AcroFields.FIELD_TYPE_SIGNATURE)
                    {
                        return(key);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Get text field font size
        /// </summary>
        /// <param name="acroFields">AcroFields</param>
        /// <param name="fieldName">Text field name</param>
        /// <returns>text field font size</returns>
        public static float GetFontSize(AcroFields acroFields, string fieldName)
        {
            if (acroFields.GetFieldType(fieldName) == AcroFields.FIELD_TYPE_TEXT)
            {
                // need the dictionary field appearance
                var pdfDictionary = acroFields.GetFieldItem(fieldName).GetMerged(0);
                var pdfString     = pdfDictionary.GetAsString(PdfName.DA);
                if (pdfString != null)
                {
                    var daNames = AcroFields.SplitDAelements(pdfString.ToString());

                    float size;
                    return(daNames[1] != null &&
                           Single.TryParse(daNames[1].ToString(), out size)
                        ? size : 0f);
                }
            }

            return(0f); // text field auto-sized font
        }
Exemplo n.º 16
0
        private static IEnumerable <DocumentTemplateItem> ParseItems(AcroFields acroFields)
        {
            foreach (var fieldKey in acroFields.Fields.Keys)
            {
                var item = new DocumentTemplateItem {
                    Label = Core.Utils.StringUtils.GetCamelCase(fieldKey)
                };

                if (acroFields.GetFieldType(fieldKey) == AcroFields.FIELD_TYPE_COMBO)
                {
                    foreach (var itemValue in acroFields.GetAppearanceStates(fieldKey))
                    {
                        item.DocumentTemplateItemValues.Add(new DocumentTemplateItemValue {
                            Value = itemValue
                        });
                    }
                }

                yield return(item);
            }
        }
Exemplo n.º 17
0
        public AusBaseResponse getRadioTemplate(GetTemplateFieldReq getTemplateFieldReq)
        {
            AusBaseResponse            ausBaseResponse         = new AusBaseResponse();
            List <GetTemplateFieldRes> getTemplateFieldResList = new List <GetTemplateFieldRes>();

            string          fileCode        = getTemplateFieldReq.fileCode;
            PDFEntityConfig pDFEntityConfig = CommonConstantsUtil.PDFCONFIG[fileCode];

            string path = pDFEntityConfig.filePath;

            PdfReader.unethicalreading = true;
            PdfReader reader = new PdfReader(path);

            MemoryStream memory = new MemoryStream();

            PdfStamper stamper = new PdfStamper(reader, memory, '\0', false);

            stamper.Writer.CloseStream = false;
            AcroFields pdfFormFields = stamper.AcroFields;

            foreach (var item in pdfFormFields.Fields)
            {
                var d    = item.Value.GetMerged(0);
                int type = pdfFormFields.GetFieldType(item.Key);

                if (type == 2)
                {
                    GetTemplateFieldRes getTemplateFieldRes = new GetTemplateFieldRes();
                    string[]            aaa = pdfFormFields.GetAppearanceStates(item.Key);
                    getTemplateFieldRes.fieldName = item.Key;
                    getTemplateFieldRes.children  = aaa;

                    getTemplateFieldResList.Add(getTemplateFieldRes);
                }
            }
            ausBaseResponse.responseBody = getTemplateFieldResList;
            ausBaseResponse.responseCode = 0;

            return(ausBaseResponse);
        }
Exemplo n.º 18
0
        /// <summary>
        ///  METODO 5: Inserire un testo in un acrofield ti tipo testo
        ///  Inserting the given text into a textfield
        /// </summary>
        /// <param name="fieldName">string Name of the textfield to modify</param>
        /// <param name="text">string Text to insert</param>
        public void InsertTextInField(string fieldName, string text)
        {
            //Checking if argument is null
            if (fieldName == null)
            {
                throw new ArgumentNullException("fieldName");
            }
            if (text == null)
            {
                throw new ArgumentNullException("valueToSelect");
            }

            //Getting forms
            AcroFields form = stamper.AcroFields;

            //Checking if document has no fields
            if (form.Fields.Count == 0)
            {
                throw new DocumentHasNoFieldsException();
            }

            //Looking for a text-field with the given name
            var result = form.Fields
                         .Where(kvp =>
                                form.GetTranslatedFieldName(kvp.Key).Equals(fieldName) &&
                                form.GetFieldType(kvp.Key) == AcroFields.FIELD_TYPE_TEXT
                                )
                         .Select(kvp => form.GetTranslatedFieldName(kvp.Key))
                         ?.FirstOrDefault();

            //Checking if the query had results
            if (result == null)
            {
                throw new FieldNotFoundException(fieldName, AcroFields.FIELD_TYPE_RADIOBUTTON);
            }

            //Setting the given text
            form.SetField(fieldName, text);
        }
Exemplo n.º 19
0
        private object ProcessPdf(PdfReader pr)
        {
            AcroFields     flds    = pr.AcroFields;
            FormSubmission formSub = Container.NewTransientInstance <FormSubmission>();

            foreach (DictionaryEntry entry in flds.Fields)
            {
                string     fieldName = entry.Key.ToString();
                FieldTypes type      = (FieldTypes)flds.GetFieldType(fieldName);
                string     content   = flds.GetField(fieldName);
                formSub.AddFormField(type, fieldName, content);
            }

            //Following code will write the .pdf as a byte array
            var ims = new MemoryStream();
            var ps  = new PdfStamper(pr, ims);

            ps.Close();
            formSub.FormAsBytes = ims.ToArray();

            //TODO:  Guard against 1) the FormCode field not existing 2) There being no FormDefinition for that code

            string formCode = flds.GetField(AppSettings.FieldLabelForFormCode());

            formSub.FormCode = formCode;
            FormDefinition formDef = FormRepository.FindFormDefinitionByCode(formCode);

            Container.Persist(ref formSub);

            //GenerateTaskIfApplicable(formSub, formDef);
            object result = null;

            if (formDef != null)
            {
                result = AutoProcessIfApplicable(formSub, formDef);  //TODO:  Or maybe form submission? Or some standard thank you acknowledgement?
            }
            return(result ?? formSub);
        }
Exemplo n.º 20
0
        public string findSignatureField(byte[] inputPdf, string fieldName)
        {
            string resultFieldName = "";

            Console.WriteLine("Read PDF");
            PdfReader  reader = new PdfReader(inputPdf);
            AcroFields form   = reader.AcroFields;

            foreach (string key in form.Fields.Keys)
            {
                if (key.IndexOf(fieldName) > 0)
                {
                    if (AcroFields.FIELD_TYPE_SIGNATURE == form.GetFieldType(key))
                    {
                        Console.WriteLine("Signature Field Found");
                        resultFieldName = key;
                        break;
                    }
                }
            }
            reader.Close();
            return(resultFieldName);
        }
Exemplo n.º 21
0
        public static response_item_type[] FillForm(pdf_stamper_request request, string mapping_root_path, string template_root_path, string output_root_path, DataTable data, string fonts_root_path, bool force_unc)
        {
            lock (_lock) {
                try {
                    List <Item> items_with_path = new List <Item>();
                    mappings    mapping         = new mappings();
                    if (File.Exists(mapping_root_path))
                    {
                        mapping = File.ReadAllText(mapping_root_path).DeserializeXml2 <mappings>();
                    }

                    FileInfo mapping_path = new FileInfo(mapping_root_path);

                    /*
                     * string fox_helper_path = Path.Combine(mapping_path.DirectoryName, "Fox.txt");
                     * if (!File.Exists(fox_helper_path)) {
                     *  StringBuilder b = new StringBuilder();
                     *  b.Append(@"
                     * DIMENSION laArray[30,2]
                     * laArray[1,1] = 'Obrazac1'
                     * laArray[2,1] = 'Obrazac2'
                     * laArray[3,1] = 'Obrazac3'
                     * laArray[4,1] = 'Obrazac4'
                     * laArray[5,1] = 'Obrazac5'
                     * laArray[6,1] = 'Obrazac6'
                     * laArray[7,1] = 'Obrazac7'
                     * laArray[8,1] = 'Obrazac8'
                     * laArray[9,1] = 'Obrazac9'
                     * laArray[10,1] ='Obrazac10'
                     * laArray[11,1] = 'Obrazac11'
                     * laArray[12,1] = 'Obrazac12'
                     * laArray[13,1] = 'Obrazac13'
                     * laArray[14,1] = 'Obrazac14'
                     * laArray[15,1] = 'Obrazac15'
                     * laArray[16,1] = 'Obrazac16'
                     * laArray[17,1] = 'Obrazac17'
                     * laArray[18,1] = 'Obrazac18'
                     * laArray[19,1] = 'Obrazac19'
                     * laArray[20,1] ='Obrazac20'
                     * laArray[21,1] = 'Obrazac21'
                     * laArray[22,1] = 'Obrazac22'
                     * laArray[23,1] = 'Obrazac23'
                     * laArray[24,1] = 'Obrazac24'
                     * laArray[25,1] = 'Obrazac25'
                     * laArray[26,1] = 'Obrazac26'
                     * laArray[27,1] = 'Obrazac27'
                     * laArray[28,1] = 'Obrazac28'
                     * laArray[29,1] = 'Obrazac29'
                     * laArray[30,1] ='Obrazac30'
                     * ");
                     *  int current_index = -1;
                     *  foreach (var item in mapping.mapping_item) {
                     *      current_index = Int32.Parse(item.pdf_template.ToString().Replace("Obrazac", ""));
                     *      string source_document_path = item.file_path.Replace("@root", template_root_path);
                     *      FileInfo info = new FileInfo(source_document_path);
                     *      string value = string.Format("laArray[{0},2] = '{1}'", current_index, info.Name.Replace(info.Extension,String.Empty));
                     *      b.AppendLine(value);
                     *  }
                     *  File.WriteAllText(fox_helper_path,b.ToString());
                     *
                     * }
                     */
                    if (data.Rows.Count == 0)
                    {
                        Logging.Singleton.WriteDebug("There is no data in the provided data table!");

                        foreach (var template in request.pdf_template_list)
                        {
                            mapping_item_type selected = mapping.mapping_item.Where(p => p.pdf_template == template).First();

                            string source_document_path = selected.file_path.Replace("@root", template_root_path);
                            items_with_path.Add(new Item()
                            {
                                Path = source_document_path, PdfTemplate = template
                            });
                        }
                        if (request.merge_output == true)
                        {
                            string merged_document_path = Path.Combine(output_root_path, String.Format("{0}_{1}{2}", "merged", DateTime.Now.ToFileTimeUtc().ToString(), ".pdf"));

                            PdfMerge merge = new PdfMerge();
                            foreach (var item in items_with_path)
                            {
                                merge.AddDocument(item.Path);
                            }
                            merge.EnablePagination = false;
                            merge.Merge(merged_document_path);
                            string result = Convert.ToBase64String(File.ReadAllBytes(merged_document_path));
                            return(new response_item_type[] { new response_item_type()
                                                              {
                                                                  pdf_template = template.MergedContent, data = force_unc? string.Empty : result, unc_path = merged_document_path
                                                              } });
                        }
                        else
                        {
                            List <response_item_type> items = new List <response_item_type>();
                            foreach (var item in items_with_path)
                            {
                                var temp = new response_item_type()
                                {
                                    pdf_template = item.PdfTemplate, data = force_unc ? string.Empty : Convert.ToBase64String(File.ReadAllBytes(item.Path)), unc_path = item.Path
                                };
                                items.Add(temp);
                            }
                            return(items.ToArray());
                        }
                    }
                    else
                    {
                        DataRow row    = data.Rows[0];
                        string  id_pog = string.Empty;
                        if (data.Columns.Contains("id_pog"))
                        {
                            id_pog = row["id_pog"].ToString();
                        }

                        if (request.debug_mode)
                        {
                            foreach (DataColumn column in data.Columns)
                            {
                                Logging.Singleton.WriteDebugFormat("Data column [{0}] has a value [{1}]", column.ToString(), row[column].ToString());
                            }
                        }

                        foreach (var template in request.pdf_template_list)
                        {
                            mapping_item_type selected = mapping.mapping_item.Where(p => p.pdf_template == template).First();

                            string   source_document_path = selected.file_path.Replace("@root", template_root_path);
                            FileInfo f = new FileInfo(source_document_path);

                            string destination_document_path = Path.Combine(output_root_path,
                                                                            String.Format("{0}_{1}_{2}{3}",
                                                                                          id_pog.Replace("/", "-").Trim(),
                                                                                          f.Name.Replace(f.Extension, ""),
                                                                                          DateTime.Now.ToFileTimeUtc().ToString(),
                                                                                          f.Extension)
                                                                            );

                            items_with_path.Add(new Item()
                            {
                                Path = destination_document_path, PdfTemplate = template
                            });

                            PdfReader reader = new PdfReader(source_document_path);
                            using (PdfStamper stamper = new PdfStamper(reader, new FileStream(destination_document_path, FileMode.Create))) {
                                AcroFields fields = stamper.AcroFields;


                                //Full path to the Unicode Arial file
                                //string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

                                //Create a base font object making sure to specify IDENTITY-H
                                //BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                                //Create a specific font object
                                //Font f = new Font(bf, 12, Font.NORMAL);
                                iTextSharp.text.pdf.BaseFont baseFont = iTextSharp.text.pdf.BaseFont.CreateFont(Path.Combine(fonts_root_path, "arial.ttf"), "Windows-1250", true);

                                fields.AddSubstitutionFont(baseFont);
                                if (request.debug_mode)
                                {
                                    foreach (var key in fields.Fields.Keys)
                                    {
                                        Logging.Singleton.WriteDebugFormat("Pdf field [{0}]. Data type [{1}]", key, fields.GetFieldType(key));
                                    }
                                }

                                foreach (var key in fields.Fields.Keys)
                                {
                                    var items = selected.mapping.Where(p => p.data_field == key);
                                    if (items.Count() == 1)
                                    {
                                        var item = items.First();
                                        if (item.column_name == UNKNOWN)
                                        {
                                            continue;
                                        }
                                        if (data.Columns.Contains(item.column_name))
                                        {
                                            string value = row[item.column_name].ToString();

                                            if (item.field_type == data_field_type.CheckBox)
                                            {
                                                int  int_value     = 0;
                                                bool boolean_value = false;
                                                if (Int32.TryParse(value, out int_value))
                                                {
                                                    value = int_value == 0? "No" : "Yes";
                                                }
                                                else if (Boolean.TryParse(value, out boolean_value))
                                                {
                                                    value = boolean_value == false? "No" : "Yes";
                                                }
                                                else
                                                {
                                                    throw new NotImplementedException(string.Format("Invalid Value [{0}] was provided for Check box type field!", value));
                                                }
                                            }
                                            fields.SetField(key, value);
                                        }
                                        else
                                        {
                                            Logging.Singleton.WriteDebugFormat("Column {0} does not belong to table {1}! Check your mappings for template {2}", item.column_name, data.TableName, template);
                                        }
                                    }
                                    else if (items.Count() == 0)
                                    {
                                        var current = selected.mapping.ToList();

                                        data_field_type field_type = data_field_type.Text;
                                        if (key.Contains("Check"))
                                        {
                                            field_type = data_field_type.CheckBox;
                                        }
                                        else if (key.Contains("Radio"))
                                        {
                                            field_type = data_field_type.RadioButton;
                                        }

                                        current.Add(new mapping_type()
                                        {
                                            column_name = UNKNOWN, data_field = key, field_type = field_type
                                        });

                                        selected.mapping = current.ToArray();

                                        File.WriteAllText(mapping_root_path, mapping.SerializeXml());
                                    }
                                    else
                                    {
                                        throw new NotImplementedException();
                                    }
                                }
                                // flatten form fields and close document
                                if (request.read_only || (request.merge_output && request.pdf_template_list.Length > 1))
                                {
                                    Logging.Singleton.WriteDebugFormat("Form flattening requested... Read only {0}, Merge output {1}, Template list count {2}", request.read_only, request.merge_output, request.pdf_template_list.Length);
                                    stamper.FormFlattening = true;
                                }

                                stamper.Close();
                            }
                        }
                        if (items_with_path.Count() == 1)
                        {
                            string path   = items_with_path.First().Path;
                            var    bytes  = File.ReadAllBytes(path);
                            string result = Convert.ToBase64String(bytes);
                            Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                            return(new response_item_type[] { new response_item_type()
                                                              {
                                                                  pdf_template = items_with_path.First().PdfTemplate, data = force_unc ? string.Empty : result, unc_path = path
                                                              } });
                            //return new response_item_type[] { new response_item_type() { pdf_template = items_with_path.First().PdfTemplate, data = Convert.ToBase64String(new byte[] {1,2,3,4,5,6,7,8,9}) } };
                        }
                        else
                        {
                            if (request.merge_output == true)
                            {
                                string merged_document_path = Path.Combine(output_root_path, String.Format("{0}_{1}{2}{3}", id_pog.Replace("/", "-").Trim(), "merged", DateTime.Now.ToFileTimeUtc().ToString(), ".pdf"));

                                //List<string> file_names = new List<string>();
                                //foreach (var item in items_with_path) {
                                //    file_names.Add(item.Path);
                                //}
                                //var path = MergePdfForms(file_names, merged_document_path);

                                PdfMerge merge = new PdfMerge();
                                foreach (var item in items_with_path)
                                {
                                    merge.AddDocument(item.Path);
                                }



                                merge.EnablePagination = false;
                                merge.Merge(merged_document_path);
                                //using (FileStream file = new FileStream(merged_document_path, FileMode.Create, System.IO.FileAccess.Write)) {
                                //    byte[] bytes = new byte[stream.Length];
                                //    stream.Read(bytes, 0, (int)stream.Length);
                                //    file.Write(bytes, 0, bytes.Length);
                                //    stream.Close();
                                //}

                                var    bytes  = File.ReadAllBytes(merged_document_path);
                                string result = Convert.ToBase64String(bytes);
                                Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                                return(new response_item_type[] { new response_item_type()
                                                                  {
                                                                      pdf_template = template.MergedContent, data = force_unc ? string.Empty : result, unc_path = merged_document_path
                                                                  } });
                            }
                            else
                            {
                                List <response_item_type> items = new List <response_item_type>();
                                foreach (var item in items_with_path)
                                {
                                    var    bytes  = File.ReadAllBytes(item.Path);
                                    string result = Convert.ToBase64String(bytes);
                                    Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                                    var temp = new response_item_type()
                                    {
                                        pdf_template = item.PdfTemplate, data = force_unc ? string.Empty : result, unc_path = item.Path
                                    };
                                    //var temp = new response_item_type() { pdf_template = item.PdfTemplate, data = Convert.ToBase64String(new byte[] {1,2,3,4,5,6,7,8,9}) };
                                    items.Add(temp);
                                }

                                return(items.ToArray());
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    string message = Logging.CreateExceptionMessage(ex);
                    Logging.Singleton.WriteDebug(message);
                    return(null);
                }
            }
        }
Exemplo n.º 22
0
        // Get /GetTime
        public object save()
        {
            string templateFile = "/Users/user/Downloads/1022out.pdf";
            string outFile      = "/Users/user/Downloads/1022out.html";

            //  ConvertPdfStreamToHtml();

            iTextSharp.text.pdf.PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;

            try
            {
                pdfReader = new iTextSharp.text.pdf.PdfReader(templateFile);


                AcroFields pdfFormFields = pdfReader.AcroFields;
                foreach (var item in pdfFormFields.Fields)
                {
                    var d    = item.Value.GetMerged(0);
                    int type = pdfFormFields.GetFieldType(item.Key);


                    //     Console.WriteLine(item.Key+":"+type.ToString);
                    Console.WriteLine("{0},{1}", item.Key, type);

                    if (type == 2)
                    {
                        string[] aaa = pdfFormFields.GetAppearanceStates(item.Key);
                        Console.WriteLine("{0}", string.Join(",", aaa));
                    }


                    //       PrintProperties(item);
                    var str = d.Get(PdfName.V);
                    if (!string.IsNullOrEmpty(str?.ToString()))
                    {
                        var    p = (str.GetBytes()[0] << 8) + str.GetBytes()[1];
                        string code;
                        switch (p)
                        {
                        case 0xefbb:
                            code = "UTF-8";
                            break;

                        case 0xfffe:
                            code = "Unicode";
                            break;

                        case 0xfeff:
                            code = "UTF-16BE";
                            break;

                        default:
                            code = "GBK";
                            break;
                        }
                        var value = Encoding.GetEncoding(code).GetString(str.GetBytes());
                        Console.WriteLine(item.Key + ":" + value);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("" + ex.Message);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
            }



            return(DateTime.Now);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Handles the Click event of the BtnGenerateReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void BtnGenerateReport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtPDFFile.Text))
            {
                _formFields.Clear();

                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (FileStream fs = File.OpenRead(txtPDFFile.Text))
                        {
                            fs.CopyTo(ms);
                        }

                        PdfReader.unethicalreading = true;
                        PdfReader  pdfReader     = new PdfReader(ms.ToArray());
                        AcroFields pdfFormFields = pdfReader.AcroFields;

                        foreach (KeyValuePair <string, AcroFields.Item> kvp in pdfFormFields.Fields)
                        {
                            FormField formField = new FormField
                            {
                                FieldName  = pdfFormFields.GetTranslatedFieldName(kvp.Key),
                                FieldValue = pdfFormFields.GetField(kvp.Key),
                                FieldType  = GetFormFieldType(pdfFormFields.GetFieldType(kvp.Key))
                            };

                            AcroFields.Item field  = pdfFormFields.GetFieldItem(kvp.Key);
                            PdfDictionary   merged = field.GetMerged(0);
                            TextField       fld    = new TextField(null, null, null);
                            pdfFormFields.DecodeGenericDictionary(merged, fld);

                            formField.FontName = GetFontName(fld.Font);
                            string fontSize = (fld.FontSize == 0.0f) ? "Auto" : fld.FontSize.ToString();
                            formField.FontSize = fontSize;

                            List <AcroFields.FieldPosition> fieldPositions = pdfFormFields.GetFieldPositions(kvp.Key).ToList();
                            float pageHeight = pdfReader.GetPageSizeWithRotation(fieldPositions[0].page).Height;
                            formField.FieldPositionTop    = (pageHeight - fieldPositions[0].position.Top);
                            formField.FieldPositionBottom = (pageHeight - fieldPositions[0].position.Bottom);
                            formField.FieldPositionLeft   = fieldPositions[0].position.Left;
                            formField.FieldPositionRight  = fieldPositions[0].position.Right;
                            formField.FieldHeight         = fieldPositions[0].position.Height;
                            formField.FieldWidth          = fieldPositions[0].position.Width;
                            formField.PageNumber          = fieldPositions[0].page;

                            _formFields.Add(formField);
                        }

                        GenerateTreeViewDisplay();
                        pnlSaveOptions.Enabled = true;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was an issue with processing the request. Message: \n\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    pnlSaveOptions.Enabled = pnlSaveOptions.Enabled ? true : false;
                }
            }
        }
Exemplo n.º 24
0
        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog
            {
                Filter       = "PDF files|*.pdf",
                DefaultExt   = "pdf",
                AddExtension = true
            };

            saveFileDialog1.ShowDialog();
            path = saveFileDialog1.FileName;
            Console.Write(JsonData);
            using (PdfStamper stamper = new PdfStamper(pdfForm, new FileStream(path, FileMode.Create)))
            {
                AcroFields fields = stamper.AcroFields;
                // fields.GenerateAppearances = true;
                // String[] checkboxstates = fields.GetAppearanceStates("topmostSubform[0].Page1[0].CheckBox2[0]");


                // set form fields
                foreach (KeyValuePair <string, AcroFields.Item> kvp in fields.Fields)
                {
                    count++;
                    if (formsNtype[count - 1].StartsWith("topmostSubform"))
                    {
                        Console.Write(formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27) + System.Environment.NewLine);
                        currentCheckbox = null;
                        currentItem     = null;
                    }
                    else
                    {
                        Console.Write(formsNtype[count - 1] + System.Environment.NewLine);
                        currentCheckbox = "0";
                        currentItem     = "0";
                    }

                    switch (fields.GetFieldType(kvp.Key))
                    {
                    case AcroFields.FIELD_TYPE_CHECKBOX:
                        currentCheckbox = string.IsNullOrEmpty(currentCheckbox) ? formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27): fields.GetTranslatedFieldName(kvp.Key);
                        //currentCheckbox = fields.GetTranslatedFieldName(kvp.Key);
                        fields.SetField(currentCheckbox, JsonData[currentCheckbox].ToString());
                        break;

                    case AcroFields.FIELD_TYPE_COMBO:
                    case AcroFields.FIELD_TYPE_LIST:
                    case AcroFields.FIELD_TYPE_RADIOBUTTON:
                        String[] radioStates  = fields.GetAppearanceStates("topmostSubform[0].Page1[0].RadioButtonList[0]");
                        string   currentRadio = formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27);
                        fields.SetField(currentRadio, JsonData[currentRadio].ToString());
                        break;

                    case AcroFields.FIELD_TYPE_NONE:
                    case AcroFields.FIELD_TYPE_PUSHBUTTON:
                    case AcroFields.FIELD_TYPE_SIGNATURE:
                    case AcroFields.FIELD_TYPE_TEXT:
                        currentItem = string.IsNullOrEmpty(currentItem) ? formsNtype[count - 1].Substring(27, formsNtype[count - 1].Length - 27): fields.GetTranslatedFieldName(kvp.Key);

                        // currentItem = fields.GetTranslatedFieldName(kvp.Key);
                        fields.SetField(currentItem, JsonData[currentItem].ToString());
                        break;


                        //fields.GenerateAppearances = true;

                        // Console.Write(formsNtype[count - 1] + System.Environment.NewLine);
                    }
                }
                // flatten form fields and close document
                stamper.FormFlattening = true;
                stamper.Close();
            }
        }
Exemplo n.º 25
0
        //Select Pdf
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            PdfReader.unethicalreading = true;
            inputFileName = openFileDialog1.SafeFileName;
            extension     = Path.GetExtension(inputFileName);
            this.PDFPath  = openFileDialog1.FileName;

            if (extension == ".pdf")
            {
                PdfReader  reader = new PdfReader(this.PDFPath);
                AcroFields form   = reader.AcroFields;
                pdfForm = reader;
                // 2. Get the acroform!

                if (pdfForm == null)
                {
                    Console.WriteLine("No form available");
                }
                else
                {
                    try
                    {
                        foreach (KeyValuePair <string, AcroFields.Item> kvp in form.Fields)
                        {
                            switch (form.GetFieldType(kvp.Key))
                            {
                            case AcroFields.FIELD_TYPE_CHECKBOX:
                            //  string translatedCheckboxName = form.GetTranslatedFieldName(kvp.Key);
                            //checkboxCount.Add(translatedCheckboxName);
                            //  break;
                            case AcroFields.FIELD_TYPE_COMBO:
                            case AcroFields.FIELD_TYPE_LIST:
                            case AcroFields.FIELD_TYPE_RADIOBUTTON:
                            case AcroFields.FIELD_TYPE_NONE:
                            case AcroFields.FIELD_TYPE_PUSHBUTTON:
                            case AcroFields.FIELD_TYPE_SIGNATURE:
                            case AcroFields.FIELD_TYPE_TEXT:
                                int    fileType           = form.GetFieldType(kvp.Key);
                                string fieldValue         = form.GetField(kvp.Key);
                                string translatedFileName = form.GetTranslatedFieldName(kvp.Key);
                                formsNtype.Add(translatedFileName);
                                break;
                            }
                        }
                    }
                    catch
                    {
                    }

                    /*finally
                     * {
                     * reader.Close();
                     * }*/
                    Console.WriteLine("Form Selected");
                    // 3. Filling the acroform fields...
                }
            }
            else if (extension == ".XLSX")
            {
                ReadExistingExcel(JsonData);
            }
        }
Exemplo n.º 26
0
        // ---------------------------------------------------------------------------
        public void Write(Stream stream)
        {
            string datasheet = Path.Combine(Utility.ResourcePdf, "datasheet.pdf");

            using (ZipFile zip = new ZipFile())
            {
                // Create a reader to extract info
                PdfReader reader = new PdfReader(datasheet);
                // Get the fields from the reader (read-only!!!)
                AcroFields form = reader.AcroFields;
                reader.Close();
                // Loop over the fields and get info about them
                StringBuilder sb = new StringBuilder();
                foreach (string key in form.Fields.Keys)
                {
                    sb.Append(key);
                    sb.Append(": ");
                    switch (form.GetFieldType(key))
                    {
                    case AcroFields.FIELD_TYPE_CHECKBOX:
                        sb.Append("Checkbox");
                        break;

                    case AcroFields.FIELD_TYPE_COMBO:
                        sb.Append("Combobox");
                        break;

                    case AcroFields.FIELD_TYPE_LIST:
                        sb.Append("List");
                        break;

                    case AcroFields.FIELD_TYPE_NONE:
                        sb.Append("None");
                        break;

                    case AcroFields.FIELD_TYPE_PUSHBUTTON:
                        sb.Append("Pushbutton");
                        break;

                    case AcroFields.FIELD_TYPE_RADIOBUTTON:
                        sb.Append("Radiobutton");
                        break;

                    case AcroFields.FIELD_TYPE_SIGNATURE:
                        sb.Append("Signature");
                        break;

                    case AcroFields.FIELD_TYPE_TEXT:
                        sb.Append("Text");
                        break;

                    default:
                        sb.Append("?");
                        break;
                    }
                    sb.Append(Environment.NewLine);
                }

                // Get possible values for field "CP_1"
                sb.Append("Possible values for CP_1:");
                sb.Append(Environment.NewLine);
                string[] states = form.GetAppearanceStates("CP_1");
                for (int i = 0; i < states.Length; i++)
                {
                    sb.Append(" - ");
                    sb.Append(states[i]);
                    sb.Append(Environment.NewLine);
                }

                // Get possible values for field "category"
                sb.Append("Possible values for category:");
                sb.Append(Environment.NewLine);
                states = form.GetAppearanceStates("category");
                for (int i = 0; i < states.Length - 1; i++)
                {
                    sb.Append(states[i]);
                    sb.Append(", ");
                }
                sb.Append(states[states.Length - 1]);

                zip.AddEntry(RESULT, sb.ToString());
                zip.AddFile(datasheet, "");
                zip.Save(stream);
            }
        }