forked from synopse/mORMot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SynPdf.pas
11266 lines (10467 loc) · 405 KB
/
SynPdf.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
/// PDF file generation
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynPdf;
{
This file is part of Synopse framework.
Synopse framework. Copyright (C) 2017 Arnaud Bouchez
Synopse Informatique - https://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 Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (C) 2017
the Initial Developer. All Rights Reserved.
Contributor(s):
Achim Kalwa
Alexander (chaa)
aweste
CoMPi
Damien (ddemars)
David Mead (MDW)
David Heffernan
FalconB
Florian Grummel
Harald Simon
Josh Kelley (joshkel)
Karel (vandrovnik)
LoukaO
Marsh
MChaos
Mehrdad Momeni (nosa)
mogulza
Nzsolt
Ondrej (reddwarf)
Pierre le Riche
Sinisa (sinisav)
Sundazer
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 *****
Sponsors: https://synopse.info/fossil/wiki?name=HelpDonate
Ongoing development and maintenance of the SynPDF library was sponsored
in part by:
http://www.helpndoc.com
Easy to use yet powerful help authoring environment which can generate
various documentation formats from a single source.
Thanks for your contribution!
Version 1.7
- first public release, corresponding to SQLite3 Framework 1.7
Version 1.7.2
- can use the Windows Uniscribe API to render Ordering and Shaping of the text
(see USE_UNISCRIBE conditional below)
Version 1.7.3
- issue corrected in TPdfEnum.DrawBitmap() method - occured e.g. when drawing
a bitmap using a VCLCanvas
- rare issue corrected in TPdfWrite.AddUnicodeHexTextUniScribe() method
Version 1.7.4
- added TPdfBox with Width and Height properties
- minor corrections in Uniscribe part of the rendering engine
Version 1.7.4.RTL
- added RightToLeftText property in TPdfCanvas (Uniscribe-only)
- handle ETO_RTLREADING option (Uniscribe-only) in VCLCanvas/TMetaFile
Version 1.8
- font substitution if the font is not existing in the system (worse case
will use Arial for all fonts)
- now handle ETO_GLYPH_INDEX in metafile rendering
Version 1.8.1 - features added by contribution of REDDWARF / ONDREJ - THANKS!
- new feature: allow forced JPEG compression for graphics
- new feature: UNDERLINE + STRIKEOUT support (also in RICH TEXT and rotated text !)
- new USE_SYNGDIPLUS conditional if you want to use the default jpeg unit
instead of our SynGdiPlus (but you loose TIF, PNG, and GIF support)
- enhanced: PenWidth changed to Single -> better precision (e.g. for underlined text)
- fix issue: Rotated text was misplaced for some angles
- some small fixes about FillRect() + scaling, and move/line stroke
- REDDWARF / ONDREJ made a very good work - I had very few thinks to rewrite
Version 1.8.2
- added optional XOff,YOff parameters to RenderMetaFile()
Version 1.8.3
- now handle EMR_STRETCHDIBITS (used in Html2Pdf)
- fix strike out line position (was too low)
Version 1.8.4
- fixed TextWidth() and TextMeasure()
Version 1.8.5
- fixed font enumeration problem (triggered with asiatic windows)
Version 1.8.6
- system font enumeration is now stored using UTF-8, and any non ASCII font
name will used in the PDF content the official Postscript name extracted
from its TrueType font content
- optional charset parameter is now available in TPdfCanvas.SetFont: this
was needed in case of TMetaFile rendering to fix some encoding problems
Version 1.8.7
- bitmap embedding fix - see https://synopse.info/forum/viewtopic.php?pid=237
- now initializes the Gdi+ library if necessary
Version 1.8.8
- fix small issue with font orientation in metafile enumeration
Version 1.10
- new TPdfImage.CreateJpegDirect method and PixelWidth/PixelHeight properties
Version 1.11
- unit won't need Printers unit any more (so can get rid of Forms and others)
- source code modified to be 7 bit Ansi (so will work with all encodings)
Version 1.12
- can now generate PDF/A-1 files if the new PDFA1 property is set to true
- new CreateLink and CreateBookMark methods for TPdfDocument, to easily
handle bookmarks and links
- new CreateOutline method for TPdfDocument, for direct outline adding
- new TPdfPage.PageLandscape and TPdfDocument.DefaultPageLandscape properties
- can use EMR_GDICOMMENT to embedd some SynPDF related data (like bookmarks,
links, and document outline) in the source TMetaFile - used by TSQLite3Pages
- new TPdfTextString class, used to handle Unicode parameters (e.g. in
TPdfInfo, which properties are now handling unicode encoding as expected)
- new CreateOrGetImage method to easily add a bitmap to the page, with
internal caching: if the same bitmap content is sent more than once, only
one TPDFImage will be used (used for emf enumeration, e.g. SQLite3Pages)
- now handle justified text from metafile (i.e. call to SetTextJustification
Windows API will change the PDF word space as expected)
- Uniscribe API now made public (and documented as such), for TRenderPages
- fixed memory leak in TPdfOutlineRoot.Create
- fixed issue in TPdfDocumentGDI.VCLCanvasSize
- fixed issue with fixed-width font unicode characters display
- FontSub.dll library is loaded only once for the whole application
Version 1.13
- code modifications to compile with Delphi 5 compiler
- added horizontal scaling for GDI enumeration in case of text kerning (could
occur for small fonts)
- fixed "Save when closing with Acrobat Reader X" - thanks to Ondrej
- fixed clipping problems and vertical font positioning issue in GDI
enumeration - thanks to Ondrej for those corrections!
Version 1.14
- new SetCMYKFillColor and SetCMYKStrokeColor methods for TPdfCanvas
- now handles EMR_POLYBEZIER* commands in conversion from meta file content
- fixed EZeroDivided error when enumerating SetWindowExtEx(szlExtent(0,0))
- some enhancements for better PDF/A-1 conformance to the standard: now
includes the ICC profile for RGB pictures; corrected /Link flag and XML
metadata; new header with 8 bit characters; correct outlines and other
minor issues: now pass www.pdf-tools.com/pdf/pdfa-online-pruefen.aspx test
Version 1.15
- unit now tested with Delphi XE2 (32 Bit)
Version 1.16
- includes new TSynAnsiConvert classes for handling Ansi charsets
- do not stop TMetaFile enumeration in case of invalid EMF content (e.g.
if the EMR_SELECTOBJECT refers to an out-of-range object): this is
the default behavior of GDI and GDI+ renders (and our SynGdiPlus), so
we'll stay to it - may fix issue with some badly formatted objects - also
made the TMetaFile rendering stronger to badly formated EMF input
- fixed issue in TPdfDocument.CreateOrGetImage about guessing if a bitmap is
to be reused as a pdf object
- added TPdfDocument.ForceNoBitmapReuse property
- added a "Decimals: cardinal=6" parameter to TPdfCanvas.ConcatToCTM
- TPdfCanvas.SetDash parameter is now an array of integer
- set PDF_MAX_FONTSIZE limit to 2000 - should be big enough in practice
- fixed an issue when handling bitmap palette
- fixed an issue when the first time a font was used is as Unicode
- fixed a potential GPF issue in function HashOf() in PUREPASCAL mode (used
to reuse any existing bitmap content within the PDF document)
Version 1.17
- new TPdfDocument.UseFontFallBack property (enabled by default) and
associated FontFallBackName property (set to 'Arial Unicode MS' by default),
used to define if the PDF document will handle "font fallback" for characters
not existing in the current font: it will avoid rendering block/square
symbols instead of the correct characters (e.g. for Chinese text)
- now handle device or bitmap fonts as the most close true-type font available
- speed-up of internal true-type fonts list (using binary search)
- SynPdf unit can now link to standard ZLib.pas unit if you want to use SynPdf
stand-alone and do not need SynZip.pas + deflate.obj + trees.obj
(but SQLite3Commons.pas main unit of mORMot will need SynZip, so it is
enabled by default for use within the framework)
Version 1.18
- BREAKING CHANGE of TPdfCanvas.RenderMetaFile() by spliting Scale parameter
into specific ScaleX, ScaleY values
- major speed up of TPdfCanvas.RenderMetaFile() by caching printer resolution
- implemented 40 bit and 128 bit security - see TPdfEncryption.New()
- introducing TPdfDocument.SaveToStreamDirectBegin/PageFlush/End methods,
able to render all page content directly to the destination stream/file,
therefore reducing the memory use to a minimal value for huge content - used
e.g. in TPdfDocumentGDI.SaveToStream() and TGDIPages.ExportPDFStream()
- TPdfDocumentGDI will now compress (via our SynLZ algorithm) all its page
content (TMetaFile) for efficiency
- TPdfDocumentGDI.SaveToStreamDirectPageFlush overridden method could be used
to reduce the used memory even more, by-passing page content compression
- therefore, TPdfDocumentGDI will use much less resource and memory with no
swaping to disk (tested with 200,000 simple text pages)
- reduced generated file size, with optional PDFGeneratePDF15File property
- embedd ttc fonts [d2d6953fb3] - thanks David Mead (MDW) for the patch
- fixed incorrect Postscript font name retrieval e.g. for Asiatic fonts
- fixed potential GPF issue in TPdfWrite.AddUnicodeHex and TPdfWrite.AddHex
- fixed compilation warnings regarding Delphi XE3 regressions
- fixed text color process in TPdfEnum
- handle inverted y-axis for TPdfEnum.TextOut (used e.g. for MM_LOMETRIC
compatible rendering as reported by [52c37cc5a14] and fixed by Florian)
- fixed mixed portrait/landscape page rendering within a same document
- fixed invalid ScriptShape() API error when UniScribe is true
- use TSynAnsiConvert class for internal multi-byte conversion (better speed)
- Several fixes and enhancements by Sinisa (sinisav):
- fixes are mostly for embeded metafiles
- added World Transformation matrix
- fixed scaling objects (bitmaps, pen, text)
- fixed text positioning
- added region/clipping support
- added graphics/mapping mode
- add new enum items: EMR_POLYPOLYGON, EMR_POLYPOLYLINE, EMR_POLYPOLYGON16,
EMR_POLYPOLYLINE16, EMR_GRADIENTFILL, EMR_MODIFYWORLDTRANSFORM, EMR_EXTCREATEPEN,
EMR_SETMITERLIMIT, EMR_SETMETARGN, EMR_EXTSELECTCLIPRGN, EMR_INTERSECTCLIPRECT,
EMR_SETMAPMODE, EMR_BEGINPATH, EMR_ENDPATH, EMR_ABORTPATH, EMR_CLOSEFIGURE,
EMR_FILLPATH, EMR_STROKEPATH, EMR_STROKEANDFILLPATH, EMR_SETPOLYFILLMODE,
EMR_SETSTRETCHBLTMODE, EMR_SETARCDIRECTION, EMR_POLYLINETO, EMR_POLYLINETO16,
- fixed EMR_POLYBEZIER* and moveto action (new way to mark when processed - when
coordinates are set to use Point(0,0) )
- fixed null pen and not stroke
- few more issues still remains (gradient fill, some text size issues...)
- added EMR_POLYDRAW, EMR_POLYDRAW16 process (from CoMPi proposal - thanks!)
- added EMR_FILLRGN process (from RyanC proposal - thanks for the feedback!)
- some fixes and added EMR_TRANSPARENTBLT + mirrored bitmaps (patch from Chaa)
- added EMR_SETBKMODE/EMR_SETBKCOLOR process - see ticket [487767008a]
- fix for EMR_SET*COLOR clNone color rendering (patch from vmkmg)
- fixed SYMBOL_CHARSET kind of fonts (e.g. bullets from Symbol font)
- fixed EMR_TEXTOUT rotated text positioning (patch pkrott)
- added PdfCoord() function
- increased allowed number of EMR_SAVEDC/EMR_RESTOREDC pairs during rendering
- handle SetTextAlign(TA_UPDATECP) command for feature request [a8d7393af1]
- fix vertical text alignment and line drawing (patch from ddemars - thanks!)
- introducing TPdfDocumentGDI.UseMetaFileTextPositioning instead of former
UseSetTextJustification property: now you can force exact font kerning
positioning for each character, via tpExactTextCharacterPositining; this
parameter has been also added to TPdfCanvas.RenderMetaFile() - it will
produce bigger pdf file size, but will fulfill feature request [7d6a3a3f0f]
- fixed text clipping - thanks Pierre for the patch!
- added TPdfDocumentGDI.UseMetaFileTextClipping property and corresponding
optional parameter to TPdfCanvas.RenderMetaFile()
- added vpEnforcePrintScaling to TPdfViewerPreferences set - forcing PDF 1.6 -
thanks MChaos for the proposal!
- added Harald Simon's patch for EMR_BITBLT/EMR_STRETCHBLT
- added PDF Group Content methods for creating layered content - thanks
Harald for the patch! see SynPdfLayers.dpr in sample 05
- added TPdfFormWithCanvas class - thanks Harald! see SynPdfFormCanvas.dpr
- EMR_INTERSECTCLIPRECT fix supplied by Marsh - but patch disabled by default
- huge UniScribe fixes supplied by Mehrdad Momeni (nosa) - THANKS A LOT!
- enhanced clipping process by Achim Kalwa
- added Support for ARC ARCTO PIE and CHORD - thanks ProHolz for the patch
}
{$I Synopse.inc} // define HASINLINE USETYPEINFO CPU32 CPU64
{$ifndef MSWINDOWS}
{ disable features requiring OS specific APIs
- until they are implemented }
{$define NO_USE_SYNGDIPLUS}
{$define NO_USE_UNISCRIBE}
{$define NO_USE_METAFILE}
{$define NO_USE_BITMAP}
{$endif}
{$define USE_PDFSECURITY}
{ - if defined, the TPdfDocument*.Create() constructor will have an additional
AEncryption: TPdfEncryption parameter able to create secured PDF files
- this feature will link the SynCrypto unit for MD5 and RC4 algorithms }
{$ifdef NO_USE_PDFSECURITY}
{ this special conditional can be set globaly for an application which doesn't
need the security features, therefore dependency to SynCrypto unit }
{$undef USE_PDFSECURITY}
{$endif}
{$define USE_UNISCRIBE}
{ - if defined, the PDF engine will use the Windows Uniscribe API to
render Ordering and Shaping of the text (useful for Hebrew, Arabic and
some Asiatic languages)
- this feature need the TPdfDocument.UseUniscribe property to be forced to true
according to the language of the text you want to render
- can be undefined to safe some KB if you're sure you won't need it }
{$ifdef NO_USE_UNISCRIBE}
{ this special conditional can be set globaly for an application which doesn't
need the UniScribe features }
{$undef USE_UNISCRIBE}
{$endif}
{$define USE_SYNGDIPLUS}
{ - if defined, the PDF engine will use SynGdiPlus to handle all
JPG, TIF, PNG and GIF image types (prefered way, but need XP or later OS)
- if you'd rather use the default jpeg unit (and add some more code to your
executable), undefine this conditional }
{$ifdef NO_USE_SYNGDIPLUS}
{ this special conditional can be set globaly for an application which doesn't
need the SynGdiPlus features (like TMetaFile drawing), and would rather
use the default jpeg unit }
{$undef USE_SYNGDIPLUS}
{$endif}
{$define USE_SYNZIP}
{ - if defined, the PDF engine will use SynZip to handle the ZIP/deflate
compression schema (this unit is faster than the default ZLib unit,
and used by other units of the framework)
- if you'd rather use the default ZLib unit (and add some more code to your
executable), undefine this conditional }
{$ifdef NO_USE_SYNZIP}
{ this special conditional can be set globaly for an application for which
standard ZLib unit is enough (not to be used with a mORMot application) }
{$undef USE_SYNZIP}
{$endif}
{$define USE_BITMAP}
{ - if defined, the PDF engine will support TBitmap
- it would induce a dependency to the VCL.Graphics unit }
{$ifdef NO_USE_BITMAP}
{ this special conditional can be set globaly for an application which doesn't
need the TBitmap features }
{$undef USE_BITMAP}
{$endif}
{$define USE_METAFILE}
{ - if defined, the PDF engine will support TMetaFile/TMetaFileCanvas
- it would induce a dependency to the VCL.Graphics unit }
{$ifdef NO_USE_METAFILE}
{ this special conditional can be set globaly for an application which doesn't
need the TMetaFile features }
{$undef USE_METAFILE}
{$endif}
{$define USE_ARC}
{ - if defined, the PDF engine will support ARC, inducing a dependency to Math.pas }
{$ifdef NO_USE_ARC}
{$undef USE_ARC}
{$endif}
{$ifdef USE_BITMAP}
{$define USE_GRAPHICS_UNIT}
{$endif}
{$ifdef USE_METAFILE}
{$define USE_GRAPHICS_UNIT}
{$endif}
interface
uses
{$ifdef MSWINDOWS}
Windows,
WinSpool,
{$ifdef USE_GRAPHICS_UNIT}
{$ifdef ISDELPHIXE2}
VCL.Graphics,
{$else}
Graphics,
{$endif}
{$endif}
{$endif MSWINDOWS}
{$ifdef USE_SYNGDIPLUS}
SynGdiPlus, // use our GDI+ library for handling TJpegImage and such
{$else}
jpeg,
{$endif}
SysConst,
SysUtils,
Classes,
{$ifdef USE_ARC}
Math,
{$endif}
{$ifdef ISDELPHIXE3}
System.Types,
System.AnsiStrings,
{$else}
{$ifdef HASINLINE}
Types,
{$endif}
{$endif}
{$ifdef USE_SYNZIP}
SynZip,
{$else}
ZLib,
{$endif}
{$ifdef USE_PDFSECURITY}
SynCrypto,
{$endif}
SynCommons,
SynLZ;
const
MWT_IDENTITY = 1;
MWT_LEFTMULTIPLY = 2;
MWT_RIGHTMULTIPLY = 3;
MWT_SET = 4;
{$NODEFINE MWT_IDENTITY}
{$NODEFINE MWT_LEFTMULTIPLY}
{$NODEFINE MWT_RIGHTMULTIPLY}
{ some low-level record definition for True Type format table reading }
type
PSmallIntArray = ^TSmallIntArray;
TSmallIntArray = array[byte] of SmallInt;
PPointArray = ^TPointArray;
TPointArray = array[word] of TPoint;
PSmallPointArray = ^TSmallPointArray;
TSmallPointArray = array[word] of TSmallPoint;
/// The 'cmap' table begins with an index containing the table version number
// followed by the number of encoding tables. The encoding subtables follow.
TCmapHeader = packed record
/// Version number (Set to zero)
version: word;
/// Number of encoding subtables
numberSubtables: word;
end;
/// points to every 'cmap' encoding subtables
TCmapSubTableArray = packed array[byte] of packed record
/// Platform identifier
platformID: word;
/// Platform-specific encoding identifier
platformSpecificID: word;
/// Offset of the mapping table
offset: Cardinal;
end;
/// The 'hhea' table contains information needed to layout fonts whose
// characters are written horizontally, that is, either left to right or
// right to left
TCmapHHEA = packed record
version: longint;
ascent: word;
descent: word;
lineGap: word;
advanceWidthMax: word;
minLeftSideBearing: word;
minRightSideBearing: word;
xMaxExtent: word;
caretSlopeRise: SmallInt;
caretSlopeRun: SmallInt;
caretOffset: SmallInt;
reserved: Int64;
metricDataFormat: SmallInt;
numOfLongHorMetrics: word;
end;
/// The 'head' table contains global information about the font
TCmapHEAD = packed record
version: longint;
fontRevision: longint;
checkSumAdjustment: cardinal;
magicNumber: cardinal;
flags: word;
unitsPerEm: word;
createdDate: Int64;
modifiedDate: Int64;
xMin: SmallInt;
yMin: SmallInt;
xMax: SmallInt;
yMax: SmallInt;
macStyle: word;
lowestRec: word;
fontDirection: SmallInt;
indexToLocFormat: SmallInt;
glyphDataFormat: SmallInt
end;
/// header for the 'cmap' Format 4 table
// - this is a two-byte encoding format
TCmapFmt4 = packed record
format: word;
length: word;
language: word;
segCountX2: word;
searchRange: word;
entrySelector: word;
rangeShift: word;
end;
type
/// the PDF library use internaly AnsiString text encoding
// - the corresponding charset is the current system charset, or the one
// supplied as a parameter to TPdfDocument.Create
PDFString = AnsiString;
/// a PDF date, encoded as 'D:20100414113241'
TPdfDate = PDFString;
/// the internal pdf file format
TPdfFileFormat = (pdf13, pdf14, pdf15, pdf16);
/// PDF exception, raised when an invalid value is given to a constructor
EPdfInvalidValue = class(Exception);
/// PDF exception, raised when an invalid operation is triggered
EPdfInvalidOperation = class(Exception);
/// Page mode determines how the document should appear when opened
TPdfPageMode = (
pmUseNone, pmUseOutlines, pmUseThumbs, pmFullScreen);
/// Line cap style specifies the shape to be used at the ends of open
// subpaths when they are stroked
TLineCapStyle = (
lcButt_End, lcRound_End, lcProjectingSquareEnd);
/// The line join style specifies the shape to be used at the corners of paths
// that are stroked
TLineJoinStyle = (
ljMiterJoin, ljRoundJoin, ljBevelJoin);
/// The text rendering mode determines whether text is stroked, filled, or used
// as a clipping path
TTextRenderingMode = (
trFill, trStroke, trFillThenStroke, trInvisible,
trFillClipping, trStrokeClipping, trFillStrokeClipping, trClipping);
/// The annotation types determines the valid annotation subtype of TPdfDoc
TPdfAnnotationSubType = (
asTextNotes, asLink);
/// The border style of an annotation
TPdfAnnotationBorder = (
abSolid, abDashed, abBeveled, abInset, abUnderline);
/// Destination Type determines default user space coordinate system of
// Explicit destinations
TPdfDestinationType = (
dtXYZ, dtFit, dtFitH, dtFitV, dtFitR, dtFitB, dtFitBH, dtFitBV);
/// The page layout to be used when the document is opened
TPdfPageLayout = (
plSinglePage, plOneColumn, plTwoColumnLeft, plTwoColumnRight);
/// Viewer preferences specifying how the reader User Interface must start
// - vpEnforcePrintScaling will set the file version to be PDF 1.6
TPdfViewerPreference = (
vpHideToolbar, vpHideMenubar, vpHideWindowUI, vpFitWindow, vpCenterWindow,
vpEnforcePrintScaling);
/// set of Viewer preferences
TPdfViewerPreferences = set of TPdfViewerPreference;
/// available known paper size (psA4 is the default on TPdfDocument creation)
TPDFPaperSize = (
psA4, psA5, psA3, psA2, psA1, psA0, psLetter, psLegal, psUserDefined);
/// define if streams must be compressed
TPdfCompressionMethod = (
cmNone, cmFlateDecode);
/// the available PDF color range
TPdfColor = -$7FFFFFFF-1..$7FFFFFFF;
/// the PDF color, as expressed in RGB terms
// - maps COLORREF / TColorRef as used e.g. under windows
TPdfColorRGB = cardinal;
/// numerical ID for every XObject
TXObjectID = integer;
const
/// used for an used xref entry
PDF_IN_USE_ENTRY = 'n';
/// used for an unused (free) xref entry, e.g. the root entry
PDF_FREE_ENTRY = 'f';
/// used e.g. for the root xref entry
PDF_MAX_GENERATION_NUM = 65535;
PDF_ENTRY_CLOSED = 0;
PDF_ENTRY_OPENED = 1;
/// the Carriage Return and Line Feed values used in the PDF file generation
// - expect #13 and #10 under Windows, but #10 (e.g. only Line Feed) is enough
// for the PDF standard, and will create somewhat smaller PDF files
CRLF = #10;
/// the Line Feed value
LF = #10;
PDF_MIN_HORIZONTALSCALING = 10;
PDF_MAX_HORIZONTALSCALING = 300;
PDF_MAX_WORDSPACE = 300;
PDF_MIN_CHARSPACE = -30;
PDF_MAX_CHARSPACE = 300;
PDF_MAX_FONTSIZE = 2000;
PDF_MAX_ZOOMSIZE = 10;
PDF_MAX_LEADING = 300;
/// list of common fonts available by default since Windows 2000
// - to not embedd these fonts in the PDF document, and save some KB,
// just use the EmbeddedTTFIgnore property of TPdfDocument/TPdfDocumentGDI:
// ! PdfDocument.EmbeddedTTFIgnore.Text := MSWINDOWS_DEFAULT_FONTS;
// - note that this is useful only if the EmbeddedTTF property was set to TRUE
MSWINDOWS_DEFAULT_FONTS: RawUTF8 =
'Arial'#13#10'Courier New'#13#10'Georgia'#13#10+
'Impact'#13#10'Lucida Console'#13#10'Roman'#13#10'Symbol'#13#10+
'Tahoma'#13#10'Times New Roman'#13#10'Trebuchet'#13#10+
'Verdana'#13#10'WingDings';
type
/// PDF text paragraph alignment
TPdfAlignment = (paLeftJustify, paRightJustify, paCenter);
/// PDF gradient direction
TGradientDirection = (gdHorizontal, gdVertical);
/// a PDF coordinates rectangle
TPdfRect = record
Left, Top, Right, Bottom: Single;
end;
PPdfRect = ^TPdfRect;
/// a PDF coordinates box
TPdfBox = record
Left, Top, Width, Height: Single;
end;
PPdfBox = ^TPdfBox;
/// allowed types for PDF objects (i.e. TPdfObject)
TPdfObjectType = (otDirectObject, otIndirectObject, otVirtualObject);
TPdfObject = class;
TPdfCanvas = class;
TPdfFont = class;
TPdfFontTrueType = class;
TPdfDocument = class;
{$ifdef USE_PDFSECURITY}
/// the available encryption levels
// - in current version only RC4 40-bit and RC4 128-bit are available, which
// correspond respectively to PDF 1.3 and PDF 1.4 formats
// - for RC4 40-bit and RC4 128-bit, associated password are restricted to a
// maximum length of 32 characters and could contain only characters from the
// Latin-1 encoding (i.e. no accent)
TPdfEncryptionLevel = (elNone, elRC4_40, elRC4_128);
/// PDF can encode various restrictions on document operations which can be
// granted or denied individually (some settings depend on others, though):
// - Printing: If printing is not allowed, the print button in Acrobat will be
// disabled. Acrobat supports a distinction between high-resolution and
// low-resolution printing. Low-resolution printing generates a bitmapped
// image of the page which is suitable only for personal use, but prevents
// high-quality reproduction and re-distilling. Note that bitmap printing
// not only results in low output quality, but will also considerably slow
// down the printing process.
// - General Editing: If this is disabled, any document modification is
// prohibited. Content extraction and printing are allowed.
// - Content Copying and Extraction: If this is disabled, selecting document
// contents and copying it to the clipboard for repurposing the contents is
// prohibited. The accessibility interface also is disabled. If you need to
// search such documents with Acrobat you must select the Certified Plugins
// Only preference in Acrobat.
// - Authoring Comments and Form Fields: If this is disabled, adding,
// modifying, or deleting comments and form fields is prohibited. Form field
// filling is allowed.
// - Form Field Fill-in or Signing: If this is enabled, users can sign and
// fill in forms, but not create form fields.
// - Document Assembly: If this is disabled, inserting, deleting or rotating
// pages, or creating bookmarks and thumbnails is prohibited.
TPdfEncryptionPermission = (epPrinting, epGeneralEditing, epContentCopy,
epAuthoringComment, epFillingForms, epContentExtraction,
epDocumentAssembly, epPrintingHighResolution);
/// set of restrictions on PDF document operations
TPdfEncryptionPermissions = set of TPdfEncryptionPermission;
/// abstract class to handle PDF security
TPdfEncryption = class
protected
fLevel: TPdfEncryptionLevel;
fFlags: integer;
fInternalKey: TByteDynArray;
fPermissions: TPdfEncryptionPermissions;
fUserPassword: string;
fOwnerPassword: string;
fDoc: TPdfDocument;
procedure EncodeBuffer(const BufIn; var BufOut; Count: cardinal); virtual; abstract;
public
/// initialize the internal structures with the proper classes
// - do not call this method directly, but class function TPdfEncryption.New()
constructor Create(aLevel: TPdfEncryptionLevel; aPermissions: TPdfEncryptionPermissions;
const aUserPassword, aOwnerPassword: string); virtual;
/// prepare a specific document to be encrypted
// - internally used by TPdfDocument.NewDoc method
procedure AttachDocument(aDoc: TPdfDocument); virtual;
/// will create the expected TPdfEncryption instance, depending on aLevel
// - to be called as parameter of TPdfDocument/TPdfDocumentGDI.Create()
// - currently, only elRC4_40 and elRC4_128 levels are implemented
// - both passwords are expected to be ASCII-7 characters only
// - aUserPassword will be asked at file opening: to be set to '' for not
// blocking display, but optional permission
// - aOwnerPassword shall not be '', and will be used internally to cypher
// the pdf file content
// - aPermissions can be either one of the PDF_PERMISSION_ALL /
// PDF_PERMISSION_NOMODIF / PDF_PERSMISSION_NOPRINT / PDF_PERMISSION_NOCOPY /
// PDF_PERMISSION_NOCOPYNORPRINT set of options
// - typical use may be:
// ! Doc := TPdfDocument.Create(false,0,false,
// ! TPdfEncryption.New(elRC4_40,'','toto',PDF_PERMISSION_NOMODIF));
// ! Doc := TPdfDocument.Create(false,0,false,
// ! TPdfEncryption.New(elRC4_128,'','toto',PDF_PERMISSION_NOCOPYNORPRINT));
class function New(aLevel: TPdfEncryptionLevel;
const aUserPassword, aOwnerPassword: string;
aPermissions: TPdfEncryptionPermissions): TPdfEncryption;
end;
/// internal 32 bytes buffer, used during encryption process
TPdfBuffer32 = array[0..31] of byte;
/// handle PDF security with RC4+MD5 scheme in 40-bit and 128-bit
// - allowed aLevel parameters for Create() are only elRC4_40 and elRC4_128
TPdfEncryptionRC4MD5 = class(TPdfEncryption)
protected
fLastObjectNumber: integer;
fLastGenerationNumber: Integer;
fLastRC4Key: TRC4InternalKey;
fUserPass, fOwnerPass: TPdfBuffer32;
procedure EncodeBuffer(const BufIn; var BufOut; Count: cardinal); override;
public
/// prepare a specific document to be encrypted
// - will compute the internal keys
procedure AttachDocument(aDoc: TPdfDocument); override;
end;
{$endif}
/// buffered writer class, specialized for PDF encoding
TPdfWrite = class
protected
B, BEnd, BEnd4: PAnsiChar;
fDestStream: TStream;
fDestStreamPosition: integer;
fCodePage: integer;
fAddGlyphFont: (fNone, fMain, fFallBack);
fDoc: TPdfDocument;
Tmp: array[0..511] of AnsiChar;
/// internal Ansi->Unicode conversion, using the CodePage used in Create()
// - caller must release the returned memory via FreeMem()
function ToWideChar(const Ansi: PDFString; out DLen: Integer): PWideChar;
{$ifdef USE_UNISCRIBE}
/// internal method using the Windows Uniscribe API
// - return FALSE if PW was not appened to the PDF content, TRUE if OK
function AddUnicodeHexTextUniScribe(PW: PWideChar; WinAnsiTTF: TPdfFontTrueType;
NextLine: boolean; Canvas: TPdfCanvas): boolean;
{$endif}
/// internal method NOT using the Windows Uniscribe API
procedure AddUnicodeHexTextNoUniScribe(PW: PWideChar; TTF: TPdfFontTrueType;
NextLine: boolean; Canvas: TPdfCanvas);
/// internal methods handling font fall-back
procedure AddGlyphFromChar(Char: WideChar; Canvas: TPdfCanvas;
TTF: TPdfFontTrueType; NextLine: PBoolean);
procedure AddGlyphFlush(Canvas: TPdfCanvas; TTF: TPdfFontTrueType; NextLine: PBoolean);
public
/// create the buffered writer, for a specified destination stream
constructor Create(Destination: TPdfDocument; DestStream: TStream);
/// add a character to the buffer
function Add(c: AnsiChar): TPdfWrite; overload; {$ifdef HASINLINE}inline;{$endif}
/// add an integer numerical value to the buffer
function Add(Value: Integer): TPdfWrite; overload;
/// add an integer numerical value to the buffer
// - add a trailing space
function AddWithSpace(Value: Integer): TPdfWrite; overload;
/// add an integer numerical value to the buffer
// - with a specified fixed number of digits (left filled by '0')
function Add(Value, DigitCount: Integer): TPdfWrite; overload;
/// add a floating point numerical value to the buffer
// - up to 2 decimals are written
function Add(Value: TSynExtended): TPdfWrite; overload;
/// add a floating point numerical value to the buffer
// - up to 2 decimals are written, together with a trailing space
function AddWithSpace(Value: TSynExtended): TPdfWrite; overload;
/// add a floating point numerical value to the buffer
// - this version handles a variable number of decimals, together with
// a trailing space - this is used by ConcatToCTM e.g. or enhanced precision
function AddWithSpace(Value: TSynExtended; Decimals: cardinal): TPdfWrite; overload;
/// direct raw write of some data
// - no conversion is made
function Add(Text: PAnsiChar; Len: integer): TPdfWrite; overload;
/// direct raw write of some data
// - no conversion is made
function Add(const Text: RawByteString): TPdfWrite; overload;
/// hexadecimal write of some row data
// - row data is written as hexadecimal byte values, one by one
function AddHex(const Bin: PDFString): TPdfWrite;
/// add a word value, as Big-Endian 4 hexadecimal characters
function AddHex4(aWordValue: cardinal): TPdfWrite;
/// convert some text into unicode characters, then write it as as Big-Endian
// 4 hexadecimal characters
// - Ansi to Unicode conversion uses the CodePage set by Create() constructor
function AddToUnicodeHex(const Text: PDFString): TPdfWrite;
/// write some unicode text as as Big-Endian 4 hexadecimal characters
function AddUnicodeHex(PW: PWideChar; WideCharCount: integer): TPdfWrite;
/// convert some text into unicode characters, then write it as PDF Text
// - Ansi to Unicode conversion uses the CodePage set by Create() constructor
// - use (...) for all WinAnsi characters, or <..hexa..> for Unicode characters
// - if NextLine is TRUE, the first written PDF Text command is not Tj but '
// - during the text process, corresponding TPdfTrueTypeFont properties are
// updated (Unicode version created if necessary, indicate used glyphs for
// further Font properties writting to the PDF file content...)
// - if the current font is not True Type, all Unicode characters are
// drawn as '?'
function AddToUnicodeHexText(const Text: PDFString; NextLine: boolean;
Canvas: TPdfCanvas): TPdfWrite;
/// write some Unicode text, as PDF text
// - incoming unicode text must end with a #0
// - use (...) for all WinAnsi characters, or <..hexa..> for Unicode characters
// - if NextLine is TRUE, the first written PDF Text command is not Tj but '
// - during the text process, corresponding TPdfTrueTypeFont properties are
// updated (Unicode version created if necessary, indicate used glyphs for
// further Font properties writting to the PDF file content...)
// - if the current font is not True Type, all Unicode characters are
// drawn as '?'
function AddUnicodeHexText(PW: PWideChar; NextLine: boolean;
Canvas: TPdfCanvas): TPdfWrite;
/// write some Unicode text, encoded as Glyphs indexes, corresponding
// to the current font
function AddGlyphs(Glyphs: PWord; GlyphsCount: integer; Canvas: TPdfCanvas;
AVisAttrsPtr: Pointer=nil): TPdfWrite;
/// add some WinAnsi text as PDF text
// - used by TPdfText object
// - will optionally encrypt the content
function AddEscapeContent(const Text: RawByteString): TPdfWrite;
/// add some WinAnsi text as PDF text
// - used by TPdfText object
function AddEscape(Text: PAnsiChar; TextLen: integer): TPdfWrite;
/// add some WinAnsi text as PDF text
// - used by TPdfCanvas.ShowText method for WinAnsi text
function AddEscapeText(Text: PAnsiChar; Font: TPdfFont): TPdfWrite;
/// add some PDF /property value
function AddEscapeName(Text: PAnsiChar): TPdfWrite;
{$ifdef MSWINDOWS}
/// add a PDF color, from its TPdfColorRGB RGB value
function AddColorStr(Color: TPdfColorRGB): TPdfWrite;
{$endif}
/// add a TBitmap.Scanline[] content into the stream
procedure AddRGB(P: PAnsiChar; PInc, Count: integer);
/// add an ISO 8601 encoded date time (e.g. '2010-06-16T15:06:59-07:00')
function AddIso8601(DateTime: TDateTime): TPdfWrite;
/// add an integer value as binary, specifying a storage size in bytes
function AddIntegerBin(value: integer; bytesize: cardinal): TPdfWrite;
public
/// flush the internal buffer to the destination stream
procedure Save; {$ifdef HASINLINE}inline;{$endif}
/// return the current position
// - add the current internal buffer stream position to the destination
// stream position
function Position: Integer; {$ifdef HASINLINE}inline;{$endif}
/// get the data written to the Writer as a PDFString
// - this method could not use Save to flush the data, if all input was
// inside the internal buffer (save some CPU and memory): so don't intend
// the destination stream to be flushed after having called this method
function ToPDFString: PDFString;
end;
/// object manager is a virtual class to manage instance of indirect PDF objects
TPdfObjectMgr = class(TObject)
public
procedure AddObject(AObject: TPdfObject); virtual; abstract;
function GetObject(ObjectID: integer): TPdfObject; virtual; abstract;
end;
/// master class for most PDF objects declaration
TPdfObject = class(TObject)
private
FObjectType: TPdfObjectType;
FObjectNumber: integer;
FGenerationNumber: integer;
FSaveAtTheEnd: boolean;
protected
procedure InternalWriteTo(W: TPdfWrite); virtual;
procedure SetObjectNumber(Value: integer);
function SpaceNotNeeded: boolean; virtual;
public
/// create the PDF object instance
constructor Create; virtual;
/// Write object to specified stream
// - If object is indirect object then write references to stream
procedure WriteTo(var W: TPdfWrite);
/// write indirect object to specified stream
// - this method called by parent object
procedure WriteValueTo(var W: TPdfWrite);
/// low-level force the object to be saved now
// - you should not use this low-level method, unless you want to force
// the FSaveAtTheEnd internal flag to be set to force, so that
// TPdfDocument.SaveToStreamDirectPageFlush would flush the object content
procedure ForceSaveNow;
/// the associated PDF Object Number
// - If you set an object number higher than zero, the object is considered
// as indirect. Otherwise, the object is considered as direct object.
property ObjectNumber: integer read FObjectNumber write SetObjectNumber;
/// the associated PDF Generation Number
property GenerationNumber: integer read FGenerationNumber;
/// the corresponding type of this PDF object
property ObjectType: TPdfObjectType read FObjectType;
end;
/// a virtual PDF object, with an associated PDF Object Number
TPdfVirtualObject = class(TPdfObject)
public
constructor Create(AObjectId: integer); reintroduce;
end;
/// a PDF object, storing a boolean value
TPdfBoolean = class(TPdfObject)
private
FValue: boolean;
protected
procedure InternalWriteTo(W: TPdfWrite); override;
public
constructor Create(AValue: Boolean); reintroduce;
property Value: boolean read FValue write FValue;
end;
/// a PDF object, storing a NULL value
TPdfNull = class(TPdfObject)
protected
procedure InternalWriteTo(W: TPdfWrite); override;
end;
/// a PDF object, storing a numerical (integer) value
TPdfNumber = class(TPdfObject)
private
FValue: integer;
protected
procedure InternalWriteTo(W: TPdfWrite); override;
public
constructor Create(AValue: Integer); reintroduce;
property Value: integer read FValue write FValue;
end;
/// a PDF object, storing a numerical (floating point) value
TPdfReal = class(TPdfObject)
private
FValue: double;
protected
procedure InternalWriteTo(W: TPdfWrite); override;
public
constructor Create(AValue: double); reintroduce;
property Value: double read FValue write FValue;
end;
/// a PDF object, storing a textual value
// - the value is specified as a PDFString
// - this object is stored as '(escapedValue)'
// - in case of MBCS, conversion is made into Unicode before writing, and
// stored as '<FEFFHexUnicodeEncodedValue>'
TPdfText = class(TPdfObject)
private
FValue: RawByteString;
protected
procedure InternalWriteTo(W: TPdfWrite); override;
function SpaceNotNeeded: boolean; override;
public
constructor Create(const AValue: RawByteString); reintroduce;
property Value: RawByteString read FValue write FValue;
end;
/// a PDF object, storing a textual value
// - the value is specified as an UTF-8 encoded string
// - this object is stored as '(escapedValue)'
// - in case characters with ANSI code higher than 8 Bits, conversion is made
// into Unicode before writing, and '<FEFFHexUnicodeEncodedValue>'