-
-
Notifications
You must be signed in to change notification settings - Fork 136
/
mormot.ui.pdf.pas
12365 lines (11569 loc) · 406 KB
/
mormot.ui.pdf.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 on Windows
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.ui.pdf;
{
*****************************************************************************
High Performance PDF Engine for Windows
- Shared types and functions
- Internal classes mapping PDF objects
- TPdfDocument TPdfPage main rendering classes
- TPdfDocumentGdi for GDI/TCanvas rendering support
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
{$ifdef OSPOSIX}
// do-nothing-unit on non Windows system
implementation
{$else}
{$define USE_PDFSECURITY}
// if defined, the TPdfDocument*.Create() constructor will have an additional
// AEncryption: TPdfEncryption parameter able to create secured PDF files
// - this feature links mormot.crypt.core.pas 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 mormot.crypt.core.pas
{$undef USE_PDFSECURITY}
{$endif NO_USE_PDFSECURITY}
{$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 does
// not need the UniScribe features
{$undef USE_UNISCRIBE}
{$endif USE_UNISCRIBE}
{$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 USE_SYNGDIPLUS}
{$define USE_METAFILE}
// if defined, the PDF engine will support TMetaFile / TPdfDocumentGdi
{$ifdef NO_USE_METAFILE}
// this special conditional can be set globaly for an application which
// doesn't need the TMetaFile / TPdfDocumentGdi features
{$undef USE_METAFILE}
{$endif USE_METAFILE}
{$define USE_GRAPHICS_UNIT} // VCL/LCL usage is mandatory by now at low level
uses
{$ifdef OSWINDOWS}
windows,
winspool,
{$ifdef USE_UNISCRIBE}
mormot.lib.uniscribe,
{$endif USE_UNISCRIBE}
{$endif OSWINDOWS}
{$ifdef USE_GRAPHICS_UNIT}
{$ifdef FPC}
lcltype,
lclproc,
lclintf,
rtlconsts,
{$ifdef USE_METAFILE}
mormot.ui.core, // for TMetaFile definition
{$endif USE_METAFILE}
{$else}
{$endif FPC}
{$ifdef NEEDVCLPREFIX}
vcl.graphics,
{$else}
graphics,
{$endif NEEDVCLPREFIX}
{$endif USE_GRAPHICS_UNIT}
sysutils,
types,
classes,
variants,
math,
{$ifdef USE_PDFSECURITY}
mormot.crypt.core,
{$endif USE_PDFSECURITY}
{$ifdef USE_SYNGDIPLUS}
mormot.ui.gdiplus,
{$else}
jpeg,
{$endif USE_SYNGDIPLUS}
mormot.core.base,
mormot.core.os,
mormot.lib.z,
mormot.core.unicode,
mormot.core.text,
mormot.core.datetime,
mormot.core.buffers,
mormot.core.data;
{************ Shared types and functions }
type
/// the PDF library uses internaly AnsiString text encoding
// - the corresponding charset/codepage is the current system charset, or
// the one supplied as a parameter to TPdfDocument.Create
PdfString = RawByteString;
/// a PDF date, encoded as 'D:20100414113241'
TPdfDate = PdfString;
{$ifdef FPC}
{ some FPC/Delphi LCL/VCL compatibility definitions }
type
// FPC wrappers are just pointless and confusing here
TPoint = TPOINTL;
PPoint = PPOINTL;
TRect = packed record
case integer of
0: (
Left, Top, Right, Bottom: integer
);
1: (
TopLeft, BottomRight: TPoint
);
2: (
Rect: Types.TRect
);
end;
PRect = ^TRect;
function Rect(ALeft, ATop, ARight, ABottom: integer): TRect;
{$ifdef HASINLINE} inline; {$endif}
function Point(X, Y: integer): TPoint;
{$ifdef HASINLINE} inline; {$endif}
{$endif FPC}
type
/// 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;
/// the internal pdf file format
TPdfFileFormat = (
pdf13,
pdf14,
pdf15,
pdf16,
pdf17);
/// the PDF/A level
TPdfALevel = (
pdfaNone,
pdfa1A,
pdfa1B,
pdfa2A,
pdfa2B,
pdfa3A,
pdfa3B);
/// PDF exception, raised when an invalid value is given to a constructor
EPdfInvalidValue = class(ESynException);
/// PDF exception, raised when an invalid operation is triggered
EPdfInvalidOperation = class(ESynException);
/// 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);
/// PDF text paragraph alignment
TPdfAlignment = (
paLeftJustify,
paRightJustify,
paCenter);
/// PDF gradient direction
TGradientDirection = (
gdHorizontal,
gdVertical);
/// allowed types for PDF objects (i.e. TPdfObject)
TPdfObjectType = (
otDirectObject,
otIndirectObject,
otVirtualObject);
/// 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;
/// the recognized families of the Standard 14 Fonts
TPdfFontStandard = (
pfsTimes,
pfsHelvetica,
pfsCourier);
/// numerical ID for every XObject
TXObjectID = integer;
/// is used to define how TMetaFile text positioning is rendered
// - tpSetTextJustification will handle efficiently the fact that TMetaFileCanvas
// used SetTextJustification() API calls to justify text: it will converted
// to SetWordSpace() pdf rendering
// - tpExactTextCharacterPositining will use the individual glyph positioning
// information as specified within the TMetaFile content: resulting pdf size
// will be bigger, but font kerning will be rendered as expected
// - tpKerningFromAveragePosition will use global font kerning via
// SetHorizontalScaling() pdf rendering
TPdfCanvasRenderMetaFileTextPositioning = (
tpKerningFromAveragePosition,
tpSetTextJustification,
tpExactTextCharacterPositining);
/// is used to define how TMetaFile text is clipped
// - by default, text will be clipped with the specified TEMRText.ptlReference
// - you could set tcClipExplicit to clip following the specified rclBounds
// - or tcAlwaysClip to use the current clipping region (if any)
// - finally, tcNeverClip would disable whole text clipping process, which
// has been reported to be preferred e.g. on Wine
TPdfCanvasRenderMetaFileTextClipping = (
tcClipReference,
tcClipExplicit,
tcAlwaysClip,
tcNeverClip);
/// is used to define the TMetaFile kind of arc to be drawn
TPdfCanvasArcType = (
acArc,
acArcTo,
acArcAngle,
acPie,
acChoord);
/// potential font styles
TPdfFontStyle = (
pfsBold,
pfsItalic,
pfsUnderline,
pfsStrikeOut);
/// set of font styles
TPdfFontStyles = set of TPdfFontStyle;
/// defines the data stored inside a EMR_GDICOMMENT message
// - pgcOutline can be used to add an outline at the current position (i.e.
// the last Y parameter of a Move): the text is the associated title, UTF-8 encoded
// and the outline tree is created from the number of leading spaces in the title
// - pgcBookmark will create a destination at the current position (i.e.
// the last Y parameter of a Move), with some text supplied as bookmark name
// - pgcLink/pgcLinkNoBorder will create a asLink annotation, expecting the data
// to be filled with TRect inclusive-inclusive bounding rectangle coordinates,
// followed by the corresponding bookmark name
// - pgcJpegDirect will include a JPEG image directly from its file content
// - pgcBeginMarkContent/pgcEndMarkContent will map
// BeginMarkedContent/EndMarkedContent sections
// - use the GdiComment*() functions to append the corresponding
// EMR_GDICOMMENT message to a metafile content
TPdfGdiComment = (
pgcOutline,
pgcBookmark,
pgcLink,
pgcLinkNoBorder,
pgcJpegDirect,
pgcBeginMarkContent,
pgcEndMarkContent);
{$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
// - to be used as parameter for TPdfEncryption.New() class method
// - see PDF_PERMISSION_ALL, PDF_PERMISSION_NOMODIF, PDF_PERSMISSION_NOPRINT,
// PDF_PERMISSION_NOCOPY and PDF_PERMISSION_NOCOPYNORPRINT constants
TPdfEncryptionPermissions = set of TPdfEncryptionPermission;
const
/// allow all actions for a pdf encrypted file
// - to be used as parameter for TPdfEncryption.New() class method
PDF_PERMISSION_ALL: TPdfEncryptionPermissions =
[Low(TPdfEncryptionPermission)..high(TPdfEncryptionPermission)];
/// disable modification and annotation of a pdf encrypted file
// - to be used as parameter for TPdfEncryption.New() class method
PDF_PERMISSION_NOMODIF: TPdfEncryptionPermissions = [
epPrinting,
epContentCopy,
epPrintingHighResolution,
epFillingForms,
epContentExtraction,
epDocumentAssembly];
/// disable printing for a pdf encrypted file
// - to be used as parameter for TPdfEncryption.New() class method
PDF_PERSMISSION_NOPRINT: TPdfEncryptionPermissions = [
epGeneralEditing,
epContentCopy,
epAuthoringComment,
epContentExtraction,
epDocumentAssembly];
/// disable content extraction or copy for a pdf encrypted file
// - to be used as parameter for TPdfEncryption.New() class method
PDF_PERMISSION_NOCOPY: TPdfEncryptionPermissions = [
epPrinting,
epAuthoringComment,
epPrintingHighResolution,
epFillingForms];
/// disable printing and content extraction or copy for a pdf encrypted file
// - to be used as parameter for TPdfEncryption.New() class method
PDF_PERMISSION_NOCOPYNORPRINT: TPdfEncryptionPermissions = [];
{$endif USE_PDFSECURITY}
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#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';
/// this function returns true if the supplied text contain any MBCS character
// - typical call must check first if MBCS is currently enabled
// ! if SysLocale.FarEast and _HasMultiByteString(pointer(Text)) then ...
function HasMultiByteString(Value: PAnsiChar): boolean;
/// convert an unsigned integer into a PdfString text
function UInt32ToPdfString(Value: cardinal): PdfString;
{$ifdef HASINLINE} inline; {$endif}
/// convert a date, into PDF string format, i.e. as 'D:20100414113241Z'
function DateTimeToPdfDate(ADate: TDateTime): TPdfDate;
/// decode PDF date, encoded as 'D:20100414113241'
function PdfDateToDateTime(const AText: TPdfDate; out AValue: TDateTime): boolean;
/// wrapper to create a temporary PDF coordinates rectangle
function PdfRect(Left, Top, Right, Bottom: single): TPdfRect; overload;
{$ifdef HASINLINE} inline;{$endif}
/// wrapper to create a temporary PDF coordinates rectangle
function PdfRect(const Box: TPdfBox): TPdfRect; overload;
{$ifdef HASINLINE} inline;{$endif}
/// wrapper to create a temporary PDF box
function PdfBox(Left, Top, Width, Height: single): TPdfBox;
{$ifdef HASINLINE} inline;{$endif}
/// reverse char orders for every hebrew and arabic words
// - just reverse all the UTF-16 codepoints in the supplied buffer
procedure L2R(W: PWideChar; L: PtrInt);
/// convert some milli meters dimension to internal PDF twips value
function PdfCoord(MM: single): integer;
{$ifdef HASINLINE} inline;{$endif}
/// retrieve the paper size used by the current selected printer
function CurrentPrinterPaperSize: TPdfPaperSize;
/// retrieve the current printer resolution
function CurrentPrinterRes: TPoint;
{************ Internal classes mapping PDF objects }
type
TPdfObject = class;
TPdfCanvas = class;
TPdfFont = class;
TPdfFontTrueType = class;
TPdfDocument = class;
{$ifdef USE_PDFSECURITY}
/// 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;
fUserPass, fOwnerPass: TPdfBuffer32;
fLastRC4Key: TRC4;
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 USE_PDFSECURITY}
/// buffered writer class, specialized for PDF encoding
TPdfWrite = class
protected
B, BEnd, BEnd4: PAnsiChar;
fDestStream: TStream;
fDestStreamPosition: integer;
fDoc: TPdfDocument;
fAddGlyphFont: (fNone, fMain, fFallBack);
fTmp: array[0..511] of AnsiChar;
/// internal Ansi->Unicode conversion, using the CodePage used in Create()
// - returned Dest.len is in WideChar count, not in bytes
// - caller must release the returned memory via Dest.Done
procedure ToWideChar(const Ansi: PdfString; out Dest: TSynTempBuffer);
{$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; PWLen: integer;
WinAnsiTtf: TPdfFontTrueType; NextLine: boolean; Canvas: TPdfCanvas): boolean;
{$endif USE_UNISCRIBE}
/// 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
// - and append 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: double): 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: double): 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: double; Decimals: cardinal): TPdfWrite; overload;
/// direct raw write of some data
// - no conversion is made
function Add(Text: PAnsiChar; Len: PtrInt): TPdfWrite; overload;
/// direct raw write of some data
// - no conversion is made
function Add(const Text: RawByteString): TPdfWrite; overload;
/// direct raw write of some data
// - conversion is forced to UTF-8 output from Text string encoding
function AddS(const Text: string): 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 writing 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 writing to the PDF file content...)
// - if the current font is not true Type, all Unicode characters are
// drawn as '?'
function AddUnicodeHexText(PW: PWideChar; PWLen: integer; 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;
/// add a PDF color, from its TPdfColorRGB RGB value
function AddColorStr(Color: TPdfColorRGB): TPdfWrite;
/// 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>'
TPdfTextUtf8 = class(TPdfObject)
private
fValue: RawUtf8;
protected
procedure InternalWriteTo(W: TPdfWrite); override;
function SpaceNotNeeded: boolean; override;
public
constructor Create(const AValue: RawUtf8); reintroduce;
property Value: RawUtf8
read fValue write fValue;
end;
/// a PDF object, storing a textual value
// - the value is specified as a RTL 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>'
TPdfTextString = class(TPdfTextUtf8)
private
function GetValue: string;
procedure SetValue(const Value: string);
public
constructor Create(const AValue: string); reintroduce;
property Value: string
read GetValue write SetValue;
end;
/// a PDF object, storing a raw PDF content
// - this object is stored into the PDF stream as the defined Value
TPdfRawText = class(TPdfText)
protected
function SpaceNotNeeded: boolean; override;
procedure InternalWriteTo(W: TPdfWrite); override;
end;
/// a PDF object, storing a textual value with no encryption
// - the value is specified as a memory buffer
// - this object is stored as '(escapedValue)'
TPdfClearText = class(TPdfText)
protected
procedure InternalWriteTo(W: TPdfWrite); override;
public
constructor Create(Buffer: pointer; Len: integer); reintroduce;
end;
/// a PDF object, storing a PDF name
// - this object is stored as '/Value'
TPdfName = class(TPdfText)
protected
procedure InternalWriteTo(W: TPdfWrite); override;
public
/// append the 'SUBSET+' prefix to the Value
// - used e.g. to notify that a font is included as a subset
function AppendPrefix: RawUtf8;
end;
/// used to store an array of PDF objects
TPdfArray = class(TPdfObject)
private
fArray: TSynList;
fObjectMgr: TPdfObjectMgr;
function GetItems(Index: integer): TPdfObject;
{$ifdef HASINLINE}inline;{$endif}
function GetItemCount: integer;
{$ifdef HASINLINE}inline;{$endif}
protected
procedure InternalWriteTo(W: TPdfWrite); override;
function SpaceNotNeeded: boolean; override;
public
/// create an array of PDF objects
constructor Create(AObjectMgr: TPdfObjectMgr); reintroduce; overload;
/// create an array of PDF objects, with some specified TPdfNumber values
constructor Create(AObjectMgr: TPdfObjectMgr; const AArray: array of integer);
reintroduce; overload;
/// create an array of PDF objects, with some specified TPdfNumber values
constructor Create(AObjectMgr: TPdfObjectMgr; AArray: PWordArray;
AArrayCount: integer); reintroduce; overload;
/// create an array of PDF objects, with some specified TPdfName values
constructor CreateNames(AObjectMgr: TPdfObjectMgr;
const AArray: array of PdfString); reintroduce; overload;
/// create an array of PDF objects, with some specified TPdfReal values
constructor CreateReals(AObjectMgr: TPdfObjectMgr;
const AArray: array of double); reintroduce; overload;
/// release the instance memory, and all embedded objects instances
destructor Destroy; override;
/// Add a PDF object to the array
// - if AItem already exists, do nothing
function AddItem(AItem: TPdfObject): integer;
/// insert a PDF object to the array
// - if AItem already exists, do nothing
procedure InsertItem(Index: integer; AItem: TPdfObject);
/// retrieve a TPdfName object stored in the array
function FindName(const AName: PdfString): TPdfName;
/// remove a specified TPdfName object stored in the array
function RemoveName(const AName: PdfString): boolean;
/// retrieve an object instance, stored in the array
property Items[Index: integer]: TPdfObject
read GetItems; default;
/// retrieve the array size
property ItemCount: integer
read GetItemCount;