forked from synopse/SynPDF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mORMotReport.pas
5525 lines (5143 loc) · 195 KB
/
mORMotReport.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// Reporting unit
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit mORMotReport;
(*
This file is part of Synopse framework.
Synopse framework. Copyright (C) 2015 Arnaud Bouchez
Synopse Informatique - http://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is Synopse framework.
The Initial Developer of the Original Code is Angus Johnson.
Portions created by the Initial Developer are Copyright (C) 2003
the Initial Developer. All Rights Reserved.
Portions created by Arnaud Bouchez for Synopse are Copyright (C) 2015
Arnaud Bouchez. All Rights Reserved.
Contributor(s):
- Celery
- Leo
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
Initial Notes and Copyright:
******************************
Component Name: TPages
Module: Pages
Description: Report writer and previewer
Version: 1.6
Date: 25-MAY-2004 (initial version)
Target: Win32, Delphi 3 - Delphi 7
Author: Angus Johnson, http://www.angusj.com
Copyright © 2003 Angus Johnson
Notes:
* TGDIPages is designed as a simple lightweight report writer. Reports are
created in code, they are not banded, nor are they directly linked to
TDatasets. If you're looking for a dataset aware report writer then
TGDIPages is not for you. TGDIPages is a visual component based on a
TScrollbox, though it isn't necessary to view reports prior to printing.
* Main features include:
+ Text can be output either wrapped between page margins, in columns
or at specified offsets.
+ Multiple alignment options -
> left, right and justified in non-columned text
> left, right and currency in columned text
+ Tabs to Assigned tabstops
+ Multi-line page headers, footers and column headers
+ Multiple fonts can be used.
+ Angled text output
+ Single, line & half, and double line spacing
+ Methods for printing bitmaps, metafiles, lines, boxes and arrows
+ Page numbering can be redefined
+ Text output 'groups' prevent blocks of text spanning across pages
+ Designed around a TScrollbox descendant preview window with:
mouse click zoom control; keyboard handling of lineup, linedown,
pageup and pagedown srolling; mouse wheel scrolling.
* In order to get the best print quality, TGDIPages uses the selected
printer driver's resolution to prepare reports.
If a report will be printed to a different printer (eg by using a
PrintDialog), it's preferable to change to that printer object BEFORE
preparing the report. Otherwise, the report will be stretch down to the
printer canvas resulting in a slight degradation in print quality.
Enhanced for the freeware Synopse framework:
**********************************************
- Windows XP, Vista and Seven compatibility adding
- fix printing metafiles and page groups on some printer (with bad drivers)
- optionnaly use antialiaised drawing (via SynGdiPlus unit)
- popup menu creation, with zoom, print or copy features (and custom entries)
- direct PDF export (if a PDF printer is installed, or via SynPdf unit)
- direct page export to clipboard as text
- optional Black and White / Duplex mode (with out TPrinterNew custom class)
- new useful methods for easy text adding (especially column definition)
- new fast double buffering drawing
- full Unicode text process (even before Delphi 2009)
- speed up and various bug fixes to work with Delphi 5 up to XE3
Modifications © 2009-2015 Arnaud Bouchez
Version 1.4 - February 8, 2010
- whole Synopse SQLite3 database framework released under the GNU Lesser
General Public License version 3, instead of generic "Public Domain"
Version 1.6
- new version, using our SynGdiPlus unit: if the GDI+ is available,
it will use it to render the page using its AntiAliased engine;
under Windows 98 or 2000, no antialiasing will occur, but the program
will still run (since our SynGdiPlus unit use dynamic linking of the
gdiplus.dll library);
if only GDI+ 1.0 is available (i.e. with a Windows XP without any Office
2003/2007 installed) a pure Delphi version of GDI+ drawing is used, which
should not be able to convert 100% of page content, but should work on
most cases
Version 1.8
- some fixes for compilation under Delphi 2009/2010
Version 1.9
- new AppendRichEdit method to draw RichEdit content
- new WordWrapLeftCols property used to optionaly word wrap caLeft columns
into multiple lines, i.e. if the text is wider than the column width, its
content is wrapped to the next line (set to false by default) - this
also will handle #13/#10 in column text as a "go to next line" command
Version 1.9.2
- fix font color issue in header and footers
- safety additional code to avoid any division per 0 exception
Version 1.11
- fixed issue in TGDIPages.AppendRichEdit - see user feedback from
http://synopse.info/forum/viewtopic.php?pid=671#p671
- added Author, Subject and Keywords optional parameters to TGDIPages.ExportPDF
Version 1.12
- fixed one issue (in SynGdiPlus) for displaying bitmaps in anti-aliased mode
and displaying underlined or stroken out text - new ForceInternalAntiAliased
method (true by default) using SynGdiPlus instead of GDI+ 1.1 native conversion
- OnStringToUnicodeEvent is now called for all text, whatever the alignment is
- new property BiDiMode, for formatting the text in right to left order
- added new DrawBMP overloaded method to add some bitmap as a (centered)
paragraph, with some optional legend - bitmaps are now cached and reused
in the exported PDF, if the same one is drawn multiple time in the document
- added new AddBookMark, AddOutline and AddLink methods (working also with
the PDF export using SynPdf) :)
- live navigation via links in the preview screen, and via the new 'Bookmarks'
popup menu entry
- additional ExportPDF* properties used during PDF export
- introducing the new TRenderPages class, for high-quality document rendering
(used e.g. within SynProject for document preview and PDF generation,
with basic understanding of the rtf format)
Version 1.15
- fixed an endless loop in TGDIPages.DrawTextAcrossCols when wrapping text
- fixed an issue in TGDIPages.DrawTextAcrossCols when test is exported to pdf
(wrong clipping region set)
- if TGDIPages.WordWrapLeftCols=TRUE, won't wrap column headers
Version 1.16
- includes new TSynAnsiConvert classes for handling Ansi charsets
- some minor fixes (e.g. preview landscape or keys for popup menu)
- fix issue in TGDIPages.AppendRichEdit() when called on a blank page
- enhanced the print preview screen with a left-sided button bar
- new TGdiPages.RenderGraphic method (accepting both TBitmap and TMetaFile)
Version 1.17
- now whole text process is UNICODE-ready, even on pre-Delphi-2009 versions
- now implements font fall-back in internal Anti-Aliaised drawing,
if the new ForceInternalAntiAliasedFontFallBack property is set to TRUE
Version 1.18
- renamed SQLite3Pages.pas to mORMotReport.pas
- TGdiPages now handles several page layouts per report - see new overloaded
TGDIPages.NewPageLayout() methods and also Orientation property which now
allows several page orientations per report - feature request [204b698b3d]
- now internal page content (TMetaFile) is compressed using our SynLZ
algorithm: we were able to generate reports with more than 20,000 pages!
- added optional EndOfPagePositions parameter to TGDIPages.AppendRichEdit()
- speed up and memory resource decrease for pdf export of huge reports
- fixed issue about disabled Zoom menu entry if no Outline is defined
- fixed unexpected exception with TGDIPages.DrawText() and huge string
- proper function TGDIPages.GetLineHeight() computation - from kln feedback
- added ExportPDFBackground and ExportPDFGeneratePDF15File properties
- added ExportPDFEncryptionLevel/User/OwnerPassword/Permissions properties to
optionally export report as 40 bit or 128 bit encrypted pdf
- added setter method for ZoomStatus property (during preview) - [dd656b470b]
- added TGDIPages.ExportPDFStream() method - to be used e.g. on servers
- fixed [cfdc644038] about truncated parenthesis in pdf export for caCurrency
- fixed [e7ffb69131] about TGDIPages.DrawGraphic() when the TGraphic is Empty
- allow preview as a blank colored component at design time (thanks to Celery)
- added VisibleButtons optional parameter to TGDIPages.ShowPreviewForm method
as requested by [4d64a52675]
*)
interface
{.$define MOUSE_CLICK_PERFORM_ZOOM} // old not user-friendly behavior
{.$define RENDERPAGES} // TRenderBox and TRenderPages are not yet finished
{$define GDIPLUSDRAW}
// optionaly (if ForceNoAntiAliased=false) use GDI+ to draw for antialiasing:
// slower but smoother (need the GDI+ library, best with version 1.1)
{.$define USEPDFPRINTER}
// do not use the Synopse PDF engine, in Delphi code, but a PDF virtual printer
{.$define PRINTERNEW}
// if our custom Printer.pas unit is installed, use TPrinterNew class instead
// of TPrinter to allow Black&White and Duplex printing
// -> disabled by default, should be enabled globaly from the Project Options
{$ifndef ENHANCEDRTL}
{$undef PRINTERNEW}
// Black&White and Duplex printing are only available with our Enhanced RTL
{$endif}
{$I Synopse.inc} // define HASINLINE USETYPEINFO CPU32 CPU64 OWNNORMTOUPPER
{$HPPEMIT '#undef DrawText'}
uses
SynCommons, SynLZ,
{$ifndef USEPDFPRINTER}
SynPdf,
{$endif}
Windows, Messages, SysUtils, Classes, Contnrs,
{$ifdef GDIPLUSDRAW}
SynGdiPlus,
{$endif}
Graphics, Controls, Dialogs, Forms, StdCtrls,
ExtCtrls, WinSpool, Printers, Menus, ShellAPI, RichEdit;
const
MAXCOLS = 20;
MAXTABS = 20;
{{ this constant can be used to be replaced by the page number in
the middle of any text }
PAGENUMBER = '<<pagenumber>>';
type
/// text paragraph alignment
TTextAlign = (taLeft,taRight,taCenter,taJustified);
/// text column alignment
TColAlign = (caLeft,caRight,caCenter, caCurrency);
/// text line spacing
TLineSpacing = (lsSingle, lsOneAndHalf, lsDouble);
/// available zoom mode
// - zsPercent is used with a zoom percentage (e.g. 100% or 50%)
// - zsPageFit fits the page to the report
// - zsPageWidth zooms the page to fit the report width on screen
TZoomStatus = (zsPercent, zsPageFit, zsPageWidth);
/// Event triggered when a new page is added
TNewPageEvent = procedure(Sender: TObject; PageNumber: integer) of object;
/// Event triggered when the Zoom was changed
TZoomChangedEvent = procedure(Sender: TObject;
Zoom: integer; ZoomStatus: TZoomStatus) of object;
/// Event triggered to allow custom unicode character display on the screen
// - called for all text, whatever the alignment is
// - Text content can be modified by this event handler to customize
// some characters (e.g. '>=' can be converted to the one unicode equivalent)
TOnStringToUnicodeEvent = function(const Text: SynUnicode): SynUnicode of object;
/// available known paper size for NewPageLayout() method
TGdiPagePaperSize = (
psA4, psA5, psA3, psLetter, psLegal);
TGDIPages = class;
/// a report layout state, as used by SaveLayout/RestoreSavedLayout methods
TSavedState = record
FontName: string;
FontColor: integer;
Flags: integer;
LeftMargin: integer;
RightMargin: integer;
BiDiMode: TBiDiMode;
end;
/// internal format of the header or footer text
THeaderFooter = class
public
Text: SynUnicode;
State: TSavedState;
/// initialize the header or footer parameters with current report state
constructor Create(Report: TGDIPages; doubleline: boolean;
const aText: SynUnicode=''; IsText: boolean=false);
end;
/// internal format of a text column
TColRec = record
ColLeft, ColRight: integer;
ColAlign: TColAlign;
ColBold: boolean;
end;
TPopupMenuClass = class of TPopupMenu;
/// hack the TPaintBox to allow custom background erase
TPagePaintBox = class(TPaintBox)
private
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
end;
/// internal structure used to store bookmarks or links
TGDIPagereference = class
public
/// the associated page number (starting at 1)
Page: Integer;
/// graphical coordinates of the hot zone
// - for bookmarks, Top is the Y position
// - for links, the TRect will describe the hot region
// - for Outline, Top is the Y position and Bottom the outline tree level
Rect: TRect;
/// coordinates on screen of the hot zone
Preview: TRect;
/// initialize the structure with the current page
constructor Create(PageNumber: integer; Left, Top, Right, Bottom: integer);
/// compute the coordinates on screen into Preview
procedure ToPreview(Pages: TGDIPages);
end;
/// contains one page
TGDIPageContent = record
/// SynLZ-compressed content of the page
MetaFileCompressed: RawByteString;
/// text equivalent of the page
Text: string;
/// the physical page size
SizePx: TPoint;
/// margin of the page
MarginPx: TRect;
/// non printable offset of the page
OffsetPx: TPoint;
end;
/// used to store all pages of the report
TGDIPageContentDynArray = array of TGDIPageContent;
/// the available menu items
TGdiPagePreviewButton = (
rNone, rNextPage, rPreviousPage, rGotoPage, rZoom, rBookmarks,
rPageAsText, rPrint, rExportPDF, rClose);
/// set of menu items
TGdiPagePreviewButtons = set of TGdiPagePreviewButton;
/// Report class for generating documents from code
// - data is drawn in memory, they displayed or printed as desired
// - allow preview and printing, and direct pdf export
// - handle bookmark, outlines and links inside the document
// - page coordinates are in mm's
TGDIPages = class(TScrollBox)
protected
fPreviewSurface: TPagePaintbox;
fCanvas: TMetafileCanvas;
fCanvasText: string;
fBeforeGroupText: string;
fGroupPage: TMetafile;
fPages: TGDIPageContentDynArray;
fHeaderLines: TObjectList;
fFooterLines: TObjectList;
fColumns: array of TColRec;
fColumnHeaderList: TStringList;
{$ifdef MOUSE_CLICK_PERFORM_ZOOM}
fZoomTimer: TTimer;
{$endif}
fPtrHdl: THandle;
fTabCount: integer;
fCurrentPrinter: string;
fOrientation: TPrinterOrientation;
fDefaultLineWidth: integer; //drawing line width (boxes etc)
fVirtualPageNum: integer;
fCurrPreviewPage: integer;
fZoomIn: boolean;
fLineHeight: integer; //Text line height
fLineSpacing: TLineSpacing;
fCurrentYPos: integer;
fCurrentTextTop, fCurrentTextPage: integer;
fHeaderHeight: integer;
fHangIndent: integer;
fAlign: TTextAlign;
fBiDiMode: TBiDiMode;
fPageMarginsPx: TRect;
fHasPrinterInstalled: boolean;
{$ifdef USEPDFPRINTER}
fHasPDFPrinterInstalled: boolean;
fPDFPrinterIndex: integer;
{$else}
fForceJPEGCompression: Integer;
fExportPDFApplication: string;
fExportPDFAuthor: string;
fExportPDFSubject: string;
fExportPDFKeywords: string;
fExportPDFEmbeddedTTF: boolean;
fExportPDFA1: boolean;
fExportPDFBackground: TGraphic;
{$ifndef NO_USE_UNISCRIBE}
fExportPDFUseUniscribe: boolean;
{$endif}
fExportPDFUseFontFallBack: boolean;
fExportPDFFontFallBackName: string;
fExportPDFEncryptionLevel: TPdfEncryptionLevel;
fExportPDFEncryptionUserPassword: string;
fExportPDFEncryptionOwnerPassword: string;
fExportPDFEncryptionPermissions: TPdfEncryptionPermissions;
fExportPDFGeneratePDF15File: boolean;
{$endif}
fPrinterPxPerInch: TPoint;
fPhysicalSizePx: TPoint; //size of page in printer pixels
fPhysicalOffsetPx: TPoint; //size of non-printing margins in pixels
fCustomPxPerInch: TPoint;
fCustomPageSize: TPoint;
fCustomNonPrintableOffset: TPoint;
fCustomPageMargins: TRect;
fZoom: integer;
fZoomStatus: TZoomStatus;
fNegsToParenthesesInCurrCols: boolean;
fWordWrapLeftCols: boolean;
fUseOutlines: boolean;
fForceScreenResolution: boolean;
fHeaderDone: boolean;
fFooterHeight: integer;
fFooterGap: integer;
fInHeaderOrFooter: boolean;
fColumnHeaderPrinted: boolean;
fColumnHeaderPrintedAtLeastOnce: boolean;
fDrawTextAcrossColsDrawingHeader: boolean;
fColumnHeaderInGroup: boolean;
fColumnsUsedInGroup: boolean;
fGroupVerticalSpace: integer;
fGroupVerticalPos: integer;
fZoomChangedEvent: TZoomChangedEvent;
fPreviewPageChangedEvent: TNotifyEvent;
fStartNewPage: TNewPageEvent;
fStartPageHeader: TNotifyEvent;
fEndPageHeader: TNotifyEvent;
fStartPageFooter: TNotifyEvent;
fEndPageFooter: TNotifyEvent;
fStartColumnHeader: TNotifyEvent;
fEndColumnHeader: TNotifyEvent;
fSavedCount: integer;
fSaved: array of TSavedState;
fTab: array of integer;
fColumnsWithBottomGrayLine: boolean;
fColumnsRowLineHeight: integer;
fOnDocumentProducedEvent: TNotifyEvent;
PageRightButton, PageLeftButton: TPoint;
fPagesToFooterText: string; // not SynUnicode, since calls format()
fPagesToFooterAt: TPoint;
fPagesToFooterState: TSavedState;
fMetaFileForPage: TMetaFile;
fCurrentMetaFile: TMetaFile;
procedure GetPrinterParams;
procedure SetAnyCustomPagePx;
function GetPaperSize: TSize;
procedure FlushPageContent;
function PrinterPxToScreenPxX(PrinterPx: integer): integer;
function PrinterPxToScreenPxY(PrinterPx: integer): integer;
procedure ResizeAndCenterPaintbox;
function GetMetaFileForPage(PageIndex: integer): TMetaFile;
procedure SetMetaFileForPage(PageIndex: integer; MetaFile: TMetaFile);
function GetOrientation: TPrinterOrientation;
procedure SetOrientation(orientation: TPrinterOrientation);
procedure SetTextAlign(Value: TTextAlign);
procedure SetPage(NewPreviewPage: integer);
function GetPageCount: integer;
function GetLineHeight: integer;
function GetLineHeightMm: integer;
procedure CheckYPos; //ie: if not vertical room force new page
function GetYPos: integer;
procedure SetYPos(YPos: integer);
procedure NewPageInternal; virtual;
function CreateMetaFile(aWidth, aHeight: integer): TMetaFile;
function CreateMetafileCanvas(Page: TMetafile): TMetafileCanvas;
procedure UpdateMetafileCanvasFont(aCanvas: TMetafileCanvas);
function TextFormatsToFlags: integer;
procedure SetFontWithFlags(flags: integer);
function GetPageMargins: TRect;
procedure SetPageMargins(Rect: TRect);
procedure DoHeader;
procedure DoFooter;
procedure DoHeaderFooterInternal(Lines: TObjectList);
procedure CalcFooterGap;
function GetColumnCount: integer;
function GetColumnRec(col: integer): TColRec;
procedure PrintColumnHeaders;
procedure SetZoom(zoom: integer);
procedure SetZoomStatus(aZoomStatus: TZoomStatus);
procedure ZoomTimerInternal(X,Y: integer; ZoomIn: boolean);
procedure ZoomTimer(Sender: TObject);
procedure LineInternal(start,finish: integer; DoubleLine: boolean);
procedure PrintFormattedLine(s: SynUnicode; flags: integer;
const aBookmark: string=''; const aLink: string='');
procedure LeftOrJustifiedWrap(const s: SynUnicode);
procedure RightOrCenterWrap(const s: SynUnicode);
procedure GetTextLimitsPx(var LeftOffset, RightOffset: integer);
procedure HandleTabsAndPrint(const leftstring: SynUnicode;
var rightstring: SynUnicode; leftOffset, rightOffset: integer);
procedure PreviewPaint(Sender: TObject);
procedure PreviewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PreviewMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PreviewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
function GetLeftMargin: integer;
procedure SetLeftMargin(const Value: integer);
function GetRightMarginPos: integer;
function GetSavedState: TSavedState;
procedure SetSavedState(const SavedState: TSavedState);
/// can be used internaly (for instance by fPagesToFooterState)
property SavedState: TSavedState read GetSavedState write SetSavedState;
protected
fMousePos: TPoint;
{$ifndef MOUSE_CLICK_PERFORM_ZOOM}
fButtonDown, fButtonDownScroll: TPoint;
{$endif}
/// Strings[] are the bookmark names, and Objects[] are TGDIPagereference
// to get the Y position
fBookmarks: TStringList;
/// Strings[] are the bookmark names, and Objects[] are TGDIPagereference to
// get the hot region
fLinks: TStringList;
fLinksCurrent: integer;
/// Strings[] are the outline titles, and Objects[] are TGDIPagereference
// to get the Y position of the destination
fOutline: TStringList;
fInternalUnicodeString: SynUnicode;
PreviewForm: TForm;
PreviewButtons: array of TButton;
PreviewPageCountLabel: TLabel;
procedure CMFontChanged(var Msg: TMessage); message CM_FONTCHANGED;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure CreateWnd; override;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
{$IFNDEF VER100}
function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer;
MousePos: TPoint): Boolean; override; //no mousewheel support in Delphi 3
{$ENDIF}
procedure PopupMenuPopup(Sender: TObject);
procedure CheckHeaderDone; virtual;
// warning: PW buffer is overwritten at the next method call
procedure InternalUnicodeString(const s: SynUnicode;
var PW: PWideChar; var PWLen: integer; size: PSize);
public
/// Event triggered when the ReportPopupMenu is displayed
// - default handling (i.e. leave this field nil) is to add Page naviguation
// - you can override this method for adding items to the ReportPopupMenu
OnPopupMenuPopup: TNotifyEvent;
/// Event triggered when a ReportPopupMenu item is selected
// - default handling (i.e. leave this field nil) is for Page navigation
// - you can override this method for handling additionnal items to the menu
// - the Tag component of the custom TMenuItem should be 0 or greater than
// Report pages count: use 1000 as a start for custom TMenuItem.Tag values
OnPopupMenuClick: TNotifyEvent;
/// user can customize this class to create an advanced popup menu instance
PopupMenuClass: TPopupMenuClass;
/// the title of the report
// - used for the preview caption form
// - used for the printing document name
Caption: string;
/// if true, the PrintPages() method will use a temporary bitmap for printing
// - some printer device drivers have problems with printing metafiles
// which contains other metafiles; should have been fixed
// - not useful, since slows the printing a lot and makes huge memory usage
ForcePrintAsBitmap: boolean;
/// if true the preview will not use GDI+ library to draw anti-aliaised graphics
// - this may be slow on old computers, so caller can disable it on demand
ForceNoAntiAliased: boolean;
/// if true, drawing will NOT to use native GDI+ 1.1 conversion
// - we found out that GDI+ 1.1 was not as good as our internal conversion
// function written in Delphi, e.g. for underlined fonts
// - so this property is set to true by default for proper display on screen
// - will only be used if ForceNoAntiAliased is false, of course
ForceInternalAntiAliased: boolean;
/// if true, internal text drawing will use a font-fallback mechanism
// for characters not existing within the current font (just as with GDI)
// - is disabled by default, but could be set to TRUE to force enabling
// TGDIPlusFull.ForceUseDrawString property
ForceInternalAntiAliasedFontFallBack: boolean;
{$ifdef PRINTERNEW}
// the PrintPages() will use this parameter to force black and white, or
// color mode, whatever the global printer setting is
ForcePrintColorMode: (printColorDefault, printBW, printColor);
// the PrintPages() will use this parameter to force duplex mode,
// whatever the global printer setting is
ForcePrintDuplexMode: (printDuplexDefault, printSimplex, printDuplex);
{$endif}
/// if true, the headers are copied only once to the text
ForceCopyTextAsWholeContent: boolean;
/// customize left aligned text conversion from Ansi
// - to be used before Delphi 2009/2010/XE only, in order to force some
// character customization (e.g. <= or >=)
OnStringToUnicode: TOnStringToUnicodeEvent;
/// set group page fill method
// - if set to true, the groups will be forced to be placed on the same page
// (this was the original default "Pages" component behavior, but this
// is not usual in page composition, so is disabled by default in TGDIPages)
// - if set to false, the groups will force a page feed if there is not
// enough place for 20 lines on the current page (default behavior)
GroupsMustBeOnSamePage: boolean;
/// the bitmap used to draw the page
PreviewSurfaceBitmap: TBitmap;
/// creates the reporting component
constructor Create(AOwner: TComponent); override;
/// finalize the component, releasing all used memory
destructor Destroy; override;
/// customized invalidate
procedure Invalidate; override;
/// Begin a Report document
// - Every report must start with BeginDoc and end with EndDoc
// - note that Printers.SetPrinter() should be set BEFORE calling BeginDoc,
// otherwise you may have a "canvas does not allow drawing" error
procedure BeginDoc;
/// Clear the current Report document
procedure Clear; virtual;
/// draw some text as a paragraph, with the current alignment
// - this method does all word-wrapping and formating if necessary
// - this method handle multiple paragraphs inside s (separated by newlines -
// i.e. #13)
procedure DrawText(const s: string); {$ifdef HASINLINE}inline;{$endif}
/// draw some UTF-8 text as a paragraph, with the current alignment
// - this method does all word-wrapping and formating if necessary
// - this method handle multiple paragraphs inside s (separated by newlines -
// i.e. #13)
procedure DrawTextU(const s: RawUTF8); {$ifdef HASINLINE}inline;{$endif}
/// draw some Unicode text as a paragraph, with the current alignment
// - this method does all word-wrapping and formating if necessary
// - this method handle multiple paragraphs inside s (separated by newlines -
// i.e. #13)
procedure DrawTextW(const s: SynUnicode);
/// draw some text as a paragraph, with the current alignment
// - this method use format() like parameterss
procedure DrawTextFmt(const s: string; const Args: array of const);
/// get the formating flags associated to a Title
function TitleFlags: integer;
/// draw some text as a paragraph title
// - the outline level can be specified, if UseOutline property is enabled
// - if aBookmark is set, a bookmark is created at this position
// - if aLink is set, a link to the specified bookmark name (in aLink) is made
procedure DrawTitle(const s: SynUnicode; DrawBottomLine: boolean=false; OutlineLevel: Integer=0;
const aBookmark: string=''; const aLink: string='');
/// draw one line of text, with the current alignment
procedure DrawTextAt(s: SynUnicode; XPos: integer; const aLink: string='';
CheckPageNumber: boolean=false);
/// draw one line of text, with a specified Angle and X Position
procedure DrawAngledTextAt(const s: SynUnicode; XPos, Angle: integer);
/// draw a square box at the given coordinates
procedure DrawBox(left,top,right,bottom: integer);
/// draw a filled square box at the given coordinates
procedure DrawBoxFilled(left,top,right,bottom: integer; Color: TColor);
/// Stretch draws a bitmap image at the specified page coordinates in mm's
procedure DrawBMP(rec: TRect; bmp: TBitmap); overload;
/// add the bitmap at the specified X position
// - if there is not enough place to draw the bitmap, go to next page
// - then the current Y position is updated
// - bLeft (in mm) is calculated in reference to the LeftMargin position
// - if bLeft is maxInt, the bitmap is centered to the page width
// - bitmap is stretched (keeping aspect ratio) for the resulting width to
// match the bWidth parameter (in mm)
procedure DrawBMP(bmp: TBitmap; bLeft, bWidth: integer; const Legend: string=''); overload;
/// Stretch draws a metafile image at the specified page coordinates in mm's
procedure DrawMeta(rec: TRect; meta: TMetafile);
/// add the graphic (bitmap or metafile) at the specified X position
// - handle only TBitmap and TMetafile kind of TGraphic
// - if there is not enough place to draw the bitmap, go to next page
// - then the current Y position is updated
// - bLeft (in mm) is calculated in reference to the LeftMargin position
// - if bLeft is maxInt, the bitmap is centered to the page width
// - bitmap is stretched (keeping aspect ratio) for the resulting width to
// match the bWidth parameter (in mm)
procedure DrawGraphic(graph: TGraphic; bLeft, bWidth: integer; const Legend: SynUnicode='');
/// draw an Arrow
procedure DrawArrow(Point1, Point2: TPoint; HeadSize: integer; SolidHead: boolean);
/// draw a Line, either simple or double, between the left & right margins
procedure DrawLine(doubleline: boolean=false);
/// draw a Dashed Line between the left & right margins
procedure DrawDashedLine;
/// append a Rich Edit content to the current report
// - note that if you want the TRichEdit component to handle more than 64 KB
// of RTF content, you have to set its MaxLength property as expected (this
// is a limitation of the VCL, not of this method)
// - you can specify optionally a pointer to a TIntegerDynArray variable,
// which will be filled with the position of each page last char: it may
// be handy e.g. to add some cross-reference table about the rendered content
procedure AppendRichEdit(RichEditHandle: HWnd; EndOfPagePositions: PIntegerDynArray=nil);
/// jump some line space between paragraphs
// - Increments the current Y Position the equivalent of a single line
// relative to the current font height and line spacing
procedure NewLine;
/// jump some half line space between paragraphs
// - Increments the current Y Position the equivalent of an half single line
// relative to the current font height and line spacing
procedure NewHalfLine;
/// jump some line space between paragraphs
// - Increments the current Y Position the equivalent of 'count' lines
// relative to the current font height and line spacing
procedure NewLines(count: integer);
/// save the current font and alignment
procedure SaveLayout; virtual;
/// restore last saved font and alignment
procedure RestoreSavedLayout; virtual;
/// jump to next page, i.e. force a page break
procedure NewPage(ForceEndGroup: boolean=false);
/// jump to next page, but only if some content is pending
procedure NewPageIfAnyContent;
/// change the page layout for the upcoming page
// - will then force a page break by a call to NewPage(true) method
// - can change the default margin if margin*>=0
// - can change the default non-printable printer margin if nonPrintable*>=0
procedure NewPageLayout(sizeWidthMM, sizeHeightMM: integer;
nonPrintableWidthMM: integer=-1; nonPrintableHeightMM: integer=-1); overload;
/// change the page layout for the upcoming page
// - will then force a page break by a call to NewPage(true) method
// - can change the default margin if margin*>=0
// - can change the default non-printable printer margin if nonPrintable*>=0
procedure NewPageLayout(paperSize: TGdiPagePaperSize;
orientation: TPrinterOrientation=poPortrait;
nonPrintableWidthMM: integer=-1; nonPrintableHeightMM: integer=-1); overload;
/// begin a Group: stops the contents from being split across pages
// - BeginGroup-EndGroup text blocks can't be nested
procedure BeginGroup;
/// end a previously defined Group
// - BeginGroup-EndGroup text blocks can't be nested
procedure EndGroup;
/// End the Report document
// - Every report must start with BeginDoc and end with EndDoc
procedure EndDoc;
/// Print the selected pages to the default printer of Printer unit
// - if PrintFrom=0 and PrintTo=0, then all pages are printed
// - if PrintFrom=-1 or PrintTo=-1, then a printer dialog is displayed
function PrintPages(PrintFrom, PrintTo: integer): boolean;
/// export the current report as PDF file
{$ifdef USEPDFPRINTER}
// - uses an external 'PDF' printer
{$else}
// - uses internal PDF code, from Synopse PDF engine (handle bookmarks,
// outline and twin bitmaps) - in this case, a file name can be set
{$endif}
function ExportPDF(aPdfFileName: TFileName; ShowErrorOnScreen: boolean;
LaunchAfter: boolean=true): boolean;
{$ifndef USEPDFPRINTER}
/// export the current report as PDF in a specified stream
// - uses internal PDF code, from Synopse PDF engine (handle bookmarks,
// outline and twin bitmaps) - in this case, a file name can be set
function ExportPDFStream(aDest: TStream): boolean;
{$endif}
/// show a form with the preview, allowing the user to browse pages and
// print the report
// - you can customize the buttons and popup menu actions displayed on
// the screen - by default, all buttons are visible
procedure ShowPreviewForm(VisibleButtons: TGdiPagePreviewButtons =
[rNextPage..High(TGdiPagePreviewButton)]);
/// set the Tabs stops on every line
// - if one value is provided, it will set the Tabs as every multiple of it
// - if more than one value are provided, they will be the exact Tabs positions
procedure SetTabStops(const tabs: array of integer);
/// returns true if there is enough space in the current Report for Count lines
// - Used to check if there's sufficient vertical space remaining on the page
// for the specified number of lines based on the current Y position
function HasSpaceForLines(Count: integer): boolean;
/// returns true if there is enough space in the current Report for a
// vertical size, specified in mm
function HasSpaceFor(mm: integer): boolean;
/// Clear all already predefined Headers
procedure ClearHeaders;
/// Adds either a single line or a double line (drawn between the left &
// right page margins) to the page header
procedure AddLineToHeader(doubleline: boolean);
/// Adds text using to current font and alignment to the page header
procedure AddTextToHeader(const s: SynUnicode);
/// Adds text to the page header at the specified horizontal position and
// using to current font.
// - No Line feed will be triggered: this method doesn't increment the YPos,
// so can be used to add multiple text on the same line
// - if XPos=-1, will put the text at the current right margin
procedure AddTextToHeaderAt(const s: SynUnicode; XPos: integer);
/// Clear all already predefined Footers
procedure ClearFooters;
/// Adds either a single line or a double line (drawn between the left &
// right page margins) to the page footer
procedure AddLineToFooter(doubleline: boolean);
/// Adds text using to current font and alignment to the page footer
procedure AddTextToFooter(const s: SynUnicode);
/// Adds text to the page footer at the specified horizontal position and
// using to current font. No Line feed will be triggered.
// - if XPos=-1, will put the text at the current right margin
procedure AddTextToFooterAt(const s: SynUnicode; XPos: integer);
/// Will add the current 'Page n/n' text at the specified position
// - PageText must be of format 'Page %d/%d', in the desired language
// - if XPos=-1, will put the text at the current right margin
procedure AddPagesToFooterAt(const PageText: string; XPos: integer);
/// register a column, with proper alignment
procedure AddColumn(left, right: integer; align: TColAlign; bold: boolean);
/// register same alignement columns, with percentage of page column width
// - sum of all percent width should be 100, but can be of any value
// - negative widths are converted into absolute values, but
// corresponding alignment is set to right
// - if a column need to be right aligned or currency aligned,
// use SetColumnAlign() method below
// - individual column may be printed in bold with SetColumnBold() method
procedure AddColumns(const PercentWidth: array of integer; align: TColAlign=caLeft);
/// register some column headers, with the current font formating
// - Column headers will appear just above the first text output in
// columns on each page
// - you can call this method several times in order to have diverse
// font formats across the column headers
procedure AddColumnHeaders(const headers: array of SynUnicode;
WithBottomGrayLine: boolean=false; BoldFont: boolean=false;
RowLineHeight: integer=0; flags: integer=0);
/// register some column headers, with the current font formating
// - Column headers will appear just above the first text output in
// columns on each page
// - call this method once with all columns text as CSV
procedure AddColumnHeadersFromCSV(var CSV: PWideChar;
WithBottomGrayLine: boolean; BoldFont: boolean=false; RowLineHeight: integer=0);
/// draw some text, split across every columns
// - if BackgroundColor is not clNone (i.e. clRed or clNavy or clBlack), the
// row is printed on white with this background color (e.g. to highlight errors)
procedure DrawTextAcrossCols(const StringArray: array of SynUnicode;
BackgroundColor: TColor=clNone);
/// draw some text, split across every columns
// - this method expect the text to be separated by commas
// - if BackgroundColor is not clNone (i.e. clRed or clNavy or clBlack), the
// row is printed on white with this background color (e.g. to highlight errors)
procedure DrawTextAcrossColsFromCSV(var CSV: PWideChar; BackgroundColor: TColor=clNone);
/// draw (double if specified) lines at the bottom of all currency columns
procedure DrawLinesInCurrencyCols(doublelines: boolean);
/// retrieve the current Column count
property ColumnCount: integer read GetColumnCount;
/// retrieve the attributes of a specified column
function GetColumnInfo(index: integer): TColRec;
/// individually set column alignment
// - useful after habing used AddColumns([]) method e.g.
procedure SetColumnAlign(index: integer; align: TColAlign);
/// individually set column bold state
// - useful after habing used AddColumns([]) method e.g.
procedure SetColumnBold(index: integer);
/// erase all columns and the associated headers
procedure ClearColumns;
/// clear the Headers associated to the Columns
procedure ClearColumnHeaders;
/// ColumnHeadersNeeded will force column headers to be drawn again just
// prior to printing the next row of columned text
// - Usually column headers are drawn once per page just above the first
// column. ColumnHeadersNeeded is useful where columns of text have been
// separated by a number of lines of non-columned text
procedure ColumnHeadersNeeded;
/// create a bookmark entry at the current position of the current page
// - return false if this bookmark name was already existing, true on success
// - if aYPosition is not 0, the current Y position will be used
function AddBookMark(const aBookmarkName: string; aYPosition: integer=0): Boolean; virtual;
/// go to the specified bookmark
// - returns true if the bookmark name was existing and reached
function GotoBookmark(const aBookmarkName: string): Boolean; virtual;
/// create an outline entry at the current position of the current page
// - if aYPosition is not 0, the current Y position will be used
procedure AddOutline(const aTitle: string; aLevel: Integer;
aYPosition: integer=0; aPageNumber: integer=0); virtual;
/// create a link entry at the specified coordinates of the current page
// - coordinates are specified in mm
// - the bookmark name is not checked by this method: a bookmark can be
// linked before being marked in the document
procedure AddLink(const aBookmarkName: string; aRect: TRect;
aPageNumber: integer=0); virtual;
/// convert a rect of mm into pixel canvas units
function MmToPrinter(const R: TRect): TRect;
/// convert a rect of pixel canvas units into mm
function PrinterToMM(const R: TRect): TRect;
/// convert a mm X position into pixel canvas units
function MmToPrinterPxX(mm: integer): integer;
/// convert a mm Y position into pixel canvas units
function MmToPrinterPxY(mm: integer): integer;
/// convert a pixel canvas X position into mm
function PrinterPxToMmX(px: integer): integer;
/// convert a pixel canvas Y position into mm
function PrinterPxToMmY(px: integer): integer;
/// return the width of the specified text, in mm
function TextWidth(const Text: SynUnicode): integer;
/// the current Text Alignment, during text adding
property TextAlign: TTextAlign read fAlign write SetTextAlign;
/// specifies the reading order (bidirectional mode) of the box
// - only bdLeftToRight and bdRightToLeft are handled
// - this will be used by DrawText[At], DrawTitle, AddTextToHeader/Footer[At],
// DrawTextAcrossCols, SaveLayout/RestoreSavedLayout methods
property BiDiMode: TBiDiMode read fBiDiMode write fBiDiMode;
/// create a meta file and its associated canvas for displaying a picture
// - you must release manually both Objects after usage
function CreatePictureMetaFile(Width, Height: integer;
out MetaCanvas: TCanvas): TMetaFile;
/// Distance (in mm's) from the top of the page to the top of the current group
// - returns CurrentYPos if no group is in use
function CurrentGroupPosStart: integer;
/// go to the specified Y position on a given page
// - used e.g. by GotoBookmark() method
procedure GotoPosition(aPage: integer; aYPos: integer);
/// access to all pages content
// - numerotation begin with Pages[0] for page 1
// - the Pages[] property should be rarely needed
property Pages: TGDIPageContentDynArray read fPages;
/// add an item to the popup menu
// - used mostly internaly to add page browsing
// - default OnClick event is to go to page set by the Tag property
function NewPopupMenuItem(const aCaption: string; Tag: integer=0;
SubMenu: TMenuItem=nil; OnClick: TNotifyEvent=nil; ImageIndex: integer=-1): TMenuItem;
/// this is the main popup menu item click event
procedure PopupMenuItemClick(Sender: TObject);
/// can be used to draw directly using GDI commands
// - The Canvas property should be rarely needed
property Canvas: TMetaFileCanvas read fCanvas;
/// Distance (in mm's) from the top of the page to the top of the next line
property CurrentYPos: integer read GetYPos write SetYPos;
/// get current line height (mm)
property LineHeight: integer read GetLineHeightMm;
/// the name of the current selected printer
// - note that Printers.SetPrinter() should be set BEFORE calling BeginDoc,
// otherwise you may have a "canvas does not allow drawing" error
property PrinterName: string read fCurrentPrinter;
/// the index of the previewed page
// - please note that the first page is 1 (not 0)
property Page: integer read fCurrPreviewPage write SetPage;
/// total number of pages
property PageCount: integer read GetPageCount;
/// Size of each margin relative to its corresponding edge in mm's
property PageMargins: TRect read GetPageMargins write SetPageMargins;
/// Size of the left margin relative to its corresponding edge in mm's
property LeftMargin: integer read GetLeftMargin write SetLeftMargin;
/// Position of the right margin, in mm
property RightMarginPos: integer read GetRightMarginPos;
/// get the current selected paper size, in mm's
property PaperSize: TSize read GetPaperSize;
/// number of pixel per inch, for X and Y directions
property PrinterPxPerInch: TPoint read fPrinterPxPerInch;
{$ifdef USEPDFPRINTER}
/// true if any printer appears to be a PDF printer
property HasPDFPrinterInstalled: boolean read fHasPDFPrinterInstalled;
{$else}
/// this property can force saving all bitmaps as JPEG in exported PDF
// - by default, this property is set to 0 by the constructor of this class,
// meaning that the JPEG compression is not forced, and the engine will use
// the native resolution of the bitmap - in this case, the resulting
// PDF file content will be bigger in size (e.g. use this for printing)
// - 60 is the prefered way e.g. for publishing PDF over the internet
// - 80/90 is a good ration if you want to have a nice PDF to see on screen
// - of course, this doesn't affect vectorial (i.e. emf) pictures
property ExportPDFForceJPEGCompression: integer read fForceJPEGCompression write fForceJPEGCompression;
/// optional application name used during Export to PDF
// - if not set, global Application.Title will be used
property ExportPDFApplication: string read fExportPDFApplication write fExportPDFApplication;
/// optional Author name used during Export to PDF
property ExportPDFAuthor: string read fExportPDFAuthor write fExportPDFAuthor;
/// optional Subject text used during Export to PDF
property ExportPDFSubject: string read fExportPDFSubject write fExportPDFSubject;