-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtf.go
More file actions
103 lines (80 loc) · 2.54 KB
/
rtf.go
File metadata and controls
103 lines (80 loc) · 2.54 KB
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
package docreader
import (
"fmt"
"os"
"regexp"
"strings"
)
// RtfReader 用于读取 .rtf 文件
type RtfReader struct{}
// ReadText 读取 RTF 文件的文本内容(简单提取纯文本)
func (r *RtfReader) ReadText(filePath string) (string, error) {
// 读取文件内容
data, err := os.ReadFile(filePath)
if err != nil {
return "", WrapError("RtfReader.ReadText", filePath, ErrFileRead)
}
content := string(data)
// 简单的 RTF 文本提取
// 移除 RTF 控制字符
content = removeRtfControls(content)
return content, nil
}
// GetMetadata 获取 RTF 文件的元数据
func (r *RtfReader) GetMetadata(filePath string) (map[string]string, error) {
metadata := make(map[string]string)
// 获取文件信息
fileInfo, err := os.Stat(filePath)
if err != nil {
return nil, WrapError("RtfReader.GetMetadata", filePath, ErrFileNotFound)
}
metadata["size"] = fmt.Sprintf("%d", fileInfo.Size())
metadata["modified"] = fileInfo.ModTime().String()
return metadata, nil
}
// removeRtfControls 移除 RTF 控制字符,提取纯文本
func removeRtfControls(content string) string {
// 移除 RTF 头部
re := regexp.MustCompile(`\\rtf\d+`)
content = re.ReplaceAllString(content, "")
// 移除控制字
re = regexp.MustCompile(`\\[a-z]+\d*\s?`)
content = re.ReplaceAllString(content, "")
// 移除花括号
content = strings.ReplaceAll(content, "{", "")
content = strings.ReplaceAll(content, "}", "")
// 移除多余的空白
re = regexp.MustCompile(`\s+`)
content = re.ReplaceAllString(content, " ")
return strings.TrimSpace(content)
}
// ReadWithConfig 根据配置读取 RTF 文件,返回结构化结果
func (r *RtfReader) ReadWithConfig(filePath string, config *ReadConfig) (*DocumentResult, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return nil, WrapError("RtfReader.ReadWithConfig", filePath, ErrFileRead)
}
content := string(data)
content = removeRtfControls(content)
lines := strings.Split(content, "\n")
result := &DocumentResult{
FilePath: filePath,
TotalPages: 1,
Pages: make([]PageContent, 0),
Metadata: make(map[string]string),
}
// 获取元数据
metadata, _ := r.GetMetadata(filePath)
result.Metadata = metadata
// 根据配置筛选行
filteredLines := filterLinesForSinglePage(lines, config)
pageContent := PageContent{
PageNumber: 0,
Lines: filteredLines,
TotalLines: len(filteredLines),
}
result.Pages = append(result.Pages, pageContent)
result.TotalLines = len(filteredLines)
result.Content = strings.Join(filteredLines, "\n")
return result, nil
}