Search code examples
c#pdfitextpdf-generationitext7

Set Combobox value is adding weird characters... (C#)


I am using iText7 for a project. We need to export data to a PDF programmatically.

It is working fine for simple textfields, textareas and for checkboxes. But is it doing weird stuff when we are trying to set values onto dropdownlist (combobox).

Foreach of the above combobox, the options are : Critique; Important; Modéré; Faible;

Here is the code inside a self alone program.cs file :

using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;

public class Program
{
    public static readonly string CHECKED_STATE_VALUE = "Yes";
    public static readonly string UNCHECKED_STATE_VALUE = "Off";

    private static void ConsoleOutFieldData(PdfFormField field)
    {
        Console.WriteLine(field.GetFieldName() + ": " + field.GetValue());
    }

    private static void Main(string[] args)
    {
        PdfReader reader = new PdfReader(@"C:\code-test\CERTAQ-FORM-17-001-Declaration_d_incident.pdf");
        PdfWriter writer = new PdfWriter(@"C:\code-test\test1.pdf");

        PdfDocument pdfDoc = new PdfDocument(reader, writer);
        PdfAcroForm? form = PdfAcroForm.GetAcroForm(pdfDoc, true);
        var fields = form.GetFormFields();

        Console.WriteLine("Before :");
        ConsoleOutFieldData(form.GetField("cbImpactA"));
        ConsoleOutFieldData(form.GetField("cbImpactB"));
        ConsoleOutFieldData(form.GetField("cbImpactC"));
        ConsoleOutFieldData(form.GetField("cbImpactD"));

        // Combobox
        form.GetField("cbImpactA").SetValue("Critique");
        form.GetField("cbImpactB").SetValue("Modéré");
        form.GetField("cbImpactC").SetValue("Important");
        form.GetField("cbImpactD").SetValue("Faible");

        Console.WriteLine("After :");
        ConsoleOutFieldData(form.GetField("cbImpactA"));
        ConsoleOutFieldData(form.GetField("cbImpactB"));
        ConsoleOutFieldData(form.GetField("cbImpactC"));
        ConsoleOutFieldData(form.GetField("cbImpactD"));

        // Rendre les champs non modifiables.
        form.FlattenFields();
        pdfDoc.Close();
    }
}

Here is the result into the console and on the PDF output :

Before :
cbImpactA: Modéré
cbImpactB: Critique
cbImpactC: Faible
cbImpactD: Important
After :
cbImpactA: þÿCritique
cbImpactB: þÿModéré
cbImpactC: þÿImportant
cbImpactD: þÿFaible

On the PDF Output you can see that the values seem to contain new line character. PDF Screenshot

What did I do wrong?


Solution

  • Thanks to @K J helping me to find the problem.

    Here is what I did to fix my problem : I removed the 4 dropdown fields from the form then I recreated them. I used DocFly to edit my PDF for FREE.

    Look at the results now :)

    enter image description here

    enter image description here