easyofd-reader 0.1.2

OFD file reader for easyofd-rust
Documentation
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
#![allow(clippy::too_many_lines)]
//! # easyofd-reader
//!
//! OFD file reader that parses GB/T 33190-2016 compliant ZIP archives.
//!
//! ## Architecture
//!
//! ```text
//! input.ofd (ZIP)
//! ├── OFD.xml                    → find DocRoot
//! └── Doc_0/
//!     ├── Document.xml           → read page list
//!     └── Pages/
//!         ├── Page_0.xml         → parse content
//!         └── Page_N.xml
//! ```

mod ofd_reader;
mod parser;
mod read_options;

// ── ofdrw 对齐新增模块 ──
pub mod bad_ofd_exception;
pub mod content_extractor;
pub mod delta_tool;
pub mod dl_ofd_reader;
pub mod error_path_exception;
pub mod extractor;
pub mod keyword;
pub mod model;
pub mod ofd_reader_facade;
pub mod page_info;
pub mod resource_locator;
pub mod resource_manage;
pub mod seal_ofd_reader;
pub mod tools;
pub mod zip_util;

// ── 默认导出 ──
pub use bad_ofd_exception::BadOfdException;
pub use content_extractor::ContentExtractor;
#[allow(deprecated)]
pub use dl_ofd_reader::DlOfdReader;
pub use error_path_exception::ErrorPathException;
pub use keyword::{KeywordExtractor, KeywordPosition, KeywordResource, TextCodeEntry};
#[allow(deprecated)]
pub use model::{
    AnnotionEntity, OfdDocumentVo, OfdPageVo, SealDataVo, StampAnnotVo, TemplatePageEntity,
    TemplateZOrder,
};
pub use ofd_reader::OfdReader;
pub use ofd_reader_facade::OfdReaderFacade;
pub use page_info::PageInfo;
pub use read_options::ReadOptions;
pub use resource_locator::ResourceLocator;
pub use resource_manage::ResourceManage;
#[allow(deprecated)]
pub use seal_ofd_reader::SealOfdReader;

// ── ofdrw Java 类名别名(snake_case → PascalCase 对齐) ──

/// 对应 Java: `org.ofdrw.reader.OFDReader`
///
/// Java 原始类名为全大写 `OFDReader`,Rust 版使用 [`OfdReader`]。
/// 此别名保持与 Java API 的名称兼容。
pub type OFDReader = OfdReader;

/// 对应 Java: `org.ofdrw.reader.BadOFDException`
///
/// Java 原始类名为 `BadOFDException`,Rust 版使用 [`BadOfdException`]。
pub type BadOFDException = BadOfdException;

/// 对应 Java: `org.ofdrw.reader.DLOFDReader`
///
/// Java 原始类名为 `DLOFDReader`,Rust 版使用 [`DlOfdReader`]。
#[allow(deprecated)]
pub type DLOFDReader = DlOfdReader;

/// 对应 Java: `org.ofdrw.reader.SealOFDReader`
///
/// Java 原始类名为 `SealOFDReader`,Rust 版使用 [`SealOfdReader`]。
#[allow(deprecated)]
pub type SealOFDReader = SealOfdReader;

/// 对应 Java: `org.ofdrw.reader.model.OFDDocumentVo`
///
/// Java 原始类名为 `OFDDocumentVo`,Rust 版使用 [`OfdDocumentVo`]。
#[allow(deprecated)]
pub type OFDDocumentVo = OfdDocumentVo;

/// 对应 Java: `org.ofdrw.reader.model.OFDPageVo`
///
/// Java 原始类名为 `OFDPageVo`,Rust 版使用 [`OfdPageVo`]。
#[allow(deprecated)]
pub type OFDPageVo = OfdPageVo;

/// 对应 Java: `org.ofdrw.reader.tools.NameSpaceModifier`
///
/// Java 原始类名为 `NameSpaceModifier`(驼峰含大写 S),
/// Rust 版使用 [`tools::namespace_modifier::NamespaceModifier`]。
#[allow(deprecated)]
pub type NameSpaceModifier = tools::namespace_modifier::NamespaceModifier;

