-
Notifications
You must be signed in to change notification settings - Fork 101
/
pdf_sign_twice_visible_annotation.go
196 lines (163 loc) · 4.59 KB
/
pdf_sign_twice_visible_annotation.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
/*
* This example showcases how to append a new page with signature to a PDF document.
* The file is signed using a private/public key pair.
*
* $ ./pdf_sign_twice_visible_annotation <INPUT_PDF_PATH> <OUTPUT_PDF_PATH>
*/
package main
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"io/ioutil"
"log"
"math/big"
"os"
"time"
"github.com/unidoc/unipdf/v3/common/license"
"github.com/unidoc/unipdf/v3/annotator"
"github.com/unidoc/unipdf/v3/core"
"github.com/unidoc/unipdf/v3/model"
"github.com/unidoc/unipdf/v3/model/sighandler"
)
func init() {
//Make sure to load your metered License API key prior to using the library.
//If you need a key, you can # and create a free one at https://cloud.unidoc.io
err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
if err != nil {
panic(err)
}
}
func main() {
args := os.Args
if len(args) < 3 {
log.Fatalln("Usage: go run pdf_sign_twice_visible_annotation INPUT_PDF_PATH OUTPUT_PDF_PATH")
}
inputPath := args[1]
outputPath := args[2]
// Read the original file.
f, err := os.Open(inputPath)
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
defer f.Close()
pdfReader, err := model.NewPdfReader(f)
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
// Add signature
buf, err := addSignature(pdfReader, 0)
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
// Open reader for the signed document
pdfReader, err = model.NewPdfReader(bytes.NewReader(buf))
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
// Add signature
buf, err = addSignature(pdfReader, 1)
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
// Write the resulting file to output.pdf file.
err = ioutil.WriteFile(outputPath, buf, 0666)
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
log.Printf("PDF file successfully saved to output path: %s\n", outputPath)
fmt.Println("Done")
}
func addSignature(pdfReader *model.PdfReader, signNumber int) ([]byte, error) {
totalPage, err := pdfReader.GetNumPages()
if err != nil {
log.Fatalf("Fail: %v\n", err)
}
// Create appender.
appender, err := model.NewPdfAppender(pdfReader)
if err != nil {
return nil, err
}
// Generate key pair.
priv, cert, err := generateSigKeys()
if err != nil {
return nil, err
}
// Create signature handler.
handler, err := sighandler.NewAdobePKCS7Detached(priv, cert)
if err != nil {
return nil, err
}
// Create signature.
signature := model.NewPdfSignature(handler)
signature.SetName("Test Signature Appearance Name")
signature.SetReason("TestSignatureAppearance Reason")
signature.SetDate(time.Now(), "")
// Initialize signature.
if err := signature.Initialize(); err != nil {
return nil, err
}
opts := annotator.NewSignatureFieldOpts()
opts.FontSize = 8
opts.Rect = []float64{float64(50 + signNumber*100), 250, float64(150 + signNumber*100), 300}
opts.TextColor = model.NewPdfColorDeviceRGB(255, 0, 0)
sigField, err := annotator.NewSignatureField(
signature,
[]*annotator.SignatureLine{
annotator.NewSignatureLine("Name", "John Doe"),
annotator.NewSignatureLine("Date", "2019.03.14"),
annotator.NewSignatureLine("Reason", fmt.Sprintf("Test sign #%d", signNumber)),
annotator.NewSignatureLine("Location", "London"),
annotator.NewSignatureLine("DN", "authority2:name2"),
},
opts,
)
if err != nil {
return nil, err
}
sigField.T = core.MakeString(fmt.Sprintf("New Page Signature %d", signNumber))
if err = appender.Sign(totalPage, sigField); err != nil {
log.Fatalf("Fail: %v\n", err)
}
buf := &bytes.Buffer{}
// Write output PDF file.
if err = appender.Write(buf); err != nil {
return nil, err
}
log.Println("PDF file successfully signed")
return buf.Bytes(), nil
}
func generateSigKeys() (*rsa.PrivateKey, *x509.Certificate, error) {
var now = time.Now()
// Generate private key.
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
// Initialize X509 certificate template.
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: "any",
Organization: []string{"Test Company"},
},
NotBefore: now.Add(-time.Hour),
NotAfter: now.Add(time.Hour * 24 * 365),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
// Generate X509 certificate.
certData, err := x509.CreateCertificate(rand.Reader, &template, &template, priv.Public(), priv)
if err != nil {
return nil, nil, err
}
cert, err := x509.ParseCertificate(certData)
if err != nil {
return nil, nil, err
}
return priv, cert, nil
}