Skip to content

Видобування метаданих документа

Кожен формат Office містить невеликий набір «основних властивостей» — автор, дата останньої зміни, заголовок, тема, ключові слова — плюс розширений набір, специфічний для кожного формату. Office Oxide надає доступ до обох.

Формат та базова інформація

Хендл Document повертає назву формату й лічильники (аркуші, слайди, розділи):

Rust

use office_oxide::{Document, DocumentFormat};

let doc = Document::open("report.docx")?;
assert_eq!(doc.format(), DocumentFormat::Docx);

Python

from office_oxide import Document

with Document.open("report.docx") as doc:
    print(doc.format)            # "docx"
    print(doc.detect_format())   # confirms via magic bytes

JavaScript

using doc = Document.open('report.docx');
console.log(doc.format);        // "docx"

Go

doc, err := officeoxide.Open("report.docx")
if err != nil { log.Fatal(err) }
defer doc.Close()

fmtName, _ := doc.Format()   // "docx"
fmt.Println(fmtName)

C#

using OfficeOxide;

using var doc = Document.Open("report.docx");
Console.WriteLine(doc.Format);   // "docx"

C

int err = 0;
OfficeDocumentHandle *doc = office_document_open("report.docx", &err);
if (!doc) { fprintf(stderr, "open failed: code=%d\n", err); return 1; }
const char *fmt = office_document_format(doc);   /* "docx" — do NOT free */
printf("%s\n", fmt);
office_document_free(doc);

WASM

import { WasmDocument } from 'office-oxide-wasm';

const data = new Uint8Array(await (await fetch('/report.docx')).arrayBuffer());
using doc = new WasmDocument(data, 'docx');
console.log(doc.formatName());   // "docx"

Основні властивості

У форматах OOXML основні властивості зберігаються у docProps/core.xml. Нативні біндинги надають типізований аксесор core_properties(); Go, C#, C і WASM зчитують ті самі поля з блоку metadata уніфікованого JSON IR.

Rust

use office_oxide::Document;

let doc = Document::open("report.docx")?;
if let Some(docx) = doc.as_docx() {
    let props = docx.core_properties();
    println!("{:?}", props.title);
    println!("{:?}", props.author);
}

Python

from office_oxide import Document

with Document.open("report.docx") as doc:
    docx = doc.as_docx()
    props = docx.core_properties()
    print(props.title)            # str | None
    print(props.author)           # str | None
    print(props.created)          # datetime | None
    print(props.modified)         # datetime | None
    print(props.subject)          # str | None
    print(props.keywords)         # str | None

Go

doc, _ := officeoxide.Open("report.docx")
defer doc.Close()

irJSON, _ := doc.ToIRJSON()
var ir struct {
    Metadata struct {
        Title    string `json:"title"`
        Author   string `json:"author"`
        Created  string `json:"created"`
        Modified string `json:"modified"`
        Subject  string `json:"subject"`
        Keywords string `json:"keywords"`
    } `json:"metadata"`
}
json.Unmarshal([]byte(irJSON), &ir)
fmt.Println(ir.Metadata.Title, ir.Metadata.Author)

C#

using OfficeOxide;
using System.Text.Json;

using var doc = Document.Open("report.docx");
using var ir = JsonDocument.Parse(doc.ToIrJson());

var meta = ir.RootElement.GetProperty("metadata");
Console.WriteLine(meta.GetProperty("title").GetString());
Console.WriteLine(meta.GetProperty("author").GetString());
Console.WriteLine(meta.GetProperty("created").GetString());

C

int err = 0;
OfficeDocumentHandle *doc = office_document_open("report.docx", &err);
char *ir_json = office_document_to_ir_json(doc, &err);   /* DocumentIR as JSON */
if (ir_json) {
    /* parse with your JSON lib; read ir["metadata"]["title"], ["author"], ... */
    office_oxide_free_string(ir_json);
}
office_document_free(doc);

WASM

import { WasmDocument } from 'office-oxide-wasm';

const data = new Uint8Array(await (await fetch('/report.docx')).arrayBuffer());
using doc = new WasmDocument(data, 'docx');
const meta = doc.toIr().metadata;          // JS object
console.log(meta.title, meta.author, meta.created);

Той самий аксесор core_properties() наявний також у as_xlsx() і as_pptx().

Розширені властивості застосунку

docProps/app.xml зберігає розширені метадані: кількість сторінок, слів, абзаців, слайдів, назву та версію застосунку, гіперпосилання тощо.

Python

with Document.open("report.docx") as doc:
    app = doc.as_docx().app_properties()
    print(app.application)   # "Microsoft Office Word"
    print(app.app_version)
    print(app.pages)
    print(app.words)
    print(app.paragraphs)

Для PPTX app_properties() надає slides, notes, presentation_format тощо. Для XLSX — список назв аркушів.

Користувацькі властивості

core_properties() і app_properties() покривають стандартні набори. Щоб отримати ключі, визначені застосунком (задані у Word через «Властивості документа → Розширені властивості»), використовуйте:

Python

with Document.open("report.docx") as doc:
    custom = doc.as_docx().custom_properties()
    for name, value in custom.items():
        print(name, value)

Застарілі формати

DOC, XLS і PPT зберігають метадані у потоках OLE2 \005SummaryInformation і \005DocumentSummaryInformation. Office Oxide розбирає їх у ту саму структуру core_properties():

Python

with Document.open("legacy.doc") as doc:
    props = doc.as_doc().core_properties()
    print(props.author, props.created)

Чому це важливо

  • Пошукова індексація — заголовок, автор і ключові слова забезпечують виявлення документів.
  • Відповідність вимогам — дата останньої зміни, автор і журнал правок складають основу аудиторського сліду.
  • Дедублікація — автор + заголовок + дата створення дає дешевий, але ефективний відбиток документа.
  • Видалення персональних даних — зчитайте основні властивості перед публікацією, а тоді скористайтесь EditableDocument, щоб їх очистити.

Дивіться також