This script illustrates how to write data to a text file and read the contents of a text file.
First step: write the script
go to the Script Manager, double click on “UserMain” and:
1) add this line to the top of the script:
2) copy/paste all of the following text:
procedure WriteTextToFile(Filename, Contents: String); var T: TStringList; begin T := TStringList.Create; // Sets the contents. T.Text := Contents; // Saves the file. T.SaveToFile(Filename); T.Free; end; procedure WriteText; var S, S2: String; begin // A simple script to test the function. // Finds a name for our text file. // a) Gets the path to the folder where to save the file. S := GetGlobalVar("HEPubStorageLocation", ""); if S = "" then exit; // b) Appends the filename S := IncludeTrailingBackslash(S) + "testfile.txt"; // Then obtains the form contents. S2 := GetFormContents; // Calls our procedure to output a text file. if S2 <> "" then WriteTextToFile(S, S2); end; function OnFormSubmit(Action, Method: String): Boolean; begin // When a form is submitted by the user (HTML Viewer only) WriteText; // Set Result to True if you do not want the viewer to handle the form action itself. Result := False; end;
Be sure to remove the existing OnFormSubmit event and replace it with the one shown above before you continue.
When you submit a form, the HTML viewer will trigger the OnFormSubmit event. As you can see, we call the WriteText procedure: the latter will find a name for the text file (using the global variable “HEPubStorageLocation” which ensures us that we have a folder where we can write files), read the contents of the form thanks to GetFormContents and finally write the contents of the text file.
The WriteTextToFile is a general function that you can use in any of your publication. It uses an internal object TStringList to create the text file.
You can use this general function to get the entire contents of an existing text file:
uses Classes; //Add this to the top of the script function ReadTextFile(Filename: String): String; var T: TStringList; begin T := TStringList.Create; // Loads the text file. T.LoadFromFile(Filename); // Gets the contents. Result := T.Text; T.Free; end;
The TStringList object is an interesting object to manipulate text data and text files: for more information about how to use it, please go to this page: http://www.delphibasics.co.uk/RTL.asp?Name=TStringList
To use the TStringList object, you must define: uses Classes; at the top of your scripts.
Copyright G.D.G. Software 2018. All rights reserved