Hướng Dẫn Nhà Phát Triển

Aspose.Note FOSS for Python is a free, open-source library for reading Microsoft OneNote .one các tệp section mà không phụ thuộc vào Microsoft Office. Nó cung cấp một API công cộng sạch sẽ dưới aspose.note gói, được mô hình hóa dựa trên Aspose.Note cho giao diện .NET. Thư viện phù hợp cho tự động hoá tài liệu, lập chỉ mục nội dung, các pipeline trích xuất dữ liệu, và quy trình làm việc lưu trữ.

Hướng dẫn dành cho nhà phát triển này bao gồm toàn bộ bề mặt API công cộng có sẵn trong phiên bản 26.3.1, kèm theo các ví dụ mã có thể chạy cho mọi tính năng chính.

Tải Tài Liệu

Tải một .one tệp từ đường dẫn tệp hoặc luồng nhị phân. The Document lớp là điểm vào cho mọi hoạt động.

Tải từ đường dẫn tệp

from aspose.note import Document

doc = Document("MyNotes.one")

Tải từ luồng nhị phân

Hữu ích khi đọc từ lưu trữ đám mây, phản hồi HTTP, hoặc bộ đệm trong bộ nhớ:

from pathlib import Path
from aspose.note import Document

with Path("MyNotes.one").open("rb") as f:
    doc = Document(f)

Tùy chọn tải

Sử dụng LoadOptions để đặt các tham số tùy chọn khi tải:

from aspose.note import Document, LoadOptions

opts = LoadOptions()
opts.LoadHistory = True   # Include page history in the DOM
doc = Document("MyNotes.one", opts)

Lưu ý: DocumentPassword tồn tại trên LoadOptions để tương thích API, nhưng tài liệu được mã hoá không được hỗ trợ. Cố gắng tải một tệp được mã hoá sẽ gây ra IncorrectPasswordException.


Cấu Trúc Tài Liệu (DOM)

Mô hình tài liệu OneNote là một cây:

Document
  └── Page (0..n)
        ├── Title
        │     ├── TitleText (RichText)
        │     ├── TitleDate (RichText)
        │     └── TitleTime (RichText)
        └── Outline (0..n)
              └── OutlineElement (0..n)
                    ├── RichText
                    ├── Image
                    ├── Table
                    │     └── TableRow
                    │           └── TableCell
                    │                 └── RichText / Image
                    └── AttachedFile

Mỗi nút đều cung cấp ParentNode và một Document thuộc tính đi lên tới gốc. Các nút tổng hợp hỗ trợ việc lặp lại các con, FirstChild, LastChild, AppendChildLast, InsertChild, RemoveChild, và GetChildNodes(Type).


Lặp qua Các Trang

Các Trang là các con trực tiếp của Document. Lặp lại chúng trực tiếp hoặc sử dụng GetChildNodes:

from aspose.note import Document, Page

doc = Document("MyNotes.one")

for page in doc:
    title = page.Title.TitleText.Text if page.Title and page.Title.TitleText else "(untitled)"
    author = page.Author or "(unknown)"
    print(f"  {title}  [by {author}]")

Siêu dữ liệu trang:

Thuộc tínhKiểuMô tả
Title`TitleNone`
Author`strNone`
CreationTime`datetimeNone`
LastModifiedTime`datetimeNone`
Level`intNone`

Trích xuất Văn bản

Trích xuất toàn bộ văn bản thuần

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
all_text = [rt.Text for rt in doc.GetChildNodes(RichText) if rt.Text]
print("\n".join(all_text))

Kiểm tra các đoạn định dạng

Mỗi RichText chứa một danh sách các TextRun đoạn. Mỗi lần chạy mang theo riêng của nó TextStyle:

from aspose.note import Document, RichText

doc = Document("FormattedNotes.one")
for rt in doc.GetChildNodes(RichText):
    for run in rt.TextRuns:
        style = run.Style
        flags = []
        if style.IsBold: flags.append("bold")
        if style.IsItalic: flags.append("italic")
        if style.IsHyperlink: flags.append(f"link={style.HyperlinkAddress}")
        print(f"{run.Text!r:40s} [{', '.join(flags)}]")

Trích xuất siêu liên kết

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    for run in rt.TextRuns:
        if run.Style.IsHyperlink and run.Style.HyperlinkAddress:
            print(run.Text, "->", run.Style.HyperlinkAddress)

Trích xuất Hình ảnh

from aspose.note import Document, Image

