-
Notifications
You must be signed in to change notification settings - Fork 0
/
mark.go
164 lines (160 loc) · 4.06 KB
/
mark.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
package main
import (
"bufio"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/pdfcpu/pdfcpu/pkg/api"
"github.com/pdfcpu/pdfcpu/pkg/pdfcpu"
"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/validate"
)
var (
overwritef = flag.Bool("d", false, "delete original files after watermarking")
statsf = flag.Bool("s", false, "print a statistics files with details about the PDFs watermarked")
)
func main() {
flag.Parse()
if len(flag.Args()) != 1 {
fmt.Println("Expects a single argument with the name of a pdf file or directory")
os.Exit(1)
}
target := flag.Arg(0)
// get researcher's name from stdin
reader := bufio.NewReader(os.Stdin)
var name string
L:
for {
fmt.Print("Enter name: ")
name, _ = reader.ReadString('\n')
name = strings.TrimSpace(name)
fmt.Printf("Watermark with '%s'? (y)es/ enter, (e)dit, (q)uit: ", name)
cmd, _ := reader.ReadString('\n')
cmd = strings.TrimSpace(cmd)
switch cmd {
case "", "y", "yes":
break L
case "q", "quit":
fmt.Println("quitting")
os.Exit(0)
}
}
text := []string{
name,
fmt.Sprintf("made available on %s", time.Now().Format("2006-01-02")),
}
// if -s flag used, keep stats
var statsdir string
var pdfnames, errortxts []string
var totalPages int
var count int
if *statsf {
pdfnames = make([]string, 0, 500)
}
// walk the target dir
err := filepath.Walk(target, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error walking %q: %v", path, err)
}
if info.IsDir() {
if *statsf && target == path {
statsdir = target
}
return nil
}
if strings.ToLower(filepath.Ext(path)) == ".pdf" {
// don't watermark files that are already watermarked
if strings.HasSuffix(path, "_wm.pdf") {
return nil
}
// if target == path, this is a single PDF watermarking
if *statsf && target == path {
statsdir = filepath.Dir(target)
}
ctx, err := pdfcpu.ReadFile(path, pdfcpu.NewDefaultConfiguration())
if err == nil {
err = validate.XRefTable(ctx.XRefTable)
}
if err == nil {
err = pdfcpu.OptimizeXRefTable(ctx)
}
if err == nil {
err = ctx.EnsurePageCount()
}
var pageCount int
if err == nil {
// make a new watermark
wm := pdfcpu.DefaultWatermarkConfig()
wm.Opacity = 0.7
wm.TextLines = text
wm.OnTop = true
// select all pages
pageCount = ctx.PageCount
m := pdfcpu.IntSet{}
for i := 1; i <= pageCount; i++ {
m[i] = true
}
// add watermark
err = pdfcpu.AddWatermarks(ctx, m, wm)
}
// validate again
if err == nil {
err = validate.XRefTable(ctx.XRefTable)
}
// now write to file
if err == nil {
nn := strings.TrimSuffix(path, filepath.Ext(path)) + "_wm.pdf"
var nf *os.File
nf, err = os.Create(nn)
if err == nil {
err = api.WriteContext(ctx, nf)
}
nf.Close()
}
// if we've successfully written a watermarked file, update stats
if err == nil && *statsf {
count++
totalPages += pageCount
if *statsf {
pdfnames = append(pdfnames, filepath.Base(path))
}
}
// if we've successfully written a watermaked file, delete the old if in overwrite mode
if err == nil && *overwritef {
err = os.Remove(path)
}
// if errors in any of above: write to stats and clear the error if we are in stats mode; otherwise escalate the error
if err != nil {
if *statsf {
errortxts = append(errortxts, fmt.Sprintf("error for file %q: %v", path, err))
return nil
}
return err
}
}
return nil
})
if statsdir != "" && count > 0 {
sf, err := os.Create(filepath.Join(statsdir, fmt.Sprintf("stats-%d.txt", time.Now().Unix())))
if err == nil {
fmt.Fprintf(sf,
"WATERMARK STATS\r\n---\r\nResearcher: %s\r\nDate: %s\r\nTotal files: %d\r\nTotal pages: %d\r\n---\r\nFiles:\r\n%s",
name,
time.Now().Format("2006-01-02"),
count,
totalPages,
strings.Join(pdfnames, "\r\n"),
)
if len(errortxts) > 0 {
fmt.Fprintf(sf, "\r\n---\r\nErrors:\r\n%s", strings.Join(errortxts, "\r\n"))
}
}
sf.Close()
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}