PDFtoolkit VCL
Edit, enhance, secure, merge, split, view, print PDF and AcroForms documents
Compatibility
Delphi C++Builder

Form Fields Creation and Processing Using PDFtoolkit v4

It just got simpler.
By V. Subhash

PDFtoolkit components are meant to be used on PDF forms documents that have already been created. (Another product, Gnostice eDocEngine fulfills PDF-creation needs.) For form fields that exist in a PDF document, a class named TgtFormField was used. As our customers wanted the ability to add form fields in PDFtoolkit itself, a new class named TgtPDFFormfield was introduced in Version 2. Over time, this was getting unwieldy and one of them had to go. Thus, in version 4, new and existing form fields are represented by just one class TgtPDFFormfield, as it should be.

Forms Creation

So, how do you create forms now? Well, create a new Delphi VCL Forms project, drop a button and add the button-click event handler in the following example.

unit Create_Form;

{
 Delphi code to create form fields in a PDF document
}


interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls,
  gtPDFDoc, gtExPDFDoc, gtCstPDFDoc, gtPDFUtils;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  gtPDFDocument1: TgtPDFDocument;
  gtPDFFormTextField1: TgtPDFFormTextField;
  gtPDFFormListBox1: TgtPDFFormListBox;
  gtPDFFormPushButton1 {, gtPDFFormPushButton2}: TgtPDFFormPushButton;
begin
  // Create a text box form field
  gtPDFFormTextField1 := TgtPDFFormTextField.Create;
  with gtPDFFormTextField1 do begin
    Rect := gtRect(50,350,150,375);
    FieldName := 'Name';
    Value := 'John Doe';
  end;

  // Create a list box form field
  gtPDFFormListBox1 := TgtPDFFormListBox.Create;
  with gtPDFFormListBox1 do begin
    Rect := gtRect(50,400,150,425);
    FieldName := 'Country';
    AddItem('India');
    AddItem('Russia');
    AddItem('USA');
  end;

  // Create a push button form field
  gtPDFFormPushButton1 := TgtPDFFormPushButton.Create;
  with gtPDFFormPushButton1 do begin
    Rect := gtRect(50,550,150,575);
    FieldName := 'Submit1';
    Value := 'Submit1';
    NormalCaption := 'Submit Form';
    RolloverCaption := 'Submit Form';
    DownCaption := 'Submit Form';
    FormSubmitFormat := fsfHTML;
    SubmitURL := 'http://www.gnostice.com/newsletters/demos/200804/forms_test.asp';
  end;

  // Create a PDF document object
  gtPDFDocument1 := TgtPDFDocument.Create(Nil);
  try
    // Load a PDF document
    gtPDFDocument1.LoadFromFile('Input_Docs\sample_doc1.pdf');
    gtPDFDocument1.OpenAfterSave := True;
    if gtPDFDocument1.IsLoaded then begin
      // Add form fields
      gtPDFDocument1.AddFormField(gtPDFFormTextField1, 1);
      gtPDFDocument1.AddFormField(gtPDFFormPushButton1, 1);
      gtPDFDocument1.AddFormField(gtPDFFormListBox1, 1);
      // Save changed document to another file
      gtPDFDocument1.SaveToFile('Output_Docs\forms_doc1.pdf');
    end;

    // Release IO resources
    gtPDFDocument1.Reset
  except on Err:Exception do begin
      gtPDFDocument1.Reset;
      ShowMessage('Sorry, an exception was raised. ' + Err.Classname + ':' + Err.Message);
    end;
  end;

  Close;
end;

end.

Forms Processing

For enumerating forms fields that already exist in a document, the API is not very different from what users of previous versions used. Use the method TgtPDFDocuemnt.GetFormFieldCount to obtain the total number of form fields in a document. Then, use the following methods to access individual form fields.

public function GetPDFFormField(
    FieldNo: Integer  // Index of the form field in the document
): TgtPDFFormField; overload;

public function GetPDFFormField(
    FieldName: string  // Name of the form field in the document 
): TgtPDFFormField; overload;

These methods returns an TgtPDFFormField instance. You can fill values and modify other properties and save the changes back the same file or to a new file.

Now, here is the example source code for processing form fields in a PDF document. As earlier, add a button to a VCL forms application and use the click-event handler.

unit Read_Form;