/// 对应 Java: `org.ofdrw.reader.tools.NameSpaceCleaner`
///
/// Java 原始类名为 `NameSpaceCleaner`(驼峰含大写 S),
/// Rust 版使用 [`tools::namespace_cleaner::NamespaceCleaner`]。
pub type NameSpaceCleaner = tools::namespace_cleaner::NamespaceCleaner;

/// 对应 Java: `org.ofdrw.reader.ZipUtil`
///
/// 工具类以模块级函数形式实现,见 [`zip_util`] 模块。
pub use zip_util as ZipUtil;

/// 对应 Java: `org.ofdrw.reader.DeltaTool`
///
/// 工具类以模块级函数形式实现,见 [`delta_tool`] 模块。
pub use delta_tool as DeltaTool;

/// 对应 Java: `org.ofdrw.reader.tools.ImageUtils`
///
/// 工具类以模块级函数形式实现,见 [`tools::image_utils`] 模块。
pub use tools::image_utils as ImageUtils;

/// 对应 Java: `org.ofdrw.reader.tools.NameSpaceModifier`(命名空间常量)
///
/// OFD 标准命名空间 URI: `http://www.ofdspec.org/2016`。
pub use tools::namespace_modifier::OFD_NAMESPACE;

#[cfg(test)]
mod tests {
    use super::*;
    use easyofd_core::{ImageObject, PathObject, TextObject};
    use easyofd_writer::OfdWriter;

    use easyofd_core::OfdPage;

    fn roundtrip(pages: Vec<OfdPage>) -> Vec<u8> {
        let mut writer = OfdWriter::new();
        for page in pages {
            writer.add_page(page);
        }
        writer.build().unwrap()
    }

