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, чтобы их обнулить.

Смотрите также