Products
PDFControls.NET 2.0 PDFKit.NET 4.0
Created
6/5/2015
Tags
Manipulate PDF PDF forms

The format of a numeric field is determined by the JavaScript format action of the field. This code sample changes the format by changing the JavaScript of the action.

The format action uses the JavaScript method AFNumber_Format which is a built-in method supported by all major PDF readers. The first argument spcecifies the number of decimals. In this code sample, the original document uses 2 decimals and the new document uses no decimals.

using (FileStream file = new FileStream("form.pdf", FileMode.Open, FileAccess.Read))
{
    string name = "price";
    Document document = new Document(file);
                
    TextField text = document.Fields[name] as TextField;
    if (null != text)
    {
        JavaScriptAction formatAction = text.FormatAction;
        if (null != formatAction)
        {
            Console.WriteLine("Format action of {0}: {1}", name, formatAction.JavaScript.Text);
            // This writes the following to the console:
            // Format action of price: AFNumber_Format(2, 0, 0, 0, "", true);

            // change the formatting - first argument is number of decimals
            formatAction.JavaScript.Text = "AFNumber_Format(0, 0, 0, 0, \"\", true);";
        }
    }

    using (FileStream fileOut = new FileStream("out.pdf", FileMode.Create, FileAccess.Write))
    {
        document.Write(fileOut);
    }                
}
Using file As New FileStream("..\..\form.pdf", FileMode.Open, FileAccess.Read)
    Dim name As String = "price"
    Dim document As New Document(file)

    Dim text As TextField = TryCast(document.Fields(name), TextField)
    If text IsNot Nothing Then
        Dim formatAction As JavaScriptAction = text.FormatAction
        If formatAction IsNot Nothing Then
            Console.WriteLine("Format action of {0}: {1}", name, formatAction.JavaScript.Text)
            ' This writes the following to the console:
            ' Format action of price: AFNumber_Format(2, 0, 0, 0, "", true);

            ' change the formatting - first argument is number of decimals
            formatAction.JavaScript.Text = "AFNumber_Format(0, 0, 0, 0, """", true);"
        End If
    End If

    Using fileOut As New FileStream("..\..\out.pdf", FileMode.Create, FileAccess.Write)
        document.Write(fileOut)
    End Using
End Using

What happens in this sample is shown in the following image; when entering the value "-32326545.1556651" it is formatted red in the original PDF and shows two decimals seperated by a period symbol. In the new format the number is black, has no decimals and thousands are seperated by ','-characters.

PDF-change-numeric-field-format.png