    #[test]
    fn test_empty_document() {
        let bytes = OfdWriter::new().build().unwrap();
        let reader = OfdReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 0);
    }

    #[test]
    fn test_single_text_page() {
        let mut page = OfdPage::new(210.0, 297.0);
        page.add_text(TextObject::new(20.0, 30.0, "Hello OFD Reader!"));
        let bytes = roundtrip(vec![page]);

        let reader = OfdReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 1);
        assert_eq!(reader.pages()[0].content.len(), 1);

        let text = reader.extract_text();
        assert_eq!(text.len(), 1);
        assert!(text[0].contains("Hello OFD Reader!"));
    }

    #[test]
    fn test_multiple_pages() {
        let mut pages = Vec::new();
        for i in 1..=3 {
            let mut page = OfdPage::new(210.0, 297.0);
            page.add_text(TextObject::new(10.0, 20.0, format!("Page {i} text")));
            pages.push(page);
        }
        let bytes = roundtrip(pages);

        let reader = OfdReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 3);
        let text = reader.extract_text();
        assert_eq!(text.len(), 3);
        assert!(text[0].contains("Page 1"));
        assert!(text[2].contains("Page 3"));
    }

    #[test]
    fn test_extract_all_text() {
        let mut p1 = OfdPage::new(210.0, 297.0);
        p1.add_text(TextObject::new(10.0, 20.0, "First"));
        let mut p2 = OfdPage::new(210.0, 297.0);
        p2.add_text(TextObject::new(10.0, 20.0, "Second"));
        let bytes = roundtrip(vec![p1, p2]);

        let reader = OfdReader::from_bytes(&bytes).unwrap();
        let all = reader.extract_all_text();
        assert!(all.contains("First"));
        assert!(all.contains("Second"));
        assert!(all.contains("---"));
    }

    #[test]
    fn test_text_and_image() {
        let mut page = OfdPage::new(210.0, 297.0);
        page.add_text(TextObject::new(20.0, 30.0, "Invoice"));
        page.add_image(ImageObject::jpeg(150.0, 30.0, 30.0, 30.0, vec![0xFF, 0xD8]));
        let bytes = roundtrip(vec![page]);

        let reader = OfdReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.pages()[0].content.len(), 2);
        let easyofd_core::ContentObject::Image(image) = &reader.pages()[0].content[1] else {
            panic!("expected image");
        };
        assert_eq!(image.data, vec![0xFF, 0xD8]);
    }

    #[test]
    fn test_visit_selected_pages_without_collecting() {
        let mut pages = Vec::new();
        for number in 1..=4 {
            let mut page = OfdPage::new(210.0, 297.0);
            page.add_text(TextObject::new(10.0, 10.0, format!("page {number}")));
            pages.push(page);
        }
        let bytes = roundtrip(pages);
        let path = std::env::temp_dir().join("easyofd_visit_pages.ofd");
        std::fs::write(&path, bytes).unwrap();
        let mut visited = Vec::new();
        let count = OfdReader::visit_path(
            &path,
            ReadOptions {
                first_page: Some(2),
                last_page: Some(3),
                ..ReadOptions::default()
            },
            |number, page| {
                visited.push((number, ofd_reader::page_text(&page)));
                Ok(())
            },
        )
        .unwrap();
        assert_eq!(count, 2);
        assert_eq!(visited[0], (2, "page 2".to_string()));
        assert_eq!(visited[1], (3, "page 3".to_string()));
        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn test_path_roundtrip_is_not_silently_lost() {
        let mut page = OfdPage::new(210.0, 297.0);
        page.add_path(PathObject::hline(10.0, 20.0, 50.0));
        let bytes = roundtrip(vec![page]);
        let reader = OfdReader::from_bytes(&bytes).unwrap();
        assert!(matches!(
            reader.pages()[0].content[0],
            easyofd_core::ContentObject::Path(_)
        ));
    }

    #[test]
    fn test_from_file() {
        let dir = std::env::temp_dir().join("easyofd_reader");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.ofd");

        let mut page = OfdPage::new(210.0, 297.0);
        page.add_text(TextObject::new(10.0, 20.0, "File test"));
        let mut w = OfdWriter::new();
        w.add_page(page);
        w.build_to_file(&path).unwrap();

        let reader = OfdReader::open(&path).unwrap();
        assert_eq!(reader.page_count(), 1);
        assert!(reader.extract_all_text().contains("File test"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_invalid_data() {
        assert!(OfdReader::from_bytes(b"not a zip file").is_err());
    }

    #[test]
    fn test_styled_text() {
        let mut page = OfdPage::new(210.0, 297.0);
        page.add_text(
            TextObject::new(10.0, 20.0, "Styled")
                .font("SimHei")
                .size(18.0)
                .bold(),
        );
        let bytes = roundtrip(vec![page]);
        let reader = OfdReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 1);
        assert!(reader.extract_all_text().contains("Styled"));
    }

    // ─── BaseLoc resource resolution tests ─────────────────────────────────

    /// Build a minimal OFD ZIP whose `Doc_0/DocumentRes.xml` is the given
    /// XML string.  Returns the raw bytes of the ZIP archive.
    fn build_zip_with_document_res(document_res_xml: &str) -> Vec<u8> {
        use std::io::Write;

        let mut buf = std::io::Cursor::new(Vec::new());
        {
            let mut zip = zip::ZipWriter::new(&mut buf);
            let options = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);

            // OFD.xml
            zip.start_file("OFD.xml", options).unwrap();
            zip.write_all(
                br#"<?xml version="1.0" encoding="UTF-8"?>
<ofd:OFD xmlns:ofd="http://www.ofdspec.org/2016">
  <ofd:DocBody><ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot></ofd:DocBody>
</ofd:OFD>"#,
            )
            .unwrap();

            // Doc_0/Document.xml (single empty page)
            zip.start_file("Doc_0/Document.xml", options).unwrap();
            zip.write_all(
                br#"<?xml version="1.0" encoding="UTF-8"?>
<ofd:Document xmlns:ofd="http://www.ofdspec.org/2016">
  <ofd:CommonData>
    <ofd:PageArea><ofd:PhysicalBox>0 0 210 297</ofd:PhysicalBox></ofd:PageArea>
    <ofd:DocumentRes>DocumentRes.xml</ofd:DocumentRes>
  </ofd:CommonData>
  <ofd:Pages><ofd:Page BaseLoc="Pages/Page_0/Content.xml"/></ofd:Pages>
</ofd:Document>"#,
            )
            .unwrap();

            // Doc_0/Pages/Page_0/Content.xml (empty page)
            zip.start_file("Doc_0/Pages/Page_0/Content.xml", options)
                .unwrap();
            zip.write_all(
                br#"<?xml version="1.0" encoding="UTF-8"?>
<ofd:Page xmlns:ofd="http://www.ofdspec.org/2016">
  <ofd:Content/>
</ofd:Page>"#,
            )
            .unwrap();

            // Doc_0/DocumentRes.xml (caller-supplied content)
            zip.start_file("Doc_0/DocumentRes.xml", options).unwrap();
            zip.write_all(document_res_xml.as_bytes()).unwrap();

            zip.finish().unwrap();
        }
        buf.into_inner()
    }

    /// Helper: parse the DocumentRes.xml inside a test ZIP and return
    /// the `ResourceEntry` map keyed by resource ID.
    fn parse_resources_from_zip(bytes: &[u8]) -> std::collections::HashMap<String, String> {
        use parser::parse_document_resources;

        let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
        let resources =
            parse_document_resources(&mut archive, "Doc_0", Some("DocumentRes.xml")).unwrap();
        resources
            .into_iter()
            .map(|(id, entry)| (id, entry.location))
            .collect()
    }

    /// 对应 Java: ofdrw/ofdrw-parser/ResourceParser#parseBaseLoc
    ///
    /// When `<ofd:Res BaseLoc="Res">` is present, MediaFile paths must be
    /// resolved relative to the `Res/` subdirectory.
    #[test]
    fn parse_document_resources_respects_base_loc() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<ofd:Res xmlns:ofd="http://www.ofdspec.org/2016" BaseLoc="Res">
  <ofd:MultiMedias>
    <ofd:MultiMedia ID="6" Type="Image" Format="PNG">
      <ofd:MediaFile>qrcode.png</ofd:MediaFile>
    </ofd:MultiMedia>
  </ofd:MultiMedias>
</ofd:Res>"#;
        let bytes = build_zip_with_document_res(xml);
        let resources = parse_resources_from_zip(&bytes);

        assert_eq!(
            resources.get("6").map(String::as_str),
            Some("Res/qrcode.png"),
            "MediaFile path must include BaseLoc prefix"
        );
    }

    /// When there is no `BaseLoc` attribute, paths are stored as-is
    /// (backward-compatible with the pre-fix behaviour).
    #[test]
    fn parse_document_resources_no_base_loc_uses_default() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<ofd:Res xmlns:ofd="http://www.ofdspec.org/2016">
  <ofd:MultiMedias>
    <ofd:MultiMedia ID="10" Type="Image" Format="JPEG">
      <ofd:MediaFile>photo.jpg</ofd:MediaFile>
    </ofd:MultiMedia>
  </ofd:MultiMedias>
</ofd:Res>"#;
        let bytes = build_zip_with_document_res(xml);
        let resources = parse_resources_from_zip(&bytes);

        assert_eq!(
            resources.get("10").map(String::as_str),
            Some("photo.jpg"),
            "without BaseLoc, raw MediaFile path is kept"
        );
    }

    /// Nested `<ofd:Res>` elements must each maintain their own BaseLoc
    /// on the stack.  Resources inside the inner Res use the inner
    /// BaseLoc; resources after the inner Res close tag use the outer.
    #[test]
    fn parse_document_resources_nested_res() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<ofd:Res xmlns:ofd="http://www.ofdspec.org/2016" BaseLoc="Outer">
  <ofd:MultiMedias>
    <ofd:MultiMedia ID="1" Type="Image">
      <ofd:MediaFile>outer.png</ofd:MediaFile>
    </ofd:MultiMedia>
  </ofd:MultiMedias>
  <ofd:Res BaseLoc="Inner">
    <ofd:MultiMedias>
      <ofd:MultiMedia ID="2" Type="Image">
        <ofd:MediaFile>inner.png</ofd:MediaFile>
      </ofd:MultiMedia>
    </ofd:MultiMedias>
  </ofd:Res>
  <ofd:MultiMedias>
    <ofd:MultiMedia ID="3" Type="Image">
      <ofd:MediaFile>back_outer.png</ofd:MediaFile>
    </ofd:MultiMedia>
  </ofd:MultiMedias>
