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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
//! 文書。docx と doc を開く
//!
//! ```no_run
//! use folio::document::Document;
//! use std::path::Path;
//!
//! let mut document = Document::open(Path::new("file.docx")).unwrap();
//! println!("{}", document.text().unwrap());
//! ```
//!
//! 段落や表として受け取るときは、本文を順に読む。
//!
//! ```no_run
//! use folio::document::{Block, Document};
//! use std::path::Path;
//!
//! let mut document = Document::open(Path::new("file.docx")).unwrap();
//! let mut body = document.read().unwrap();
//!
//! while let Some(block) = body.read().unwrap() {
//! match block {
//! Block::Paragraph(one) => println!("{}", one.text()),
//! Block::Table(one) => println!("表 {} 行", one.row.len()),
//! }
//! }
//! ```
use crate::error::Error;
use crate::package::Package;
use crate::paragraph::{self, Paragraph};
use crate::table::{self, Table};
use crate::xml::{Event, Reader as XmlReader};
use std::path::Path;
/// 本文に並ぶもの
#[derive(Debug, Clone, PartialEq)]
pub enum Block {
Paragraph(Paragraph),
Table(Table),
}
impl Block {
/// 中の文字。表は、セルをタブで、行を改行でつなぐ
pub fn text(&self) -> String {
match self {
Block::Paragraph(one) => one.text(),
Block::Table(one) => {
let mut result = String::new();
for row in &one.row {
if !result.is_empty() {
result.push('\n');
}
for (index, cell) in row.cell.iter().enumerate() {
if index > 0 {
result.push('\t');
}
result.push_str(&cell.text());
}
}
result
}
}
}
}
/// どちらの形式を開いたか
enum Origin {
/// docx
Package(Package),
/// doc。段落ごとの文字だけを持つ
Record(Vec<String>),
}
/// 読むために開いた文書
pub struct Document {
source: Origin,
main: String,
}
impl Document {
/// docx か doc を開く
///
/// 先頭のバイトを見て、どちらの形式かを決める。読む側は形式を気にしなくてよい。
pub fn open(path: &Path) -> Result<Document, Error> {
if crate::cfb::is_compound(path) {
return open_record(path);
}
let mut package = Package::open(path)?;
let main = package.main()?;
if !package.has(&main) {
return Err(Error::at("本文のパートがありません", &main));
}
Ok(Document {source: Origin::Package(package), main})
}
/// 本文のパートの名前
pub fn main(&self) -> &str {
&self.main
}
/// 包みそのもの。folio が読まないパートを自分で取り出すときに使う
///
/// 旧形式には包みがないので None を返す。
pub fn package(&mut self) -> Option<&mut Package> {
match &mut self.source {
Origin::Package(one) => Some(one),
Origin::Record(_) => None,
}
}
/// 旧形式かどうか
pub fn is_record(&self) -> bool {
matches!(self.source, Origin::Record(_))
}
/// 本文を順に読む
pub fn read(&mut self) -> Result<Reader, Error> {
match &mut self.source {
Origin::Package(package) => Ok(Reader {
source: Source::Body(package.reader(&self.main)?),
inside: false,
ended: false,
}),
Origin::Record(line) => Ok(Reader {
source: Source::Line(line.clone(), 0),
inside: true,
ended: false,
}),
}
}
/// 本文の文字だけを、段落ごとに改行でつないで返す
pub fn text(&mut self) -> Result<String, Error> {
let mut body = self.read()?;
let mut result = String::new();
while let Some(block) = body.read()? {
result.push_str(&block.text());
result.push('\n');
}
Ok(result)
}
}
/// 本文をどこから受け取るか
enum Source {
/// docx の本文のパート
Body(XmlReader),
/// doc から取り出した段落
Line(Vec<String>, usize),
}
/// 本文を段落と表に分けて順に返すもの
///
/// 段落は数千から数万で、シートの行のような数にはならない。
/// だから 1 つずつ持ち主ごと返す。読む側は借りたものを気にしなくてよい。
pub struct Reader {
source: Source,
/// `<w:body>` の中に入ったか
inside: bool,
ended: bool,
}
impl Reader {
/// 次の段落か表。終わったら None
pub fn read(&mut self) -> Result<Option<Block>, Error> {
if self.ended {
return Ok(None);
}
let source = match &mut self.source {
Source::Body(one) => one,
Source::Line(line, at) => {
if *at >= line.len() {
self.ended = true;
return Ok(None);
}
let one = Paragraph::new(&line[*at]);
*at += 1;
return Ok(Some(Block::Paragraph(one)));
}
};
while let Some(event) = source.next()? {
if event == Event::Close {
if source.name() == "body" {
self.ended = true;
return Ok(None);
}
continue;
}
if event == Event::Text {
continue;
}
let empty = event == Event::Empty;
match source.name() {
"body" => {
self.inside = !empty;
if empty {
self.ended = true;
return Ok(None);
}
}
"p" if self.inside => {
if empty {
return Ok(Some(Block::Paragraph(Paragraph::default())));
}
return Ok(Some(Block::Paragraph(paragraph::read(source)?)));
}
"tbl" if self.inside && !empty => {
return Ok(Some(Block::Table(table::read(source)?)));
}
_ => {}
}
}
self.ended = true;
Ok(None)
}
}
/// doc を開く
fn open_record(path: &Path) -> Result<Document, Error> {
let mut file = crate::cfb::Compound::open(path)?;
if !file.has("WordDocument") {
return Err(Error::new("doc の WordDocument ストリームがありません"));
}
let main = file.read("WordDocument")?;
let name = crate::doc::table_name(&main)?;
if !file.has(name) {
return Err(Error::new(format!("doc の {name} ストリームがありません")));
}
let table = file.read(name)?;
let line = crate::doc::read(&main, &table)?;
Ok(Document {
source: Origin::Record(line),
main: "WordDocument".to_string(),
})
}