doc = Document("MyNotes.one")
for i, img in enumerate(doc.GetChildNodes(Image), start=1):
    name = img.FileName or f"image_{i}.bin"
    with open(name, "wb") as f:
        f.write(img.Bytes)
    print(f"Saved {name}  ({img.Width}x{img.Height})")

Thuộc tính hình ảnh: FileName, Bytes, Width, Height, AlternativeTextTitle, AlternativeTextDescription, HyperlinkUrl, Tags.


Phân tích Bảng

from aspose.note import Document, Table, TableRow, TableCell, RichText

doc = Document("MyNotes.one")
for table in doc.GetChildNodes(Table):
    print("Column widths:", [col.Width for col in table.Columns])
    for r, row in enumerate(table.GetChildNodes(TableRow), start=1):
        cells = row.GetChildNodes(TableCell)
        row_text = [
            " ".join(rt.Text for rt in cell.GetChildNodes(RichText)).strip()
            for cell in cells
        ]
        print(f"Row {r}:", row_text)

Tệp Đính kèm

from aspose.note import Document, AttachedFile

doc = Document("NotesWithAttachments.one")
for i, af in enumerate(doc.GetChildNodes(AttachedFile), start=1):
    name = af.FileName or f"attachment_{i}.bin"
    with open(name, "wb") as f:
        f.write(af.Bytes)
    print(f"Saved: {name}")

Thẻ và Danh sách Đánh số

Kiểm tra các mục NoteTag

from aspose.note import Document, RichText, Image, Table

doc = Document("TaggedNotes.one")
for rt in doc.GetChildNodes(RichText):
    for tag in rt.Tags:
        print(f"RichText tag: {tag.Label} icon={tag.Icon}")
for img in doc.GetChildNodes(Image):
    for tag in img.Tags:
        print(f"Image tag: {tag.Label}")

Kiểm tra danh sách đánh số

from aspose.note import Document, OutlineElement

doc = Document("NumberedNotes.one")
for oe in doc.GetChildNodes(OutlineElement):
    nl = oe.NumberList
    if nl:
        print(f"format={nl.Format!r}")

Mẫu DocumentVisitor

Sử dụng DocumentVisitor để triển khai một visitor duyệt toàn bộ cây tài liệu:

from aspose.note import Document, DocumentVisitor, Page, RichText, Image

class ContentCounter(DocumentVisitor):
    def __init__(self):
        self.pages = 0
        self.texts = 0
        self.images = 0

    def VisitPageStart(self, page: Page) -> None:
        self.pages += 1

    def VisitRichTextStart(self, rt: RichText) -> None:
        self.texts += 1

    def VisitImageStart(self, img: Image) -> None:
        self.images += 1

doc = Document("MyNotes.one")
counter = ContentCounter()
doc.Accept(counter)
print(f"Pages: {counter.pages}, Texts: {counter.texts}, Images: {counter.images}")

Xuất PDF

Xuất PDF yêu cầu phụ thuộc tùy chọn ReportLab. Cài đặt nó bằng:

pip install "aspose-note[pdf]"

Xuất PDF cơ bản

from aspose.note import Document, SaveFormat

doc = Document("MyNotes.one")
doc.Save("output.pdf", SaveFormat.Pdf)

Xuất PDF với các tùy chọn

import io
from aspose.note import Document, SaveFormat
from aspose.note.saving import PdfSaveOptions

doc = Document("MyNotes.one")

##With save options
opts = PdfSaveOptions()
doc.Save("output.pdf", opts)

##Save to in-memory stream
buf = io.BytesIO()
doc.Save(buf, PdfSaveOptions())
pdf_bytes = buf.getvalue()

Lưu ý: PdfSaveOptions.PageIndexPageCount các trường tồn tại nhưng không được chuyển tiếp tới bộ xuất PDF trong v26.3.1. Toàn bộ tài liệu luôn được xuất.


Các hạn chế hiện tại

Khu vựcTrạng thái
Đọc .one tệpĐược hỗ trợ đầy đủ
Xuất PDF (qua ReportLab)Được hỗ trợ
Ghi lại vào .oneChưa được triển khai
Tài liệu được mã hoáKhông được hỗ trợ (gây ra IncorrectPasswordException)
Định dạng lưu HTML / hình ảnh / ONEĐược khai báo để tương thích API; raise UnsupportedSaveFormatException

Hướng dẫn có sẵn


Xem Thêm

 Tiếng Việt