</ofd:Res>"#;
        let bytes = build_zip_with_document_res(xml);
        let resources = parse_resources_from_zip(&bytes);

        assert_eq!(
            resources.get("1").map(String::as_str),
            Some("Outer/outer.png"),
            "outer resource uses outer BaseLoc"
        );
        assert_eq!(
            resources.get("2").map(String::as_str),
            Some("Inner/inner.png"),
            "inner resource uses inner BaseLoc"
        );
        assert_eq!(
            resources.get("3").map(String::as_str),
            Some("Outer/back_outer.png"),
            "resource after inner Res closes uses outer BaseLoc again"
        );
    }

    // ─── Java 名称别名测试 ─────────────────────────────────────────────────

    #[test]
    fn test_ofd_reader_alias() {
        let bytes = OfdWriter::new().build().unwrap();
        // 通过 Java 风格别名 OFDReader 访问
        let reader = OFDReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 0);
    }

    #[test]
    fn test_bad_ofd_exception_alias() {
        let e = BadOFDException::corrupted("test alias");
        assert!(e.to_string().contains("test alias"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_dl_ofd_reader_alias() {
        let bytes = OfdWriter::new().build().unwrap();
        let reader = DLOFDReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 0);
    }

    #[test]
    #[allow(deprecated)]
    fn test_seal_ofd_reader_alias() {
        let bytes = OfdWriter::new().build().unwrap();
        let reader = SealOFDReader::from_bytes(&bytes).unwrap();
        assert_eq!(reader.page_count(), 0);
    }

    #[test]
    #[allow(deprecated)]
    fn test_ofd_document_vo_alias() {
        let vo = OFDDocumentVo::new("Doc_0", 210.0, 297.0, vec![]);
        assert_eq!(vo.doc_path, "Doc_0");
    }

    #[test]
    fn test_namespace_modifier_alias() {
        #[allow(deprecated)]
        let modifier = NameSpaceModifier::new();
        assert_eq!(modifier.expected_namespace(), OFD_NAMESPACE);
    }

    #[test]
    fn test_namespace_cleaner_alias() {
        let xml = "<ofd:OFD><ofd:DocBody/></ofd:OFD>";
        let result = NameSpaceCleaner::remove_ofd_prefix(xml);
        assert!(!result.contains("ofd:"));
    }

    #[test]
    fn test_zip_util_module_alias() {
        // ZipUtil 是 zip_util 模块的别名
        let data = {
            let mut buf = std::io::Cursor::new(Vec::new());
            {
                let mut zip = zip::ZipWriter::new(&mut buf);
                let options = zip::write::SimpleFileOptions::default()
                    .compression_method(zip::CompressionMethod::Stored);
                zip.start_file("test.txt", options).unwrap();
                std::io::Write::write_all(&mut zip, b"hello").unwrap();
                zip.finish().unwrap();
            }
            buf.into_inner()
        };
        let reader = std::io::Cursor::new(&data);
        let mut archive = zip::ZipArchive::new(reader).unwrap();
        let entries = ZipUtil::list_entries(&mut archive).unwrap();
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_delta_tool_module_alias() {
        let delta = vec!["1.0".into(), "2.0".into()];
        let result = DeltaTool::get_delta(Some(&delta), 2);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_image_utils_module_alias() {
        assert_eq!(
            ImageUtils::detect_format(&[0x89, 0x50, 0x4E, 0x47]),
            ImageUtils::ImageFormat::Png
        );
    }

    #[test]
    fn test_ofd_namespace_constant() {
        assert_eq!(OFD_NAMESPACE, "http://www.ofdspec.org/2016");
    }
}