forked from signintech/pdft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf_obj_data.go
105 lines (89 loc) · 2.31 KB
/
pdf_obj_data.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
package pdft
import (
"bytes"
"crypto/rc4"
"errors"
gopdf "github.com/juaismar/pdft/minigopdf"
)
//PDFObjData byte of obj
type PDFObjData struct {
objID int
data []byte
}
func (p *PDFObjData) parse(raw *[]byte, stratoffset int) error {
tmp := (*raw)[stratoffset:]
endObjIndex := regexpEndObj.FindAllIndex(tmp, 1)
if len(endObjIndex) <= 0 {
return errors.New("bad endobj")
}
endObjOffsetBefore := endObjIndex[0][0] + stratoffset
tmp = (*raw)[stratoffset:endObjOffsetBefore]
startObjIndex := regexpStartObj.FindAllIndex(tmp, 1)
if len(startObjIndex) <= 0 {
return errors.New("bad start obj")
}
startObjOffsetAfter := startObjIndex[0][1]
startObjOffset := startObjIndex[0][0]
startObjLine := tmp[startObjOffset:startObjOffsetAfter]
data := tmp[startObjOffsetAfter:]
objID, err := objIDFromStartObjLine(string(startObjLine))
if err != nil {
return err
}
p.objID = objID
p.data = data
return nil
}
//ReadProperties read all obj Properties
func (p *PDFObjData) readProperties() (*PDFObjPropertiesData, error) {
var props PDFObjPropertiesData
err := readProperties(&p.data, &props)
if err != nil {
return nil, err
}
return &props, nil
}
func (p *PDFObjData) setProperties(props *PDFObjPropertiesData) {
var data bytes.Buffer
data.WriteString("<<\n")
for _, prop := range *props {
data.WriteString("/" + prop.key + " " + prop.rawVal)
}
data.WriteString(">>\n")
p.data = data.Bytes()
}
func (p *PDFObjData) encrypt(protection *gopdf.PDFProtection) error {
stream := []byte("stream")
endstream := []byte("endstream")
start := bytes.Index(p.data, stream)
if start != -1 {
end := bytes.LastIndex(p.data, endstream)
var head, body bytes.Buffer
head.Write(p.data[0:start])
body.Write(p.data[start+len(stream) : end])
tmp := bytes.Trim(body.Bytes(), "\r\n")
tmp = bytes.Trim(tmp, "\n")
bodyRc4, err := rc4Cip(protection.Objectkey(p.objID), tmp)
if err != nil {
return err
}
var data bytes.Buffer
data.Write(head.Bytes())
data.Write(stream)
data.WriteString("\n")
data.Write(bodyRc4)
data.WriteString("\n")
data.Write(endstream)
p.data = data.Bytes()
}
return nil
}
func rc4Cip(key []byte, src []byte) ([]byte, error) {
cip, err := rc4.NewCipher(key)
if err != nil {
return nil, err
}
dest := make([]byte, len(src))
cip.XORKeyStream(dest, src)
return dest, nil
}