-
Notifications
You must be signed in to change notification settings - Fork 492
/
mergePDFs.go
58 lines (50 loc) · 1.06 KB
/
mergePDFs.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
package main
import (
"io/ioutil"
"os"
"sort"
"strings"
)
func main() {
dirPath := "." // 当前目录
mergeSplitPDFsInDirectory(dirPath)
}
func mergeSplitPDFsInDirectory(dirPath string) {
files, err := ioutil.ReadDir(dirPath)
if err != nil {
panic(err)
}
splitFiles := make(map[string][]string)
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
if strings.Contains(fileName, ".pdf.") {
baseName := strings.Split(fileName, ".pdf.")[0] + ".pdf"
splitFiles[baseName] = append(splitFiles[baseName], fileName)
}
}
for baseName, parts := range splitFiles {
sort.Strings(parts) // 确保文件顺序正确
mergeFiles(baseName, parts)
}
}
func mergeFiles(baseName string, parts []string) {
mergedFile, err := os.Create(baseName)
if err != nil {
panic(err)
}
defer mergedFile.Close()
for _, part := range parts {
data, err := ioutil.ReadFile(part)
if err != nil {
panic(err)
}
_, err = mergedFile.Write(data)
if err != nil {
panic(err)
}
os.Remove(part) // 合并后删除分割文件
}
}