-
Notifications
You must be signed in to change notification settings - Fork 1
/
ddc.go
961 lines (756 loc) · 32.4 KB
/
ddc.go
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
// Package ddc implements Digital document card specification (https://github.com/kaarkz/ddcard)
package ddc
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/vsenko/gofpdf"
pdfcpuapi "github.com/vsenko/pdfcpu/pkg/api"
"github.com/vsenko/pdfcpu/pkg/pdfcpu"
pdfcpumodel "github.com/vsenko/pdfcpu/pkg/pdfcpu/model"
pdfcputypes "github.com/vsenko/pdfcpu/pkg/pdfcpu/types"
)
const (
constPageType = "A4"
constPageOrientation = "P"
constPageUnits = "mm"
constPageWidth = 210
constPageHeight = 297
constPageTopMargin = 10
constPageBottomMargin = 10
constPageLeftMargin = 30
constPageRightMargin = 10
constContentMaxWidth = constPageWidth - constPageLeftMargin - constPageRightMargin
constContentMaxHeight = constPageHeight - constPageTopMargin - constPageBottomMargin
constHeaderHeight = 10
constIDQRSize = constHeaderHeight + 2
constFooterHeight = 10
constFooterDescriptionMaxLength = 90
constEmbeddedPageMaxWidth = constContentMaxWidth
constEmbeddedPageMaxHeight = constContentMaxHeight - constHeaderHeight - constFooterHeight
constContentTop = constPageTopMargin + constHeaderHeight + 10
constContentLeftColumnWidth = constContentMaxWidth / 3 * 2
constContentRightColumnWidth = constContentMaxWidth / 3
constContentRightColumnX = constPageLeftMargin + constContentLeftColumnWidth
constSignatureQRCodeImageSize = 42
constSignatureQRCodesInARow = 4
constSignatureQRCodeMargin = (constContentMaxWidth - constSignatureQRCodeImageSize*constSignatureQRCodesInARow) / (constSignatureQRCodesInARow + 2)
constSignatureQRCodeTopMargin = 5
constInfoBlockContentsPageNumColWidth = 10
constInfoBlockAttachmentsIndexNumColWidth = 10
constInfoBlockAttachmentsDescriptionColWidth = 75
constInfoBlockAttachmentsFileNameColWidth = constContentMaxWidth - constInfoBlockAttachmentsIndexNumColWidth - constInfoBlockAttachmentsDescriptionColWidth
constFontRegular = "LiberationSans-Regular"
constFontBold = "LiberationSans-Bold"
constFontItalic = "LiberationSans-Italic"
constFontBoldItalic = "LiberationSans-BoldItalic"
const45ccv = 45
constGrayR = 211
constGrayG = 211
constGrayB = 211
constSemiTransparent = 0.5
constMinimalAttachmentsDuringExport = 2
constTwo = 2
)
// SignatureVisualization information used to construct signature visualization page
type SignatureVisualization struct {
// Signers full name
SubjectName string `json:"subjectName"`
// Signers identification number such as IIN or passport number
SubjectID string `json:"subjectID"`
// In case if the subject signed as an employee, name of the employer
SubjectOrgName string `json:"subjectOrgName"`
// In case if the subject signed as an employee, identification number of the employer, such as BIN or tax number
SubjectOrgID string `json:"subjectOrgID"`
// Subjects full RDN in RFC 4514 format
Subject string `json:"subject"`
// Subjects alternative names from subjectAltName certificate extension
SubjectAltName string `json:"subjectAltName"`
// Serial number of the signers certificate
SerialNumber string `json:"serialNumber"`
// From value from certificate in format "19.05.2021 04:01:52 UTC+6"
From string `json:"from"`
// Until value from certificate in format "19.05.2021 04:01:52 UTC+6"
Until string `json:"until"`
// Certificate policies (aka certificate templates) in the following format "Human readable name (OID)"
Policies []string `json:"policies"`
// Key usages in the following format "Human readable name (const from https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3)"
KeyUsage []string `json:"keyUsage"`
// Extended key usages in the following format "Human readable name (OID)"
ExtKeyUsage []string `json:"extKeyUsage"`
// Certificate issuers full RDN in RFC 4514 format
Issuer string `json:"issuer"`
// Signature algorithm in the following format "Human readable name (OID)"
SignatureAlgorithm string `json:"signatureAlgorithm"`
// Time stamp imformation
TSP struct {
// Time stamp from TSP response in format "19.05.2021 04:01:52 UTC+6"
// converted to time zone of Nur-Sultan
GeneratedAt string `json:"generatedAt"`
// Serial number of the TSP signers certificate
SerialNumber string `json:"serialNumber"`
// TSP signers certificate subject full RDN in RFC 4514 format
Subject string `json:"subject"`
// TSP signers certificate issuer full RDN in RFC 4514 format
Issuer string `json:"issuer"`
} `json:"tsp"`
// OCSP response information
OCSP struct {
// ThisUpdate value from OCSP response in format "19.05.2021 04:01:52 UTC+6"
// converted to time zone of Nur-Sultan
GeneratedAt string `json:"generatedAt"`
// CertStatus from OCSP response as a string (one of "good", "revoked", or "unknown")
CertStatus string `json:"certStatus"`
// Serial number of the OCSP signers certificate
SerialNumber string `json:"serialNumber"`
// OCSP signers certificate subject full RDN in RFC 4514 format
Subject string `json:"subject"`
// OCSP signers certificate issuer full RDN in RFC 4514 format
Issuer string `json:"issuer"`
} `json:"ocsp"`
// Signature body encoded as a sey of QR codes and stored as PNG images (optional)
QRCodes [][]byte `json:"qrCodes"`
}
// SignatureInfo used to embed signature in DDC and optionally to construct visualization
type SignatureInfo struct {
// Signature body bytes
Body []byte `json:"body"`
// File name for attachment
FileName string `json:"fileName"`
// Signer name to build attachment description (optional, required if SignatureVisualization is not provided)
SignerName string `json:"signerName"`
// Signature visualization information (optional, required for signatures visualization)
SignatureVisualization *SignatureVisualization `json:"signatureVisualization"`
}
// DocumentInfo contains information about the digital document and signatures
type DocumentInfo struct {
// Title of the document
Title string `json:"title"`
// Optional description of the document
Description string `json:"description"`
// Optional id of the document
ID string `json:"id"`
// Optional qr code with the id of the document, should be set if id is set
IDQRCode []byte `json:"idQRCode"`
// Signatures information
Signatures []SignatureInfo `json:"signatures"`
// The language to build DDC in ["ru", "kk", "kk/ru"]
Language string `json:"language"`
}
// Builder builds Digital Document Card
type Builder struct {
pdf *gofpdf.Fpdf
imageOptions gofpdf.ImageOptions
di *DocumentInfo
attachments []gofpdf.Attachment
infoBlockNumPages int
// For any embedded document type
embeddedDoc io.ReadSeeker
embeddedDocFileName string
// For embedded PDFs
embeddedPDF io.ReadSeeker
embeddedPDFNumPages int
embeddedPDFPagesSizes []pdfcputypes.Dim
totalPages int
}
// NewBuilder creates a new DDC Builder
func NewBuilder(di *DocumentInfo) (*Builder, error) {
ddc := Builder{
imageOptions: gofpdf.ImageOptions{
ReadDpi: true,
ImageType: "png",
},
di: di,
}
return &ddc, nil
}
// EmbedPDF registers a digital document original in PDF format that should be embedded into DDC
func (ddc *Builder) EmbedPDF(pdf io.ReadSeeker, fileName string) error {
// Optimize PDF via pdfcpu because gopdfi Importer is fragile, does not return errors and panics
config := pdfcpumodel.NewDefaultConfiguration()
config.DecodeAllStreams = true
config.WriteObjectStream = false
config.WriteXRefStream = false
ctx, _, _, _, err := pdfcpuapi.ReadValidateAndOptimize(pdf, config, time.Now())
if err != nil {
return err
}
var b bytes.Buffer
err = pdfcpuapi.WriteContext(ctx, &b)
if err != nil {
return err
}
var optimizedPDF io.ReadSeeker = bytes.NewReader(b.Bytes())
numPages := ctx.PageCount
pagesSizes, err := ctx.PageDims()
if err != nil {
return err
}
if numPages < 1 {
return errors.New("document is empty")
}
ddc.embedDoc(pdf, optimizedPDF, numPages, pagesSizes, fileName)
return nil
}
// EmbedDoc registers a digital document original in any format that should be embedded into DDC
func (ddc *Builder) EmbedDoc(doc io.ReadSeeker, fileName string) error {
ddc.embedDoc(doc, nil, 0, nil, fileName)
return nil
}
func (ddc *Builder) embedDoc(doc, optimizedPDF io.ReadSeeker, numPages int, pagesSizes []pdfcputypes.Dim, fileName string) {
ddc.embeddedDoc = doc
ddc.embeddedDocFileName = fileName
ddc.embeddedPDF = optimizedPDF
ddc.embeddedPDFNumPages = numPages
ddc.embeddedPDFPagesSizes = pagesSizes
}
func (ddc *Builder) initPdf() (pdf *gofpdf.Fpdf, err error) {
pdf = gofpdf.New(constPageOrientation, constPageUnits, constPageType, "")
// Fpdf by default sets PDF version to "1.3" and not always bumps it when uses newer features.
// Adding an empty layer bumps the version to "1.5" thus increasing compliance with the standard.
pdf.AddLayer("Layer1", true)
pdf.AddUTF8FontFromBytes(constFontRegular, "", embeddedFontRegular)
pdf.AddUTF8FontFromBytes(constFontBold, "", embeddedFontBold)
pdf.AddUTF8FontFromBytes(constFontItalic, "", embeddedFontItalic)
pdf.AddUTF8FontFromBytes(constFontBoldItalic, "", embeddedFontBoldItalic)
// Fpdf margins are used only on Info Block pages, configure them with header and footer height to utilize auto page break
pdf.SetMargins(constPageLeftMargin, constPageTopMargin+constHeaderHeight, constPageRightMargin)
pdf.SetAutoPageBreak(true, constPageBottomMargin+constFooterHeight)
if err := pdf.Error(); err != nil {
return nil, err
}
return pdf, nil
}
func (ddc *Builder) addHeaderAndFooterToCurrentPage(headerText, footerText string, addPageNumber bool) error {
if headerText != "" {
ddc.pdf.SetXY(constPageLeftMargin, constPageTopMargin)
ddc.pdf.SetFont(constFontRegular, "", 11)
ddc.pdf.CellFormat(constContentMaxWidth, constHeaderHeight, headerText, "", 1, "LM", false, 0, "")
}
if ddc.di.ID != "" {
ddc.pdf.SetXY(constPageLeftMargin, constPageTopMargin)
ddc.pdf.SetFont(constFontRegular, "", 8)
ddc.pdf.CellFormat(constContentMaxWidth-constIDQRSize, constHeaderHeight-1, ddc.di.ID, "", 1, "RB", false, 0, "")
imgOptions := gofpdf.ImageOptions{
ReadDpi: true,
ImageType: "png",
}
ddc.pdf.RegisterImageOptionsReader("id-qr-code.png", imgOptions, bytes.NewReader(ddc.di.IDQRCode))
ddc.pdf.ImageOptions("id-qr-code.png", constPageLeftMargin+constContentMaxWidth-constIDQRSize, constPageTopMargin, constIDQRSize, constIDQRSize, false, imgOptions, 0, "")
ddc.pdf.Line(constPageLeftMargin, constPageTopMargin+constHeaderHeight, constPageLeftMargin+constContentMaxWidth-constIDQRSize, constPageTopMargin+constHeaderHeight)
} else {
ddc.pdf.Line(constPageLeftMargin, constPageTopMargin+constHeaderHeight, constPageLeftMargin+constContentMaxWidth, constPageTopMargin+constHeaderHeight)
}
ddc.pdf.Line(constPageLeftMargin, constPageHeight-constPageBottomMargin-constFooterHeight, constPageLeftMargin+constContentMaxWidth, constPageHeight-constPageBottomMargin-constFooterHeight)
if footerText != "" {
ddc.pdf.SetXY(constPageLeftMargin, constPageHeight-constPageBottomMargin-constFooterHeight)
ddc.pdf.SetFont(constFontRegular, "", 8)
ddc.pdf.CellFormat(constContentMaxWidth, constFooterHeight/2, footerText, "", 1, "LB", false, 0, "")
var descriptionBuilder strings.Builder
descriptionLength := 0
for _, runeValue := range ddc.di.Description {
if descriptionLength == constFooterDescriptionMaxLength-3 {
if _, err := descriptionBuilder.WriteString("..."); err != nil {
return err
}
break
}
if _, err := descriptionBuilder.WriteRune(runeValue); err != nil {
return err
}
descriptionLength++
}
ddc.pdf.SetFont(constFontBold, "", 8)
ddc.pdf.CellFormat(constContentMaxWidth, constFooterHeight/2, descriptionBuilder.String(), "", 1, "LT", false, 0, "")
}
if addPageNumber {
ddc.pdf.SetXY(constPageLeftMargin, constPageHeight-constPageBottomMargin-constFooterHeight)
ddc.pdf.SetFont(constFontRegular, "", 11)
pageNumberText := fmt.Sprintf(ddc.t("стр. %v из %v"), ddc.pdf.PageNo(), ddc.totalPages)
ddc.pdf.CellFormat(constContentMaxWidth, constFooterHeight, pageNumberText, "", 1, "RM", false, 0, "")
}
if err := ddc.pdf.Error(); err != nil {
return err
}
return nil
}
// Build DDC and write it's bytes to w
func (ddc *Builder) Build(visualizeDocument, visualizeSignatures bool, creationDate, builderName, howToVerify string, w io.Writer) error {
var err error
if visualizeDocument && ddc.embeddedPDF == nil {
return errors.New("visualization of non-PDF files is not available")
}
// PDF init
ddc.pdf, err = ddc.initPdf()
if err != nil {
return err
}
// Attachments
err = ddc.attachFiles()
if err != nil {
return err
}
// Simulate Info Block to find out how many pages it'll take
tempDDC, err := NewBuilder(ddc.di)
if err != nil {
return err
}
tempDDC.embedDoc(ddc.embeddedDoc, ddc.embeddedPDF, ddc.embeddedPDFNumPages, ddc.embeddedPDFPagesSizes, ddc.embeddedDocFileName)
tempDDC.pdf, err = tempDDC.initPdf()
if err != nil {
return err
}
err = tempDDC.attachFiles()
if err != nil {
return err
}
err = tempDDC.constructInfoBlock(visualizeDocument, visualizeSignatures, creationDate, builderName, howToVerify)
if err != nil {
return err
}
ddc.infoBlockNumPages = tempDDC.pdf.PageCount()
// Visualization
ddc.totalPages = ddc.infoBlockNumPages
if visualizeDocument {
ddc.totalPages += ddc.embeddedPDFNumPages
}
if visualizeSignatures {
ddc.totalPages += len(ddc.di.Signatures)
}
err = ddc.constructInfoBlock(visualizeDocument, visualizeSignatures, creationDate, builderName, howToVerify)
if err != nil {
return err
}
if visualizeDocument {
err = ddc.constructDocumentVisualization()
if err != nil {
return err
}
}
if visualizeSignatures {
err = ddc.constructSignaturesVisualization()
if err != nil {
return err
}
}
// Build output
var pdfBytes bytes.Buffer
err = ddc.pdf.Output(&pdfBytes)
if err != nil {
return err
}
// Just in case
err = ddc.pdf.Error()
if err != nil {
return err
}
// Add pages of the embedded PDF
if visualizeDocument {
var tempPDFBytes bytes.Buffer
desc := fmt.Sprintf("offset: %v 0 ,rot:0, scale:0.8 rel", constPageLeftMargin)
var wm *pdfcpumodel.Watermark
wm, err = pdfcpu.ParsePDFWatermarkDetails(ddc.embeddedDocFileName, desc, false, pdfcputypes.POINTS)
if err != nil {
return err
}
wm.PDF = ddc.embeddedPDF
wm.SkipPages = ddc.infoBlockNumPages
pageInDDC := fmt.Sprintf("%v-%v", ddc.infoBlockNumPages+1, ddc.infoBlockNumPages+ddc.embeddedPDFNumPages)
err = pdfcpuapi.AddWatermarks(bytes.NewReader(pdfBytes.Bytes()), &tempPDFBytes, []string{pageInDDC}, wm, pdfcpumodel.NewDefaultConfiguration())
if err != nil {
return err
}
pdfBytes = tempPDFBytes
}
// Optimize output
err = pdfcpuapi.Optimize(bytes.NewReader(pdfBytes.Bytes()), w, pdfcpumodel.NewDefaultConfiguration())
if err != nil {
return err
}
return nil
}
func (ddc *Builder) attachFiles() error {
ddc.attachments = make([]gofpdf.Attachment, len(ddc.di.Signatures)+1)
_, err := ddc.embeddedDoc.Seek(0, io.SeekStart)
if err != nil {
return err
}
pdfBytes, err := io.ReadAll(ddc.embeddedDoc)
if err != nil {
return err
}
ddc.attachments[0] = gofpdf.Attachment{
Content: pdfBytes,
Filename: ddc.embeddedDocFileName,
Description: ddc.t("Подлинник электронного документа"),
}
for si, signtaure := range ddc.di.Signatures {
signer := signtaure.SignerName
if signtaure.SignatureVisualization != nil {
signer = signtaure.SignatureVisualization.SubjectName
}
if signer == "" && signtaure.SignatureVisualization.SubjectID != "" {
signer = fmt.Sprintf(ddc.t("ИИН %v"), signtaure.SignatureVisualization.SubjectID)
}
if signer == "" {
return errors.New("subject ID not provided")
}
if signtaure.FileName == "" {
return errors.New("signature file name not provided")
}
ddc.attachments[1+si] = gofpdf.Attachment{
Content: signtaure.Body,
Filename: signtaure.FileName,
Description: fmt.Sprintf(ddc.t("ЭЦП, %v"), signer),
}
}
ddc.pdf.SetAttachments(ddc.attachments)
if err := ddc.pdf.Error(); err != nil {
return err
}
return nil
}
func (ddc *Builder) constructInfoBlock(visualizeDocument, visualizeSignatures bool, creationDate, builderName, howToVerify string) error {
ddc.pdf.AddPage()
ddc.pdf.SetFont(constFontBold, "", 14)
ddc.pdf.MultiCell(constContentMaxWidth, 10, ddc.t("КАРТОЧКА ЭЛЕКТРОННОГО ДОКУМЕНТА"), "", "CB", false)
ddc.pdf.SetY(ddc.pdf.GetY() + constPageTopMargin)
ddc.pdf.SetFont(constFontBold, "", 14)
ddc.pdf.MultiCell(constContentMaxWidth, 5, ddc.di.Description, "", "CB", false)
ddc.pdf.SetFont(constFontBold, "", 12)
{
ddc.pdf.SetY(ddc.pdf.GetY() + 5)
y := ddc.pdf.GetY()
ddc.pdf.MultiCell(constContentMaxWidth/constTwo, 5, ddc.t("Дата и время формирования"), "", "LB", false)
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constContentMaxWidth/2)
ddc.pdf.MultiCell(constContentMaxWidth/constTwo, 5, ddc.t("Информационная система или сервис"), "", "LB", false)
}
ddc.pdf.SetFont(constFontRegular, "", 12)
{
y := ddc.pdf.GetY()
ddc.pdf.MultiCell(constContentMaxWidth/constTwo, 5, creationDate, "", "LM", false)
lowestY := ddc.pdf.GetY()
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constContentMaxWidth/2)
ddc.pdf.MultiCell(constContentMaxWidth/constTwo, 5, builderName, "", "LM", false)
if lowestY > ddc.pdf.GetY() {
ddc.pdf.SetY(lowestY)
}
}
// Contents
ddc.pdf.SetFont(constFontBold, "", 12)
ddc.pdf.SetY(ddc.pdf.GetY() + 5)
ddc.pdf.MultiCell(constContentMaxWidth, 5, ddc.t("Содержание:"), "", "LB", false)
startPage := ddc.infoBlockNumPages + 1
documentVisualizationPages := "-"
if visualizeDocument {
documentVisualizationPages = fmt.Sprintf("%v", startPage)
startPage += ddc.embeddedPDFNumPages
}
signaturesVisualizationPages := "-"
if visualizeSignatures {
signaturesVisualizationPages = fmt.Sprintf("%v", startPage)
}
ddc.pdf.SetFont(constFontRegular, "", 12)
{
y := ddc.pdf.GetY()
ddc.pdf.MultiCell(constContentMaxWidth-constInfoBlockContentsPageNumColWidth, 5, ddc.t("Информационный блок"), "", "LM", false)
lowestY := ddc.pdf.GetY()
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constContentMaxWidth - constInfoBlockContentsPageNumColWidth)
ddc.pdf.MultiCell(constInfoBlockContentsPageNumColWidth, 5, "1", "", "RM", false)
ddc.pdf.SetY(lowestY)
y = ddc.pdf.GetY()
ddc.pdf.MultiCell(constContentMaxWidth-constInfoBlockContentsPageNumColWidth, 5, ddc.t("Визуализация электронного документа"), "", "LM", false)
lowestY = ddc.pdf.GetY()
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constContentMaxWidth - constInfoBlockContentsPageNumColWidth)
ddc.pdf.MultiCell(constInfoBlockContentsPageNumColWidth, 5, documentVisualizationPages, "", "RM", false)
ddc.pdf.SetY(lowestY)
y = ddc.pdf.GetY()
ddc.pdf.MultiCell(constContentMaxWidth-constInfoBlockContentsPageNumColWidth, 5, ddc.t("Визуализация подписей под электронным документом"), "", "LM", false)
lowestY = ddc.pdf.GetY()
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constContentMaxWidth - constInfoBlockContentsPageNumColWidth)
ddc.pdf.MultiCell(constInfoBlockContentsPageNumColWidth, 5, signaturesVisualizationPages, "", "RM", false)
ddc.pdf.SetY(lowestY)
}
// Attachments
ddc.pdf.SetFont(constFontBold, "", 12)
ddc.pdf.CellFormat(constContentMaxWidth, 10, ddc.t("Перечень вложенных файлов:"), "", 1, "LB", false, 0, "")
ddc.pdf.SetFont(constFontRegular, "", 12)
for i, a := range ddc.attachments {
y := ddc.pdf.GetY()
ddc.pdf.MultiCell(constInfoBlockAttachmentsIndexNumColWidth, 5, fmt.Sprintf("%v.", i+1), "", "LM", false)
lowestY := ddc.pdf.GetY()
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constInfoBlockAttachmentsIndexNumColWidth)
ddc.pdf.MultiCell(constInfoBlockAttachmentsFileNameColWidth, 5, a.Filename, "", "LM", false)
if ddc.pdf.GetY() > lowestY {
lowestY = ddc.pdf.GetY()
}
ddc.pdf.SetY(y)
ddc.pdf.SetX(constPageLeftMargin + constInfoBlockAttachmentsIndexNumColWidth + constInfoBlockAttachmentsFileNameColWidth)
ddc.pdf.MultiCell(constInfoBlockAttachmentsDescriptionColWidth, 5, a.Description, "", "LM", false)
if ddc.pdf.GetY() > lowestY {
lowestY = ddc.pdf.GetY()
}
ddc.pdf.SetY(lowestY)
}
// Comments
infoText := fmt.Sprintf(ddc.t(`
При формировании карточки электронного документа была автоматически выполнена процедура проверки ЭЦП в соответствии с положениями Приказа Министра по инвестициям и развитию Республики Казахстан «Об утверждении Правил проверки подлинности электронной цифровой подписи».
Карточка электронного документа — это файл в формате PDF, состоящий из визуально отображаемой части и вложенных файлов.
Визуально отображаемая часть карточки электронного документа носит исключительно информативный характер и не обладает юридической значимостью.
Многие программы для просмотра PDF поддерживают вложенные файлы, позволяют просматривать их и сохранять как обычные файлы. Среди них Adobe Acrobat Reader и браузер Firefox.
В соответствии с Законом Республики Казахстан «Об электронном документе и электронной цифровой подписи», подлинник электронного документа обладает юридической значимостью в том случае, если он подписан ЭЦП и были выполнены проверки подписи в соответствии с утвержденными правилами.
%v
ВНИМАНИЕ! Остерегайтесь мошенников! При получении электронных документов, обязательно выполняйте проверку подписей! Злоумышленники могут пробовать подделывать или менять визуально отображаемую часть карточки, так как она не защищена от изменения цифровой подписью.`),
howToVerify)
ddc.pdf.SetFont(constFontItalic, "", 10)
ddc.pdf.MultiCell(constContentMaxWidth, 4, infoText, "", "LT", false)
// No need for auto page break anymore
ddc.pdf.SetAutoPageBreak(false, 0)
// Add header and footer to all Info Block pages
for i := 1; i <= ddc.pdf.PageCount(); i++ {
ddc.pdf.SetPage(i)
if i == 1 {
err := ddc.addHeaderAndFooterToCurrentPage("", "", false)
if err != nil {
return err
}
} else {
err := ddc.addHeaderAndFooterToCurrentPage("", ddc.t("Карточка электронного документа"), true)
if err != nil {
return err
}
}
}
if err := ddc.pdf.Error(); err != nil {
return err
}
return nil
}
func (ddc *Builder) constructDocumentVisualization() error {
for pageNum := 1; pageNum <= ddc.embeddedPDFNumPages; pageNum++ {
ddc.pdf.AddPage()
err := ddc.addHeaderAndFooterToCurrentPage(ddc.t("Визуализация электронного документа"), ddc.t("Карточка электронного документа"), true)
if err != nil {
return err
}
// Calculate location
embeddedPageScaledWidth := ddc.embeddedPDFPagesSizes[pageNum-1].Width
embeddedPageScaledHeight := ddc.embeddedPDFPagesSizes[pageNum-1].Height
if embeddedPageScaledWidth > constEmbeddedPageMaxWidth {
embeddedPageScaledHeight = embeddedPageScaledHeight * constEmbeddedPageMaxWidth / embeddedPageScaledWidth
embeddedPageScaledWidth = constEmbeddedPageMaxWidth
}
if embeddedPageScaledHeight > constEmbeddedPageMaxHeight {
embeddedPageScaledWidth = embeddedPageScaledWidth * constEmbeddedPageMaxHeight / embeddedPageScaledHeight
embeddedPageScaledHeight = constEmbeddedPageMaxHeight
}
xShift := (constEmbeddedPageMaxWidth - embeddedPageScaledWidth) / 2
if xShift < 0 {
xShift = 0
}
yShift := (constEmbeddedPageMaxHeight - embeddedPageScaledHeight) / 2
if yShift < 0 {
yShift = 0
}
x := float64(constPageLeftMargin) + xShift
y := constPageTopMargin + constHeaderHeight + yShift
w := embeddedPageScaledWidth
h := embeddedPageScaledHeight
// Box
r, g, b := ddc.pdf.GetDrawColor()
ddc.pdf.SetDrawColor(constGrayR, constGrayG, constGrayB)
ddc.pdf.Rect(x, y, w, h, "D")
ddc.pdf.SetDrawColor(r, g, b)
// Watermark
r, g, b = ddc.pdf.GetTextColor()
ddc.pdf.TransformBegin()
ddc.pdf.TransformRotate(const45ccv, x+w/2, y+h/2)
ddc.pdf.SetXY(x, y+h/2)
ddc.pdf.SetTextColor(constGrayR, constGrayG, constGrayB)
ddc.pdf.SetFont(constFontRegular, "", 20)
ddc.pdf.SetAlpha(constSemiTransparent, "Normal")
ddc.pdf.MultiCell(w, 10, ddc.t("ВИЗУАЛИЗАЦИЯ ЭЛЕКТРОННОГО ДОКУМЕНТА"), "", "CM", false)
ddc.pdf.TransformEnd()
ddc.pdf.SetTextColor(r, g, b)
if err := ddc.pdf.Error(); err != nil {
return err
}
}
return nil
}
func (ddc *Builder) constructSignaturesVisualization() error {
for sIndex, signatureInfo := range ddc.di.Signatures {
signature := signatureInfo.SignatureVisualization
if signature == nil {
return errors.New("no signature visualization information provided")
}
ddc.pdf.AddPage()
err := ddc.addHeaderAndFooterToCurrentPage(ddc.t("Визуализация электронной цифровой подписи"), ddc.t("Карточка электронного документа"), true)
if err != nil {
return err
}
// Left column
ddc.pdf.SetY(constContentTop)
ddc.pdf.SetFont(constFontBold, "", 10)
ddc.pdf.CellFormat(constContentLeftColumnWidth, 5, fmt.Sprintf(ddc.t("Подпись №%v"), sIndex+1), "", 1, "LB", false, 0, "")
ddc.pdf.SetFont(constFontRegular, "", 8)
ddc.pdf.CellFormat(constContentLeftColumnWidth, 7, ddc.t("Дата формирования подписи:"), "", 1, "LB", false, 0, "")
ddc.pdf.SetFont(constFontBold, "", 8)
ddc.pdf.CellFormat(constContentLeftColumnWidth, 5, signature.TSP.GeneratedAt, "", 1, "LB", false, 0, "")
ddc.pdf.SetFont(constFontRegular, "", 8)
ddc.pdf.CellFormat(constContentLeftColumnWidth, 7, ddc.t("Подписал(а):"), "", 1, "LB", false, 0, "")
name := fmt.Sprintf(ddc.t("ИИН %v"), signature.SubjectID)
if signature.SubjectName != "" {
name = signature.SubjectName + ", " + name
}
if signature.SubjectOrgID != "" {
name = fmt.Sprintf(ddc.t("%v\n%v, БИН %v"), name, signature.SubjectOrgName, signature.SubjectOrgID)
}
ddc.pdf.SetFont(constFontBold, "", 8)
ddc.pdf.MultiCell(constContentLeftColumnWidth, 5, name, "", "LB", false)
ddc.pdf.SetFont(constFontRegular, "", 8)
ddc.pdf.CellFormat(constContentLeftColumnWidth, 7, ddc.t("Шаблон:"), "", 1, "LB", false, 0, "")
for _, policyString := range signature.Policies {
ddc.pdf.SetFont(constFontBold, "", 8)
ddc.pdf.MultiCell(constContentLeftColumnWidth, 5, fmt.Sprintf("- %v", policyString), "", "LB", false)
}
if len(signature.ExtKeyUsage) > 0 || len(signature.KeyUsage) > 0 {
ddc.pdf.SetFont(constFontRegular, "", 8)
ddc.pdf.CellFormat(constContentLeftColumnWidth, 7, ddc.t("Допустимое использование:"), "", 1, "LB", false, 0, "")
ddc.pdf.SetFont(constFontBold, "", 8)
for _, keyUsage := range signature.KeyUsage {
ddc.pdf.MultiCell(constContentLeftColumnWidth, 5, fmt.Sprintf("- %v", keyUsage), "", "LB", false)
}
for _, extKeyUsage := range signature.ExtKeyUsage {
ddc.pdf.MultiCell(constContentLeftColumnWidth, 5, fmt.Sprintf("- %v", extKeyUsage), "", "LB", false)
}
}
textBottom := ddc.pdf.GetY()
// Right column
ddc.pdf.SetY(constContentTop)
ddc.pdf.SetX(constContentRightColumnX)
ddc.pdf.SetFont(constFontRegular, "", 6)
r, g, b := ddc.pdf.GetDrawColor()
ddc.pdf.SetDrawColor(constGrayR, constGrayG, constGrayB)
certificateDetailsText := fmt.Sprintf(ddc.t(`Субъект: %v
Альтернативные имена: %v
Серийный номер: %v
С: %v
По: %v
Издатель: %v`), signature.Subject, signature.SubjectAltName, signature.SerialNumber, signature.From, signature.Until, signature.Issuer)
ddc.pdf.MultiCell(constContentRightColumnWidth, 3, certificateDetailsText, "1", "LM", false)
ddc.pdf.SetDrawColor(r, g, b)
ddc.pdf.SetY(ddc.pdf.GetY() + 1)
ddc.pdf.SetX(constContentRightColumnX)
ddc.pdf.SetFont(constFontRegular, "", 6)
r, g, b = ddc.pdf.GetDrawColor()
ddc.pdf.SetDrawColor(constGrayR, constGrayG, constGrayB)
tspDetailsText := fmt.Sprintf(ddc.t(`Метка времени: %v
Субъект: %v
Серийный номер: %v
Издатель: %v`), signature.TSP.GeneratedAt, signature.TSP.Subject, signature.TSP.SerialNumber, signature.TSP.Issuer)
ddc.pdf.MultiCell(constContentRightColumnWidth, 3, tspDetailsText, "1", "LM", false)
ddc.pdf.SetDrawColor(r, g, b)
ddc.pdf.SetY(ddc.pdf.GetY() + 1)
ddc.pdf.SetX(constContentRightColumnX)
ddc.pdf.SetFont(constFontRegular, "", 6)
r, g, b = ddc.pdf.GetDrawColor()
ddc.pdf.SetDrawColor(constGrayR, constGrayG, constGrayB)
ocspDetailsText := fmt.Sprintf(ddc.t(`OCSP: %v
Сформирован: %v
Субъект: %v
Серийный номер: %v
Издатель: %v`), signature.OCSP.CertStatus, signature.OCSP.GeneratedAt, signature.OCSP.Subject, signature.OCSP.SerialNumber, signature.OCSP.Issuer)
ddc.pdf.MultiCell(constContentRightColumnWidth, 3, ocspDetailsText, "1", "LM", false)
ddc.pdf.SetDrawColor(r, g, b)
ddc.pdf.SetY(ddc.pdf.GetY() + 1)
secondTextBottom := ddc.pdf.GetY()
if secondTextBottom > textBottom {
textBottom = secondTextBottom
}
// QR codes
yQR := textBottom + constSignatureQRCodeTopMargin + constSignatureQRCodeMargin
qrCodesInARow := 0
for qrIndex, qr := range signature.QRCodes {
imgOptions := gofpdf.ImageOptions{
ReadDpi: true,
ImageType: "png",
}
fileName := fmt.Sprintf("qr-%v-%v.png", signatureInfo.FileName, qrIndex)
ddc.pdf.RegisterImageOptionsReader(fileName, imgOptions, bytes.NewReader(qr))
x := constPageLeftMargin + constSignatureQRCodeMargin*(qrCodesInARow+1) + constSignatureQRCodeImageSize*qrCodesInARow
ddc.pdf.ImageOptions(fileName, float64(x), yQR, constSignatureQRCodeImageSize, constSignatureQRCodeImageSize, false, imgOptions, 0, "")
qrCodesInARow++
if qrCodesInARow == constSignatureQRCodesInARow {
qrCodesInARow = 0
yQR += constSignatureQRCodeMargin + constSignatureQRCodeImageSize
}
}
if err := ddc.pdf.Error(); err != nil {
return err
}
}
return nil
}
func (ddc *Builder) t(input string) string {
if ddc.di.Language == "kk" {
output, ok := kk[input]
if ok {
return output
}
}
if ddc.di.Language == "kk/ru" {
output, ok := kkRU[input]
if ok {
return output
}
}
return input
}
// AttachedFile information
type AttachedFile struct {
Name string
Bytes []byte
}
// ExtractAttachments from DDC and return them as structures
func ExtractAttachments(ddcPdf io.ReadSeeker) (documentOriginal *AttachedFile, signatures []AttachedFile, err error) {
err = pdfcpuapi.Validate(ddcPdf, nil)
if err != nil {
return nil, nil, err
}
attachments, err := pdfcpuapi.ExtractAttachmentsRaw(ddcPdf, "", nil, nil)
if err != nil {
return nil, nil, err
}
if len(attachments) < constMinimalAttachmentsDuringExport {
return nil, nil, fmt.Errorf("PDF contains less than %v attachments (%v)", len(attachments), constMinimalAttachmentsDuringExport)
}
documentOriginalBytes, err := io.ReadAll(attachments[0].Reader)
if err != nil {
return nil, nil, err
}
documentOriginal = &AttachedFile{
Name: attachments[0].FileName,
Bytes: documentOriginalBytes,
}
attachments = attachments[1:]
signatures = make([]AttachedFile, len(attachments))
for i := 0; i < len(attachments); i++ {
signatureBytes, readErr := io.ReadAll(attachments[i].Reader)
if readErr != nil {
return nil, nil, readErr
}
signatures[i].Name = attachments[i].FileName
signatures[i].Bytes = signatureBytes
}
return documentOriginal, signatures, nil
}