-
Notifications
You must be signed in to change notification settings - Fork 14
/
pdf.go
87 lines (71 loc) · 1.57 KB
/
pdf.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
package main
import (
"errors"
"fmt"
"io"
"os"
"github.com/unidoc/unidoc/pdf/creator"
pdf "github.com/unidoc/unidoc/pdf/model"
)
type PDFSource struct {
source
}
func (s PDFSource) MergeTo(c *creator.Creator) error {
debugInfo(fmt.Sprintf("Adding PDF: %+v", s.source))
f, _ := os.Open(s.path)
defer f.Close()
return addPdfPages(f, s.pages, c)
}
func getReader(rs io.ReadSeeker) (*pdf.PdfReader, error) {
pdfReader, err := pdf.NewPdfReader(rs)
if err != nil {
return nil, err
}
isEncrypted, err := pdfReader.IsEncrypted()
if err != nil {
return nil, err
}
if isEncrypted {
auth, err := pdfReader.Decrypt([]byte(""))
if err != nil {
return nil, err
}
if !auth {
return nil, errors.New("Cannot merge encrypted, password protected document")
}
}
return pdfReader, nil
}
func addPdfPages(file *os.File, pages []int, c *creator.Creator) error {
pdfReader, err := getReader(file)
if err != nil {
return err
}
if len(pages) > 0 {
debugInfo(fmt.Sprintf("Adding all pages of PDF: %s", file.Name()))
for _, pageNo := range pages {
if page, pageErr := pdfReader.GetPage(pageNo); pageErr != nil {
return pageErr
} else {
err = c.AddPage(page)
}
}
} else {
numPages, err := pdfReader.GetNumPages()
if err != nil {
return err
}
for i := 0; i < numPages; i++ {
pageNum := i + 1
page, err := pdfReader.GetPage(pageNum)
if err != nil {
return err
}
debugInfo(fmt.Sprintf("Adding page %d of PDF: %s", pageNum, file.Name()))
if err = c.AddPage(page); err != nil {
return err
}
}
}
return nil
}