Sign in Join
Wiki copytemporary

LazReport Tutorial: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Overview
22
33This page started as a translation of the Portuguese language [[LazReport Tutorial/pt|Tutorial de LazReport]] (which itself appears to be a translation from a French document). It was updated for LazReport (instead of FastReport) on Lazarus (instead of Delphi), using T*Connection instead of a DBase table.
44
55## Starting with LazReport
66
77We're going to use a demo database which is provided by Delphi (DBDEMOS). You'll need to create a new application with a main form *Form1*.
88
99We're assuming you already have your database set up as specified in [[SQLdb Tutorial0]]. If not, please do so.
1010
1111### Setting up your form
1212
1313Place the following components on the form:
1414
1515- A T*Connection, e.g. TIBConnection:
1616 - DatabaseName := your database, e.g. C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\EMPLOYEE.FDB
1717 - UserName, Password, HostName: as appropriatie (e.g. SYSDBA,password,\<none\> for Firebird embedded)
1818 - Transaction: TSQLTransaction1
1919- TSQLTransaction
2020- TSQLQuery:
2121 - Database := IBConnection1
2222 - Active: true
2323 - SQL: select * from employee
2424- TDataSource
2525 - DataSource1.DataSet := SQLQuery1
2626- TfrDBDataSet
2727 - frDbDataSet.DataSource := DataSource1
2828- TfrReport
2929- TfrDesigner
3030- 2 TButton
3131- Button1.Caption := 'Editing'
3232- Button2.Caption := 'Preview'
3333
3434This results in:
3535
3636![](/wiki-images/4/4f/Lazreptut01.png)
3737
3838Double-click on the **TfrReport** icon (or right-click, Design Report) to bring up the report designer:
3939
4040![](/wiki-images/6/6a/Lazreptut01b.png)
4141
4242### Setting up variables
4343
4444LazReport lets you link variable names to database fields or system values, in order to spare your end users from having to decipher cryptic field names. In our example, we're going to create a variable for our database fields FIRST_NAME, LAST_NAME etc.
4545
4646In the File menu, click **Variables list**. Now you get an overview of the defined variables:
4747
4848![](/wiki-images/d/d9/Lazreptutvariableseditor.png)
4949
5050Click on the button **Variables** in order to define some variables. Write the contents according ot the following image. "Demo Variables" represents a category and the other entries (xxx field) represent variables. To differentiate the two, the variables start with a space.
5151
5252**Note**. The distinction between variables and variables categories by starting variables with a space is needed unique and exclusively in this dialog (**Variables List**). Anywhere else (Report Designer, main source code and scripts) a variable should be invoked without spaces.
5353
5454![](/wiki-images/8/86/Lazreptutdefinevariables.png)
5555
5656Finally click on OK to confirm your entries, and you'll see this:
5757
5858![](/wiki-images/f/ff/Lazreptutvariablesdefined.png)
5959
6060As you can see, the category we defined is shown in the ComboBox above the variables. Each variable must be linked with a field. To do this, select the variable and then the field. Do this for all variables; the screenshot shows the link for Hire date:
6161
6262![](/wiki-images/b/b6/Lazreptutvarhiredatetofield.png)
6363
6464### Objects and bands
6565
6666After closing the variables editor, we're back in our report designer. You may have noticed a small number of objects in the object bar to the left of the report surface. These are:
6767
6868- the mouse icon pointer
6969- rectangle object
7070- band
7171- picture object
7272- subreport
7373- draw lines
7474- insert barcode object
7575
7676![](/wiki-images/6/6a/Lazreptut01b.png)
7777
7878Click the band icon, go to the report surface, and click on it to drop a band object.
7979
8080![](/wiki-images/2/29/Lazreptutinsertnewband.png)
8181
8282You must click on the type of band you want to create. Select **Report title** and click OK.
8383
8484| Band type | Use |
8585|----|----|
8686| Report title | Shown only on the first page |
8787| Report summary | Shown only on the last page |
8888| Page header | Shown at the top of each page |
8989| Page footer | Shown at the bottomof each page |
9090| Master header | Shown at the beginning of the first detail band/level |
9191| Master data | First detail level data; repeated for each record in dataset |
9292| Master footer | Shown at the end of the first detail band/level |
9393| Detail header | Shown at the beginning of the second detail band/level |
9494| Detail data | Second detail level data |
9595| Detail footer | Shown at the end of the second detail band/level |
9696| Subdetail header | Shown at the beginning of the third detail band/level |
9797| Subdetail data | Third detail level data |
9898| Subdetail footer | Shown at the end of the third detail band/level |
9999| Overlay | Shown once on each page lower layer |
100100| Column header | Shown at the top of every column |
101101| Column footer | Shown at the bottom of every column |
102102| Group header | Shown at the top of every group |
103103| Group footer | Shown at the bottom of every group |
104104| Cross header | Shown at the top of cross tables/pivot tables |
105105| Cross data | Shows cross tables/pivot table data |
106106| Cross footer | Shown at the bottom of cross tables/pivot tables |
107107
108108### Report title
109109
110110In the Report title band, add a rectangle. The text editor will show up. In the first line the title of the report should be indicated. On the the second, system date and time need to be added. They are obtained by clicking **Variable** and then Category **Other**, then double-click on the desired variable (once you are familiar with the variables, you can also just type them). Now we have:
111111
112112![](/wiki-images/a/ad/Lazreptutreporttitle.png)
113113
114114Click OK to exit the editor, then adjust the title rectangle to the desired size. Choose a color for the background with the Bucket Fill button on the toolbar.
115115
116116### The main event: showing data in the master data band
117117
118118Let's insert a master data band. LazReport prompts you for a data source; choose **frDBDataSet1**, the main data source for our example. The master band will be repeated for each record in the data source. You can double-click later on the band if you want to change the data source.
119119
120120![](/wiki-images/b/b7/Lazreptutbanddatasource.png)
121121
122122In the left half of the band we insert a rectangle and double click. The familiar text editor appears.
123123
124124Now we will add several fields in the one rectangle. If needed though, you can use one rectangle per field if you want to apply different formatting etc.
125125
126126The first line **Name** \[Full name field\] is obtained by writing Name and then, with the **Variable** button, entering the variable \[Field Name\]. Alternatively, as indicated before, you can write the resulting text directly.
127127
128128The next line **Salary** \[Salary field\] is written similarly.
129129
130130The third line - Salary divided by job grade \[\[Salary field\]/\[Job grade field\]\] - is done likewise. This shows you can perform calculations with fields coming from the data source. Note the extra set of square brackets around the calculation. As you may guess, you can not only use the variables listed via the **Variable** button, but also database fields via **DB Field**.
131131
132132![](/wiki-images/6/6a/Lazreptutmasterdata.png)
133133
134134You can use all kinds of operators and functions in your calculations; see [[LazReport Documentation|LazReport Documentation#Documentation]] for an overview.
135135
136136#### Formatting output
137137
138138You can control how the text in the rectangles is displayed.
139139
140140Let's first add a new rectangle with the *Hire date field* variable.
141141
142142In the variable editor, let's set a format. A format is valid for all variables of a rectangle/object. To show the format editor, double click on a rectangle to get the Text Editor, then click the *Format* button.
143143
144144Let's set the date format you want here:
145145
146146![](/wiki-images/1/12/Lazreptutformattingdate.png)
147147
148148The first ComboBox indicates the type of data (text, numeric, date, time, logical/boolean). The second lets you select a preset format.... with some obvious restrictions:
149149
150150- The Text type does not allow any Number type formatting.
151151- The Number type requires a number of any type (Integer, Double, Currency...).
152152- The Date type: you can choose a pre-defined format or write a custom format like MM/DD/YY for example.
153153
154154Except for Text and Logic types, you can use the formatting strings you also use in Lazarus.
155155
156156Other formatting options are present on the button bar below the menu (e.g. bold, italic, highlighting).
157157
158158Highlighting is very useful for emphasizing data. You can specify a condition that determines when highlighting is applied.
159159
160160For that, use the keyword Value to indicate the value of the variable. Here is the highlighting for all hire dates later than 1989. Because Hire date is a TDateTime field (which internally is a float), I cheated by just using the float value of January 1st, 1990 which is 32874. By default highlighter is a simple bold on white background. You can set these parameters to an area by clicking the Highlight button.
161161
162162![](/wiki-images/d/df/Lazreptutconditionalhighlight.png)
163163
164164#### A picture is worth...
165165
166166If you haven't already, we'll need to add a PHOTO field to our test database; using an SQL statement like this (note: unfortunately different databases use different syntax; BLOB can be CLOB,IMAGE,OLE...):
167167
168-`ALTER TABLE EMPLOYEE ADD PHOTO BLOB;`
168+```text
169+ALTER TABLE EMPLOYEE ADD PHOTO BLOB;
170+```
169171
170172Now add some test data - the example here uses jpg files - into the PHOTO field with your favourite database tool. Note: this is the way Delphi DBImage works: just binary blobs with image data. By default, Lazarus DBImage is more flexible and stores the file extension before the image data, allowing different file formats to be used. For simplicity's sake, we'll use the Delphi approach.
171173
172174> **Note:** For this "DBImage BLOB without file extension info" to work, you'll need the patch from issue 25453/at least revision ... of LazReport
173175
174176Now we have to tell the report you need to treat all data as binary jpg image files. Click on frReport1, go to Object Inspector, events and initiates a procedure OnDBImageReader:
175177
176178```delphi
177179procedure TForm1.frReport1DBImageRead(Sender: TObject; S: TStream;
178180 var GraphExt: string);
179181begin
180182 // Force TDBImage to Delphi compatible behaviour: únicamente acepta un formato de fichero, e.g. jpg
181183 // esto significa que los BLOBs de la base de datos deben ser justamente ficheros jpg binarios sin más datos.
182184 GraphExt:='jpg';
183185end;
184186```
185187
186188In File\>Variables List, add the SQLQuery1.PHOTO field as variable Photo field, similarly to how you did this before. If you don't see the field, you may need to set the form's SQLQuery to inactive and active again to refresh the list of columns.
187189
188190Click on the Insert image... icon on the left of the window; now click on the right side of the band to drop the image control. A Picture editor shows up:
189191
190192![](/wiki-images/4/48/Lazreptutpictureeditor.png)
191193
192194If you wanted to always show the same picture, you'd just need to click Load ... (or double click on the picture control) and choose your image.
193195
194196However, let's press the Memo button and insert your Photo variable:
195197
196198![](/wiki-images/5/56/Lazreptutphotofield.png)
197199
198200This turns the picture into an object associated with the data field. Press OK as needed to get back to the report designer.
199201
200202Adjust height and width as needed.
201203
202204You can also press F11 to show the Object Inspector which allows you to edit more if needed:
203205
204206![](/wiki-images/b/b1/Lazreptutobjectinspector.png)
205207
206208Close the report editor and save the report definition (with the same name, **lazreporttutorial.lrf**).
207209
208210If you go to File\>Preview, you'll see your report includes the images.
209211
210212Close the report editor and save the report definition as **lazreporttutorial.lrf**.
211213
212214### Detail data
213215
214216To do: show how to use the detail part of master/detail. see e.g. sample in components/lazreport/samples/editor directory; see the button title "Master-Detail" **Please write me.**
215217
216218### Loading the report from the form
217219
218220Now let's write the code required to load and view or edit our report. To this add the following code to the project:
219221
220222```delphi
221223TForm1.Button2Click(Sender procedure: TObject);
222224begin
223225 frReport1.LoadFromFile('lazreporttutorial.lrf');
224226 frReport1.ShowReport;
225227end;
226228TForm1.ButtonClick(Sender procedure: TObject);
227229begin
228230 frReport1.LoadFromFile('lazreporttutorial.lrf');
229231 frReport1.DesignReport;
230232end;
231233```
232234
233235You have a preview option that gives end users a way to modify the report without changing the basic application.
234236
235237### Printing
236238
237239Now we're going to add features to our basic example.
238240
239241Add a TButton component with Caption := 'Print...', and a TPrintDialog. Behind the scenes, a project dependency on the **Printer4Lazarus** packages will be added by the IDE, so make sure that package is installed.
240242
241243We end up with this:
242244
243245![](/wiki-images/e/e3/Lazreptutformwithprintbutton.png)
244246
245247Now add the **printers** unit to your form's uses clauses.
246248
247249Put the following code in the OnClick event of the **Print** button:
248250
249251```delphi
250252procedure TForm1.Button3Click(Sender: TObject);
251253var
252254 FromPage, ToPage, NumberCopies: Integer;
253255 ind: Integer;
254256 Collap: Boolean;
255257begin
256258 // Load report definition from application directory
257259 AppDirectory:=ExtractFilePath(ParamStr(0));
258260 frReport1.LoadFromFile('lazreporttutorial.lrf');
259261 // Need to keep track of which printer was originally selected to check for user changes
260262 ind:= Printer.PrinterIndex;
261263 // Prepare the report and just stop if we hit an error as continuing makes no sense
262264 if not frReport1.PrepareReport then Exit;
263265 // Set up dialog with some sensible defaults which user can change
264266 with PrintDialog1 do
265267 begin
266268 Options:=[poPageNums ]; // allows selecting pages/page numbers
267269 Copies:=1;
268270 Collate:=true; // ordened copies
269271 FromPage:=1; // start page
270272 ToPage:=frReport1.EMFPages.Count; // last page
271273 MaxPage:=frReport1.EMFPages.Count; // maximum allowed number of pages
272274 if Execute then // show dialog; if succesful, process user feedback
273275 begin
274276 if (Printer.PrinterIndex <> ind ) // verify if selected printer has changed
275277 or frReport1.CanRebuild // ... only makes sense if we can reformat the report
276278 or frReport1.ChangePrinter(ind, Printer.PrinterIndex) //... then change printer
277279 then
278280 frReport1.PrepareReport //... and reformat for new printer
279281 else
280282 exit; // we couldn't honour the printer change
281283
282284 if PrintDialog1.PrintRange = prPageNums then // user made page range selection
283285 begin
284286 FromPage:=PrintDialog1.FromPage; // first page
285287 ToPage:=PrintDialog1.ToPage; // last page
286288 end;
287289 NumberCopies:=PrintDialog1.Copies; // number of copies
288290 // Print the report using the supplied pages & copies
289291 frReport1.PrintPreparedReport(inttostr(FromPage)+'-'+inttostr(ToPage), NumberCopies);
290292 end;
291293 end;
292294end;
293295```
294296
295297It's a bit long, but if needed, you can create a descendant of TfrReport with an easier printing method or class , create a PrintReport (Report: string) procedure to load the report and print.
296298
297299When double clicking on **frReport1**, in the report designer File\>Page Options menu you get this:
298300
299301Select paper size:
300302
301303![](/wiki-images/9/90/Lazreptutpapersize.png)
302304
303305Choose desired margins, number of columns, and the space between them, layout order etc. ![](/wiki-images/4/4a/Lazreptutprintoptions.png)
304306
305307### Report options
306308
307309Via File\>Report Options you can set a default printer that will be used for the report (using the "Select when report loaded" checkbox).
308310
309311If you want to include the total number of pages with the page number on each page, you need to select **Two-pass report** (which tells Lazreport to build the report twice, inserting total number of pages on the second run).
310312
311313![](/wiki-images/2/2e/Lazreptutreportoptions.png)
312314
313315On the **Other** tab, you can fill out some report metadata, as is done on the screenshot below: ![](/wiki-images/f/f6/Lazreptutreportoptionsother.png)
314316
315317### General purpose variables
316318
317319Now we'll add some report variables unrelated to the database data in our example. They let you e.g. show different names according to the context.
318320
319321To do this, open the report editor and select the File menu and the Variable List. Add a Test category, and a test1 variable the same way we did earlier (with a space before the variable name):
320322
321323![](/wiki-images/8/8d/Lazreptutvariableseditortestvar.png)
322324
323325The only difference is that you will not select a value field, but leave None (the default value): ![](/wiki-images/2/20/Lazreptutvariabletest.png)
324326
325327Return to Lazarus (do not forget to save your report, if necessary) and set up the **OnGetValue'' event of the**frReport1''' component by adding the following code:
326328
327329```delphi
328330procedure TForm1.frReport1GetValue(const ParName: String; var ParValue: Variant
329331 );
330332begin
331333 // Conditionally assign value:
332334 if ParName='test1' then
333335 ParValue:='Answer: Variable "test1"'; //perhaps replace with a call to a random function or something?
334336end;
335337```
336338
337339Alternatively, you can also pass the value directly to the variable using the following code:
338340
339341```delphi
340342procedure TForm1.Button1Click(Sender:TObject);
341343begin
342344 frReport1.Values.FindVariable('test').Field := QuotedStr('test1');
343345 frReport1.ShowReport;
344346end;
345347```
346348
347349## See also
348350
349351- [[LazReport Tutorial/pt|Tutorial de LazReport]] Version used as a basis for this translation.
350352- [[LazReport Documentation]]
351353
352354---
353355*From the Free Pascal wiki, page "LazReport Tutorial", as it stood on 2020-04-02 after a change by Volkir, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
354356Category: LazReport
355357Category: Lazarus
356358Category: Tutorials

Back to history