Change the formatting of a numeric field

PDF forms, Manipulate PDF
6/5/2015

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.

C# code sample

1 using (FileStream file = new FileStream("form.pdf", FileMode.Open, FileAccess.Read)) 2 { 3 string name = "price"; 4 Document document = new Document(file); 5 6 TextField text = document.Fields[name] as TextField; 7 if (null != text) 8 { 9 JavaScriptAction formatAction = text.FormatAction; 10 if (null != formatAction) 11 { 12 Console.WriteLine("Format action of {0}: {1}", name, formatAction.JavaScript.Text); 13 // This writes the following to the console: 14 // Format action of price: AFNumber_Format(2, 0, 0, 0, "", true); 15 16 // change the formatting - first argument is number of decimals 17 formatAction.JavaScript.Text = "AFNumber_Format(0, 0, 0, 0, \"\", true);"; 18 } 19 } 20 21 using (FileStream fileOut = new FileStream("out.pdf", FileMode.Create, FileAccess.Write)) 22 { 23 document.Write(fileOut); 24 } 25 }

VB.NET code sample

1 Using file As New FileStream("..\..\form.pdf", FileMode.Open, FileAccess.Read) 2 Dim name As String = "price" 3 Dim document As New Document(file) 4 5 Dim text As TextField = TryCast(document.Fields(name), TextField) 6 If text IsNot Nothing Then 7 Dim formatAction As JavaScriptAction = text.FormatAction 8 If formatAction IsNot Nothing Then 9 Console.WriteLine("Format action of {0}: {1}", name, formatAction.JavaScript.Text) 10 ' This writes the following to the console: 11 ' Format action of price: AFNumber_Format(2, 0, 0, 0, "", true); 12 13 ' change the formatting - first argument is number of decimals 14 formatAction.JavaScript.Text = "AFNumber_Format(0, 0, 0, 0, """", true);" 15 End If 16 End If 17 18 Using fileOut As New FileStream("..\..\out.pdf", FileMode.Create, FileAccess.Write) 19 document.Write(fileOut) 20 End Using 21 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