{
 Delphi code to read all form fields in a PDF document
}

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtDlgs, TypInfo,
  gtPDFDoc, gtExPDFDoc, Grids, gtCstPDFDoc, gtClasses3, gtCstDocEng,
  gtCstPlnEng, gtCstPDFEng, gtExPDFEng, gtPDFEng, gtPDFClasses, gtExProPDFDoc;

type
  TForm2 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
var
  gtPDFDocument1: TgtPDFDocument;
  OpenTextFileDialog1: TOpenTextFileDialog;
  I, N: Integer;
  FieldName: string;
  StringGrid1: TStringGrid;
begin
  // Create PDF document, file dialog, string grid objects
  gtPDFDocument1 := TgtPDFDocument.Create(nil);
  OpenTextFileDialog1 := TOpenTextFileDialog.Create(nil);
  StringGrid1 := TStringGrid.Create(Self);

  // Specify string grid settings
  StringGrid1.RowCount := 2;
  StringGrid1.ColCount := 4;
  StringGrid1.Cells[0,0] := 'Field Name';
  StringGrid1.Cells[1,0] := 'Type';
  StringGrid1.Cells[2,0] := 'Page Number';
  StringGrid1.Cells[3,0] := 'FieldValue';
  StringGrid1.ColWidths[0] := 75;
  StringGrid1.ColWidths[1] := 75;
  StringGrid1.ColWidths[2] := 75;
  StringGrid1.ColWidths[3] := 200;
  StringGrid1.Width := 480;
  StringGrid1.Height := 300;

  // Make user to select a PDF file
  OpenTextFileDialog1.Filter := 'PDF documents (*.pdf)|*.pdf';;
  if OpenTextFileDialog1.Execute then begin
    try
      // Unload any previously loaded file
      if gtPDFDocument1.IsLoaded then begin
        gtPDFDocument1.Reset;
      end;

      gtPDFDocument1.LoadFromFile(OpenTextFileDialog1.FileName);

      // Enumerate form fields in the document
      n := gtPDFDocument1.GetFormFieldCount;
      if (gtPDFDocument1.GetFormFieldCount > 0) then begin
        // Add the string grid to the form
        StringGrid1.Parent := Self;
        StringGrid1.RowCount := N + 1;
        StringGrid1.Top := Button1.Top + Button1.Height + 30;
        StringGrid1.Left := Button1.Left;

        // Iterate through existing form fields
        for I := 1 to N do begin
          // Display form field name
          StringGrid1.Cells[0,I] := gtPDFDocument1.GetPDFFormField(I).FieldName;
          // Display form field type
          StringGrid1.Cells[1,I] := GetEnumName(TypeInfo(TgtPDFFormFieldType),
                                                integer(gtPDFDocument1.GetPDFFormField(I).FieldType));
          // Display page number of the form field
          StringGrid1.Cells[2,I] :=
              IntToStr(gtPDFDocument1.GetPDFFormField(I).PageNum);

          // Display form field value
          StringGrid1.Cells[3,I] := gtPDFDocument1.GetPDFFormField(I).Value; // catch all
          case gtPDFDocument1.GetPDFFormField(I).FieldType of // special cases
            ftCheckBox:  // check box form field
              if TgtPDFFormCheckBox(gtPDFDocument1.GetPDFFormField(I)).Checked then begin
                StringGrid1.Cells[3,I] := '[Checked]';
              end else begin
                StringGrid1.Cells[3,I] := '[Not Checked]';
              end;
            ftButton: // push button form field
              StringGrid1.Cells[3,I] :=
                  '[Caption] ' +
                  TgtPDFFormPushButton(gtPDFDocument1.GetPDFFormField(I)).NormalCaption;
          end;
        end;
      end else begin
        ShowMessage('No form fields were found.');
      end;
      // Free IO resources
      gtPDFDocument1.Reset;
    except on Err:Exception
      do begin
        gtPDFDocument1.Reset;
        ShowMessage('Sorry, an exception was raised. ' + Err.Classname + ':' + Err.Message);
      end;
    end;
  end;
end;

end.

---o0O0o---

Our .NET Developer Tools
XtremeDocumentStudio .NET

Multi-format document-processing component suite for .NET developers.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

Our Delphi/C++Builder developer tools
XtremeDocumentStudio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

Our Java developer tools
XtremeDocumentStudio (for Java)

Multi-format document-processing component suite for Java developers.

PDFOne (for Java)

A Java PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java applications.

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

Privacy | Legal | Feedback | Newsletter | Blog | Resellers © 2002-2017 Gnostice Information Technologies Private Limited. All rights reserved.