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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! docx を開く、作る、直す
//!
//! # 開く
//!
//! ```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()),
//! }
//! }
//! ```
//!
//! # 作る
//!
//! ```no_run
//! use folio::document::Writer;
//! use folio::paragraph::Paragraph;
//! use std::path::Path;
//!
//! let mut writer = Writer::create(Path::new("out.docx")).unwrap();
//! writer.paragraph(&Paragraph::styled("見出し", "Heading1")).unwrap();
//! writer.paragraph(&Paragraph::new("本文です。")).unwrap();
//! writer.finish().unwrap();
//! ```
//!
//! # 直す
//!
//! [`Writer::edit`] は本文だけを書き直し、ほかのパートは圧縮したまま写す。
//! 本文の後ろにある `<w:sectPr>` (用紙の大きさ、余白、ヘッダとフッタの指し先) も、そのまま残す。
use crate::error::Error;
use crate::package::{self, Package};
use crate::paragraph::{self, Paragraph};
use crate::table::{self, Table};
use crate::xml::{Event, Reader as XmlReader};
use crate::zip;
use std::path::Path;
/// 文書の名前空間
const MAIN: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
/// 関係の名前空間
const RELATION: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
/// XML の宣言
const HEAD: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
/// 本文のパート
const BODY: &str = "word/document.xml";
/// 直すときに、末尾から採っておく量
const KEEP: usize = 256 * 1024;
/// 用紙と余白の既定。A4 の縦、余白 2cm
const SECTION: &str = "<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>\
<w:pgMar w:top=\"1134\" w:right=\"1134\" w:bottom=\"1134\" w:left=\"1134\" \
w:header=\"709\" w:footer=\"709\" w:gutter=\"0\"/></w:sectPr>";
/// 本文に並ぶもの
#[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)
}
}
/// 作る、または直すために開いた文書
pub struct Writer {
package: package::Writer,
/// 直す元。作るだけのときは None
source: Option<Package>,
/// 本文の後ろに戻す中身
tail: Vec<u8>,
/// 組み立て中の中身
buffer: String,
}
impl Writer {
/// 新しい docx を作る
pub fn create(path: &Path) -> Result<Writer, Error> {
let mut package = package::Writer::create(path)?;
package.add("[Content_Types].xml", content_type().as_bytes())?;
package.add("_rels/.rels", root_relationship().as_bytes())?;
package.add("word/_rels/document.xml.rels", body_relationship().as_bytes())?;
package.add("word/styles.xml", styles().as_bytes())?;
package.start(BODY)?;
let head = format!("{HEAD}<w:document xmlns:w=\"{MAIN}\" xmlns:r=\"{RELATION}\"><w:body>");
package.write(head.as_bytes())?;
Ok(Writer {
package,
source: None,
tail: format!("{SECTION}</w:body></w:document>").into_bytes(),
buffer: String::with_capacity(8 * 1024),
})
}
/// すでにある docx の本文を書き直す。ほかのパートは圧縮したまま写す
pub fn edit(document: Document, path: &Path) -> Result<Writer, Error> {
let main = document.main.clone();
let Origin::Package(mut source) = document.source else {
return Err(Error::new("旧形式のファイルは直せません。docx として作り直してください"));
};
let mut package = package::Writer::create(path)?;
package.carry(&mut source, &[main.as_str()])?;
let mut reader = source.archive.reader(&main)?;
let (mut head, tail) = split(&mut reader).map_err(|error| error.within(&main))?;
head.extend_from_slice(b"<w:body>");
package.start(&main)?;
package.write(&head)?;
Ok(Writer {
package,
source: Some(source),
tail,
buffer: String::with_capacity(8 * 1024),
})
}
/// 段落を 1 つ書く
pub fn paragraph(&mut self, one: &Paragraph) -> Result<(), Error> {
self.buffer.clear();
paragraph::write_into(&mut self.buffer, one);
self.flush()
}
/// 表を 1 つ書く
///
/// docx では、表の直後に段落がないと後ろの表とつながってしまう。空の段落を続けて置く。
pub fn table(&mut self, one: &Table) -> Result<(), Error> {
self.buffer.clear();
table::write_into(&mut self.buffer, one);
self.buffer.push_str("<w:p/>");
self.flush()
}
/// 段落でも表でも書く
pub fn write(&mut self, one: &Block) -> Result<(), Error> {
match one {
Block::Paragraph(value) => self.paragraph(value),
Block::Table(value) => self.table(value),
}
}
/// 書き終える
pub fn finish(mut self) -> Result<(), Error> {
let tail = std::mem::take(&mut self.tail);
self.package.write(&tail)?;
self.package.close()?;
if let Some(source) = self.source.as_mut() {
self.package.carry(source, &[])?;
}
self.package.finish()
}
/// 組み立てたものを出す
fn flush(&mut self) -> Result<(), Error> {
let buffer = std::mem::take(&mut self.buffer);
let result = self.package.write(buffer.as_bytes());
self.buffer = buffer;
result
}
}
/// 段落でも表でも XML にして足す
pub fn block_into(result: &mut String, one: &Block) {
match one {
Block::Paragraph(value) => paragraph::write_into(result, value),
Block::Table(value) => {
table::write_into(result, value);
result.push_str("<w:p/>");
}
}
}
/// 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(),
})
}
/// 本文のパートを読み流して、`<w:body>` の前と、末尾の `<w:sectPr>` から後ろを取り出す
fn split(reader: &mut zip::Reader) -> Result<(Vec<u8>, Vec<u8>), Error> {
let cut = package::split(reader, b"<w:body", b"</w:body>", KEEP)?;
let close = format!("</w:body></w:document>");
// `<w:body>` が見つからない文書は、前後を採りようがない
if !cut.found || cut.head.is_empty() {
let head = format!("{HEAD}<w:document xmlns:w=\"{MAIN}\" xmlns:r=\"{RELATION}\">");
return Ok((head.into_bytes(), format!("{SECTION}{close}").into_bytes()));
}
let mut tail = match section(&cut.last) {
Some(value) => value,
None => SECTION.as_bytes().to_vec(),
};
tail.extend_from_slice(b"</w:body>");
tail.extend_from_slice(&cut.tail);
Ok((cut.head, tail))
}
/// 本文の末尾にある `<w:sectPr>` を取り出す
///
/// 段落の中の `<w:sectPr>` (途中の区切り) と間違えないよう、
/// その要素より後ろに何も入っていないことを確かめる。
fn section(last: &[u8]) -> Option<Vec<u8>> {
let start = package::rfind(last, b"<w:sectPr")?;
let end = match package::find(&last[start..], b"</w:sectPr>") {
Some(step) => start + step + "</w:sectPr>".len(),
None => {
let step = package::find(&last[start..], b">")?;
if last[start + step - 1] != b'/' {
return None;
}
start + step + 1
}
};
if !last[end..].iter().all(|byte| byte.is_ascii_whitespace()) {
return None;
}
Some(last[start..end].to_vec())
}
/// [Content_Types].xml
fn content_type() -> String {
let base = "application/vnd.openxmlformats-officedocument.wordprocessingml";
format!(
"{HEAD}<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
<Default Extension=\"xml\" ContentType=\"application/xml\"/>\
<Override PartName=\"/word/document.xml\" ContentType=\"{base}.document.main+xml\"/>\
<Override PartName=\"/word/styles.xml\" ContentType=\"{base}.styles+xml\"/>\
</Types>"
)
}
/// _rels/.rels
fn root_relationship() -> String {
format!(
"{HEAD}<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
<Relationship Id=\"rId1\" Type=\"{RELATION}/officeDocument\" Target=\"word/document.xml\"/>\
</Relationships>"
)
}
/// word/_rels/document.xml.rels
fn body_relationship() -> String {
format!(
"{HEAD}<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
<Relationship Id=\"rId1\" Type=\"{RELATION}/styles\" Target=\"styles.xml\"/>\
</Relationships>"
)
}
/// word/styles.xml
///
/// 段落の書式は Normal と Title、Heading1 から Heading3 まで置く。
/// [`Paragraph::styled`] に渡す名前はこれらである。
fn styles() -> String {
let mut result = format!("{HEAD}<w:styles xmlns:w=\"{MAIN}\">");
result.push_str(
"<w:docDefaults><w:rPrDefault><w:rPr>\
<w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\" w:eastAsia=\"Yu Gothic\"/>\
<w:sz w:val=\"22\"/></w:rPr></w:rPrDefault><w:pPrDefault/></w:docDefaults>",
);
result.push_str(
"<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\">\
<w:name w:val=\"Normal\"/></w:style>",
);
result.push_str(
"<w:style w:type=\"paragraph\" w:styleId=\"Title\"><w:name w:val=\"Title\"/>\
<w:basedOn w:val=\"Normal\"/><w:pPr><w:spacing w:before=\"240\" w:after=\"240\"/></w:pPr>\
<w:rPr><w:b/><w:sz w:val=\"56\"/></w:rPr></w:style>",
);
for level in 1..4 {
let size = 36 - (level - 1) * 6;
result.push_str(&format!(
"<w:style w:type=\"paragraph\" w:styleId=\"Heading{level}\">\
<w:name w:val=\"heading {level}\"/><w:basedOn w:val=\"Normal\"/>\
<w:pPr><w:outlineLvl w:val=\"{}\"/><w:spacing w:before=\"240\" w:after=\"120\"/></w:pPr>\
<w:rPr><w:b/><w:sz w:val=\"{size}\"/></w:rPr></w:style>",
level - 1
));
}
result.push_str("</w:styles>");
result
}