Sign in Join
Wiki copytemporary

FPReport Usage: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: FPReport Usage

OldNewLine
1+On this page we'll dissect how to create a simple report in code. As a starting point, we take the dataset demo report from the Free Pascal demo application.
2+
3+## Owners & Parent-Child structure
4+
5+All report elements (pages, bands, printable elements) are TComponent descendents. They are organised in a parent-child relation:
6+
7+- The pages are children of the report
8+- The bands are children of a page
9+- The printable elements are children of a band.
10+
11+The owner (as in TComponent) of the various elements is not important for the report structure, but if the owner is the natural parent of a newly created component, then the parent will be set automatically.
12+
13+## Creating the report
14+
15+Most fpReport related classes are defined in a single unit, the **fpreport** unit. So make sure you add that to your uses clause.
16+
17+``` pascal
18+uses
19+ SysUtils
20+ ,fpreport // for most FPReport classes
21+ ,dbf // for TDBF (database) access
22+ ,fpreportdb // for the TFPReportDatasetData class
23+ ,fpttf // for access to gTTFontCache singleton
24+ {$IFDEF ExportPDF}
25+ ,fpreportpdfexport // for access to the PDF Report exporter class
26+ {$ENDIF}
27+ {$IFDEF ExportAggPas}
28+ ,fpreport_export_aggpas // for access to fpGUI's fpReport AggPas exporter class
29+ {$ENDIF}
30+ {$IFDEF ExportFPImage}
31+ ,fpreportfpimageexport // for access to the FPImage exporter class
32+ {$ENDIF}
33+ ;
34+```
35+
36+Everything starts with a report component:
37+
38+``` pascal
39+PaperManager.RegisterStandardSizes; // register paper types for fpReport
40+rpt := TFPReport.Create(nil); // if your Application object is a TComponent decendant, use Self instead of nil.
41+rpt.Author := 'Graeme Geldenhuys';
42+rpt.Title := 'FPReport Demo 8 - Datasets';
43+```
44+
45+The **Author** and **Title** properties can be used in expressions in the report.
46+
47+### Providing data to the report
48+
49+Every report needs a data loop to be able to render itself. The data loop is a descendent of **TFPReportData**, there exist several pre-defined data loops.
50+
51+One of the possible data loops is based on a dataset, **TFPReportDatasetData** - defined in the **fpreportdb** unit, so remember to add that to your uses clause. It has a **Dataset** property which must be set to the dataset that provides the data to the report. The loop will run over all records in the dataset, and all fields in the dataset will be available for use in expressions used in the report.
52+
53+The following code creates a data loop component, and assigns a **TDBF** dataset to it. Note that the TDBF class is defined in the **dbf** unit.
54+
55+``` pascal
56+var
57+ lDataSet: TDBF;
58+ lReportData: TFPReportDatasetData;
59+begin
60+ lReportData := TFPReportDatasetData.Create(nil); // Same as previous code example. Use Self
61+ lDataSet := TDBF.Create(nil); // or Nil, depending on your Application object.
62+ lDataSet.TableName := 'test.dbf';
63+ lReportData.DataSet := lDataSet;
64+```
65+
66+The **lReportData** component can then be used in the report structure.
67+
68+### Adding a page
69+
70+Every report needs at least one page.
71+
72+The following page is owned by the report, so it will be added automatically to the pages of the report. Once created, a page size must be set (a set of standard sizes is available), this is done through the PageSize.PaperName property. If the name is known to the global paper manager factory, then the sizes will be set automatically from the name.
73+
74+``` pascal
75+p := TFPReportPage.Create(rpt);
76+p.Orientation := poPortrait;
77+p.PageSize.PaperName := 'A4';
78+```
79+
80+After the page name was set, the margins can be set. The measurements are in millimeter:
81+
82+``` pascal
83+{ page margins }
84+p.Margins.Left := 30;
85+p.Margins.Top := 20;
86+p.Margins.Right := 30;
87+p.Margins.Bottom := 20;
88+```
89+
90+A page can have a font. This font is then used as the default for all the bands on the page. Likewise, all elements on a band will use the font of the band by default. Note that the font name is the PostScript name of a TTF font file.
91+
92+``` pascal
93+p.Font.Name := 'LiberationSans';
94+```
95+
96+When the report must be rendered, the layouting engine will run the data loop of the page, and repeat the page as often as is needed to fit the data.
97+
98+Therefor, a page must have a data loop associated with it.
99+
100+``` pascal
101+p.Data := lReportData;
102+```
103+
104+### Adding bands to a page
105+
106+Now, the page must be filled with some content. This means adding several bands to the report page.
107+
108+A report title will be printed once, at the start of the report:
109+
110+``` pascal
111+TitleBand := TFPReportTitleBand.Create(p);
112+TitleBand.Layout.Height := 40;
113+```
114+
115+The width of the band must not be set, it is calculated automatically from the page width, the number of columns and the margins of the page.
116+
117+A band by itself is not very useful, it serves only as a placeholder for some printable elements.
118+
119+For the title page, we'll add a simple static text as the page title. All text (dynamic or static) must be added using a **TFPReportMemo** component:
120+
121+``` pascal
122+ Memo := TFPReportMemo.Create(TitleBand);
123+ Memo.Layout.Left := 5;
124+ Memo.Layout.Top := 0;
125+ Memo.Layout.Width := 140;
126+ Memo.Layout.Height := 15;
127+```
128+
129+The layout of the memo is relative to the band, and determines where the memo will be positioned.
130+
131+The text of the memo, and the internal formatting can be specified using the **Text** and **TextAlignment** properties:
132+
133+``` pascal
134+ Memo.Text := 'Dataset Demo';
135+ Memo.TextAlignment.Vertical := tlCenter;
136+ Memo.TextAlignment.Horizontal := taCentered;
137+```
138+
139+Finally, the font and font size can be set:
140+
141+``` pascal
142+ Memo.UseParentFont := False;
143+ Memo.Font.Color := TFPReportColor($000080);
144+ Memo.Font.Size := 24;
145+```
146+
147+The color is a RRGGBB value (Red/Green/Blue). Alpha channel support is not yet available. Several pre-defined values are defined in the FPReport unit.
148+
149+### The loop data
150+
151+The report title is printed only once, but normally a report will have a band that is printed for each record in the report loop. For this, a data band (**TFPReportDataBand**) must be added to the report:
152+
153+``` pascal
154+DataBand := TFPReportDataBand.Create(p);
155+DataBand.Layout.Height := 30;
156+DataBand.Data:= lReportData;
157+```
158+
159+This band will be repeated for every record in the data loop.
160+
161+As noted above, any text must be printed with a memo. This is also true for data from the data loop. The following memo will print the name field from the dataset, prepended with the literal text **"Name: "**
162+
163+``` pascal
164+ Memo := TFPReportMemo.Create(DataBand);
165+ Memo.Layout.Left := 30;
166+ Memo.Layout.Top := 0;
167+ Memo.Layout.Width := 50;
168+ Memo.Layout.Height := 5;
169+ Memo.Text := 'Name: [name]';
170+```
171+
172+### Expressions
173+
174+Dynamic text is obtained by intermixing static text and expressions.
175+
176+The expressions are anything that is between square brackets **\[\]**.
177+
178+The **TFPExpressionParser** expression engine is used to calculate the data.
179+
180+That means that Expressions are much like Pascal expressions. An expression:
181+
182+- Is typed (string, integer, float, datetime)
183+- can contain calculations on these types.
184+- can contain report variables
185+- can use data fields from the report data
186+- Can use any of the pre-defined functions available from fpexprpars.
187+
188+#### Builtin Variables
189+
190+This variables are builtin in fpreport and are always defined
191+
192+- **\[TODAY\]**
193+- **\[AUTHOR\]**
194+- **\[TITLE\]**
195+
196+#### Builtin Expressions
197+
198+This expression are builtin in fpreport and are always defined
199+
200+- **\[RecNo\]**
201+- **\[PageNo\]** Actual pagenumber
202+- **\[PageCount\]** Maximum pages (Hint: need TwoPass activated to work)
203+- **\[ColNo\]** Actual coloumn
204+- **\[PageNoPerDesignerPage\]**
205+- **\[InRepeatedGroupHeader\]**
206+- **\[InIntermediateGroupFooter\]**
207+- **\[IsOverflowed\]**
208+- **\[IsGroupDetailPrinted\]**
209+- **\[FieldIsNull\]**
210+
211+### Image Support
212+
213+If the dataset contains a blob field with an image, then this can also be printed:
214+
215+``` pascal
216+ Image := TFPReportImage.Create(DataBand);
217+ Image.Layout.Top := 0;
218+ Image.Layout.Left := 10;
219+ Image.Layout.Height := 20;
220+ Image.Layout.Width := 14.8;
221+ Image.FieldName := 'Photo';
222+ Image.Stretched := True;
223+```
224+
225+It is sufficient to set the FieldName property to the name of the field containing the image data.
226+
227+A fixed image can also be added, if so desired:
228+
229+``` pascal
230+ Image := TFPReportImage.Create(TitleBand);
231+ Image.Layout.Left := 0;
232+ Image.Layout.Top := 0;
233+ Image.Layout.Width := 40;
234+ Image.Layout.Height := 30;
235+ Image.LoadFromFile('company-logo.png');
236+ Image.Stretched := True;
237+```
238+
239+## Running the report
240+
241+To layout the report, the RunReport method can be used:
242+
243+``` pascal
244+{ specify what directories should be used to find TrueType fonts }
245+gTTFontCache.SearchPath.Add(cFCLReportDemosLocation + '/fonts/');
246+gTTFontCache.BuildFontCache;
247+
248+rpt.RunReport;
249+```
250+
251+This will create the report in memory.
252+
253+It is not visible on screen, it is not saved to file.
254+
255+## Rendering (or exporting) the report
256+
257+To actually view the report, it must be rendered or exported. A preview of the report is also an export.
258+
259+Various exporters exist:
260+
261+- [[PDF]] exporter
262+- FPImage exporter (no sub-pixel rendering)
263+- AggPas exporter (sub-pixel rendering and anti-aliasing). It is recommended to use the [AggPas](https://github.com/graemeg/fpGUI/tree/develop/src/corelib/render/software) code included in the [[fpGUI]] code repository.
264+- HTML exporter
265+- LCL canvas exporter, used as the basis for the LCL Preview exporter
266+- [[fpGUI]] canvas exporter, used as the basis for the fpGUI Preview exporter
267+
268+Thus, previewing or saving a layouted report is just a matter of creating the correct exporter, and calling the report **RenderReport** method:
269+
270+``` pascal
271+RptExporter := TFPReportExportPDF.Create(nil); // as before, use Self or Nil based on Application class
272+rpt.RenderReport(RptExporter);
273+```
274+
275+## Complete Code Example
276+
277+### Requirements
278+
279+This example can be compiled with FPC 2.6.4 or later.
280+
281+For this code to compile, you need to specify the following Unit Search Paths:
282+
283+- /data/devel/fpc-3.1.1/src/packages/fcl-report/src/
284+- ../../fpgui/src/fpreport
285+- ../../fpgui/src/corelib/render/software
286+
287+The first search path is to the **fcl-report** directory from FPC Trunk.
288+
289+The second search path (optional) is to the AggPas exporter as defined in the [[fpGUI]] code repository.
290+
291+The third search path (optional) is to the AggPas library source code, as found in the fpGUI code repository.
292+
293+You also need to make sure the constant **cFCLReportDemosLocation** defined in the source code is pointing to the correct fcl-report/demo/ directory as it is on your own system.
294+
295+### Source Code
296+
297+``` pascal
298+program project1;
299+
300+{$mode objfpc}{$H+}
301+
302+{ Which exporter do you want to use. Select any one or all. If you enable the AggPas
303+ exporter, remember to add the extra Unit Search Paths to your project settings. }
304+{$define ExportPDF}
305+{$define ExportFPImage}
306+{$define ExportAggPas}
307+
308+uses
309+ SysUtils
310+ ,fpreport // for most FPReport classes
311+ ,dbf // for TDBF (database) access
312+ ,fpreportdb // for the TFPReportDatasetData class
313+ ,fpttf // for access to gTTFontCache singleton
314+ {$IFDEF ExportPDF}
315+ ,fpreportpdfexport // for access to the PDF Report exporter class
316+ {$ENDIF}
317+ {$IFDEF ExportAggPas}
318+ ,fpreport_export_aggpas // for access to fpGUI's fpReport AggPas exporter class
319+ {$ENDIF}
320+ {$IFDEF ExportFPImage}
321+ ,fpreportfpimageexport // for access to the FPImage exporter class
322+ {$ENDIF}
323+ ;
324+
325+const
326+ cFCLReportDemosLocation = '/data/devel/fpc-3.1.1/src/packages/fcl-report/demos/';
327+
328+var
329+ rpt: TFPReport;
330+ lDataSet: TDBF;
331+ lReportData: TFPReportDatasetData;
332+ p: TFPReportPage;
333+ TitleBand: TFPReportTitleBand;
334+ Memo: TFPReportMemo;
335+ DataBand: TFPReportDataBand;
336+ Image: TFPReportImage;
337+ RptExporter: TFPReportExporter;
338+begin
339+ RptExporter := nil;
340+ if not FileExists(cFCLReportDemosLocation + 'test.dbf') then
341+ begin
342+ writeln('Unable to find database file <' + cFCLReportDemosLocation + 'test.dbf>');
343+ writeln('Please run the fcl-report''s dataset demo at least once.');
344+ writeln('');
345+ exit;
346+ end;
347+
348+ // ***** Creating the report *****
349+ PaperManager.RegisterStandardSizes;
350+ rpt:=TFPReport.Create(nil);
351+ rpt.Author := 'Graeme Geldenhuys';
352+ rpt.Title := 'FPReport Demo 8 - Datasets';
353+ try
354+ // ***** Providing data to the report *****
355+ lReportData := TFPReportDatasetData.Create(nil);
356+ lDataSet := TDBF.Create(nil);
357+ lDataSet.TableName := cFCLReportDemosLocation + 'test.dbf';
358+ lReportData.DataSet := lDataSet;
359+
360+ // ***** Adding a page *****
361+ p := TFPReportPage.Create(rpt);
362+ p.Orientation := poPortrait;
363+ p.PageSize.PaperName := 'A4';
364+
365+ { page margins }
366+ p.Margins.Left := 30;
367+ p.Margins.Top := 20;
368+ p.Margins.Right := 30;
369+ p.Margins.Bottom := 20;
370+
371+ { page's default font }
372+ p.Font.Name := 'LiberationSans'; // this is the PostScript name of the TTF font
373+
374+ { assign the data for the page data loop }
375+ p.Data := lReportData;
376+
377+ // ***** Adding bands to a page *****
378+ TitleBand := TFPReportTitleBand.Create(p);
379+ TitleBand.Layout.Height := 40;
380+// TitleBand.Frame.Shape := fsRectangle;
381+// TitleBand.Frame.BackgroundColor := clYellow;
382+
383+ Memo := TFPReportMemo.Create(TitleBand);
384+ Memo.Layout.Left := 5;
385+ Memo.Layout.Top := 0;
386+ Memo.Layout.Width := 140;
387+ Memo.Layout.Height := 15;
388+
389+ Memo.Text := 'Dataset Demo';
390+ Memo.TextAlignment.Vertical := tlCenter;
391+ Memo.TextAlignment.Horizontal := taCentered;
392+
393+ Memo.UseParentFont := False;
394+ Memo.Font.Color := TFPReportColor($000080);
395+ Memo.Font.Size := 24;
396+
397+ // ***** The loop data *****
398+ DataBand := TFPReportDataBand.Create(p);
399+ DataBand.Layout.Height := 30;
400+ DataBand.Data:= lReportData;
401+// DataBand.Frame.Shape := fsRectangle;
402+// DataBand.Frame.BackgroundColor := clCream;
403+
404+ Memo := TFPReportMemo.Create(DataBand);
405+ Memo.Layout.Left := 30;
406+ Memo.Layout.Top := 0;
407+ Memo.Layout.Width := 50;
408+ Memo.Layout.Height := 5;
409+ Memo.Text := 'Name: [name]';
410+
411+ // ***** Image Support *****
412+ Image := TFPReportImage.Create(DataBand);
413+ Image.Layout.Top := 0;
414+ Image.Layout.Left := 10;
415+ Image.Layout.Height := 20;
416+ Image.Layout.Width := 14.8;
417+ Image.FieldName := 'Photo';
418+ Image.Stretched := True;
419+
420+ Image := TFPReportImage.Create(TitleBand); // note this one is placed on the TitleBand
421+ Image.Layout.Left := 0;
422+ Image.Layout.Top := 0;
423+ Image.Layout.Width := 40;
424+ Image.Layout.Height := 30;
425+ Image.LoadFromFile(cFCLReportDemosLocation + 'pictures/woman01.png');
426+ Image.Stretched := True;
427+
428+ // ***** Running the report *****
429+ { specify what directories should be used to find TrueType fonts }
430+ gTTFontCache.SearchPath.Add(cFCLReportDemosLocation + '/fonts/');
431+ gTTFontCache.BuildFontCache;
432+
433+ rpt.RunReport;
434+
435+ // ***** Rendering (or exporting) the report *****
436+ {$IFDEF ExportPDF}
437+ if Assigned(RptExporter) then
438+ FreeAndNil(RptExporter);
439+ RptExporter := TFPReportExportPDF.Create(nil);
440+ rpt.RenderReport(RptExporter);
441+ {$ENDIF}
442+ {$IFDEF ExportAggPas}
443+ if Assigned(RptExporter) then
444+ FreeAndNil(RptExporter);
445+ RptExporter := TFPReportExportAggPas.Create(nil);
446+ TFPReportExportAggPas(RptExporter).BaseFileName := ApplicationName + '-aggpas-%.2d.png';
447+ rpt.RenderReport(RptExporter);
448+ {$ENDIF}
449+ {$IFDEF ExportFPImage}
450+ if Assigned(RptExporter) then
451+ FreeAndNil(RptExporter);
452+ RptExporter := TFPReportExportfpImage.Create(nil);
453+ TFPReportExportfpImage(RptExporter).BaseFileName := ApplicationName + '-fpimage-.png';
454+ rpt.RenderReport(RptExporter);
455+ {$ENDIF}
456+
457+ finally
458+ // Freeing all objects we used
459+ FreeAndNil(RptExporter);
460+ FreeAndNil(rpt);
461+ FreeAndNil(lReportData);
462+ FreeAndNil(lDataset);
463+ end;
464+end.
465+```
466+
467+## Loading and saving a report from/to file
468+
469+As explained in the introductory page [[FPReport]], the **TFPReport** class by itself does not have a concept of files. It only knows a streamer (**TFPReportStreamer**). FPC ships a JSON streamer **TFPReportJSONStreamer**, there is also an older XML streamer, currently untested).
470+
471+### Manually loading and saving
472+
473+The following code shows how to use a TFPReportJSONStreamer to save a report to file:
474+
475+``` pascal
476+Var
477+ J : TFPReportJSONStreamer;
478+ F : TFileStream;
479+ S : TJSONStringType;
480+begin
481+ F:=Nil;
482+ J:=TFPReportJSONStreamer.Create(Self);
483+ try
484+ FReport.WriteElement(J);
485+ F:=TFileStream.Create('txt2pdf.fpr',fmCreate);
486+ S:=J.JSON.FormatJSON();
487+ F.WriteBuffer(S[1],Length(S));
488+ finally
489+ F.Free;
490+ J.Free;
491+ end;
492+end;
493+```
494+
495+And the following code loads it again from file:
496+
497+``` pascal
498+procedure TPrintApplication.LoadReportDesign;
499+
500+Var
501+ J : TFPReportJSONStreamer;
502+ F : TFileStream;
503+ O : TJSONObject;
504+
505+begin
506+ J:=Nil;
507+ F:=TFileStream.Create('txt2pdf.fpr',fmOpenRead);
508+ try
509+ O:=GetJSON(F) as TJSONObject;
510+ J:=TFPReportJSONStreamer.Create(Self);
511+ J.JSON:=O;
512+ J.OwnsJSON:=True;
513+ FReport.ReadElement(J);
514+ finally
515+ F.Free;
516+ J.Free;
517+ end;
518+end;
519+```
520+
521+### The easy way: Using TFPJSONReport
522+
523+The *fpjsonreport* unit contains the **TFPJSONReport** class. It combines the JSON streamer and TFPReport, and makes it easier to load/save The *fpjsonreport* unit contains a **TFPJSONReport** descendent which does all the above with some simple methods:
524+
525+``` pascal
526+TFPJSONReport = class(TFPReport)
527+ procedure LoadFromStream(const aStream: TStream);
528+ procedure SaveToStream(const aStream: TStream);
529+ Procedure LoadFromJSON(aJSON : TJSONObject); virtual;
530+ Procedure SavetoJSON(aJSON : TJSONObject); virtual;
531+ Procedure LoadFromFile(const aFileName : String);
532+ Procedure SaveToFile(const aFileName : String);
533+ Property DataManager : TFPCustomReportDataManager;
534+end;
535+```
536+
537+It also is able to save the JSON Design in a lazarus .lfm file, so if you want to use a report that stores it's design info in a .lfm file, use a **TJSONFPReport** in lazarus.
538+
539+### Data management
540+
541+The **TFPReportDataManager** class can be used to create and manage data sets based on definitions found in the JSON file created by the standalone designer.
542+
543+(in fact the standalone designer uses the **TFPReportDataManager** to manage its data).
544+
545+When you use **TFPJSONReport**, you can set its **DataManager** property to an instance of **TFPReportDataManager**.
546+
547+When loading/saving the data, it will use the data manager to add and/ord interpret the extra information in the report JSON to create data sets.
548+
549+If a data set fails to open for some reason (no connection to the database or other things), the **LoadErrors** property (of type **TStrings**) will contain the error messages.
550+
551+The data manager uses a factory to create the necessary data sets. For this, it requires handlers to be registered in the executable. The following units with data handlers are available:
552+
553+- **fpreportdatacsv** for CSV support.
554+- **fpreportdatadbf** for dbf support.
555+- **fpreportdatajson** for JSON data file support.
556+- **fpreportdatasqldb** for SQLDB support.
557+
558+You must make sure to include the units for the data formats that you need in your project file. If you fail to do so, you will get errors saying that an unknown data type is used.
559+
560+## Back to main FPReport page
561+
562+- [[FPReport]]
563+
564+---
565+*From the Free Pascal wiki, page "FPReport Usage", as it stood on 2020-02-16 after a change by Trev, 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).*

Back to history