Ръководство за разработчици
Aspose.Note FOSS for Python is a free, open-source library for reading Microsoft OneNote .one секционни файлове без никаква зависимост от Microsoft Office. Той предоставя чист публичен API под the aspose.note пакет, моделиран след Aspose.Note за .NET интерфейс. Библиотеката е подходяща за автоматизация на документи, индексиране на съдържание, конвейери за извличане на данни и архивни работни потоци.
Този ръководство за разработчици обхваща пълната публична API повърхност, достъпна във версия 26.3.1, с изпълними примерни кодове за всяка основна функция.
Зареждане на документ
Заредете a .one файл от път към файл или бинарен поток. The Document class е входната точка за всички операции.
Зареждане от път към файл
from aspose.note import Document
doc = Document("MyNotes.one")Зареждане от двоичен поток
Полезно при четене от облачно съхранение, HTTP отговори или буфери в паметта:
from pathlib import Path
from aspose.note import Document
with Path("MyNotes.one").open("rb") as f:
doc = Document(f)Опции за зареждане
Използвайте LoadOptions за задаване на незадължителни параметри при зареждане:
from aspose.note import Document, LoadOptions
opts = LoadOptions()
opts.LoadHistory = True # Include page history in the DOM
doc = Document("MyNotes.one", opts)Бележка: DocumentPassword съществува на LoadOptions за съвместимост с API, но криптираните документи не се поддържат. Опитът да се зареди криптиран файл предизвиква IncorrectPasswordException.
Структура на документа (DOM)
Моделът на OneNote документа е дърво:
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Всеки възел предоставя ParentNode и Document свойство, което се изкачва до корена. Съставните възли поддържат итерация на децата, FirstChild, LastChild, AppendChildLast, InsertChild, RemoveChild, и GetChildNodes(Type).
Итерация на страници
Страниците са директните деца на Document. Итерирайте ги директно или използвайте 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}]")Метаданни на страницата:
| Свойство | Тип | Описание |
|---|---|---|
Title | `Title | None` |
Author | `str | None` |
CreationTime | `datetime | None` |
LastModifiedTime | `datetime | None` |
Level | `int | None` |
Извличане на текст
Извлечете целия прост текст
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))Прегледайте форматиращите участъци
Всеки RichText съдържа списък от TextRun сегменти. Всяко изпълнение носи своето 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)}]")Извличане на хипервръзки
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)Извличане на изображения
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})")Свойства на изображението: FileName, Bytes, Width, Height, AlternativeTextTitle, AlternativeTextDescription, HyperlinkUrl, Tags.
Парсиране на таблици
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)Прикачени файлове
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}")Тагове и номерирани списъци
Прегледайте елементите 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}")Прегледайте номерираните списъци
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}")Шаблон DocumentVisitor
Използвайте DocumentVisitor за да реализирате посетител, който обхожда цялото дърво на документа:
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}")Експортиране в PDF
Експортирането в PDF изисква опционалната зависимост ReportLab. Инсталирайте я с:
pip install "aspose-note[pdf]"Основен PDF експорт
from aspose.note import Document, SaveFormat
doc = Document("MyNotes.one")
doc.Save("output.pdf", SaveFormat.Pdf)PDF експорт с опции
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()Забележка: PdfSaveOptions.PageIndex и PageCount полетата съществуват, но не се предават към PDF експортер в v26.3.1. Целият документ винаги се експортира.
Текущи ограничения
| Област | Състояние |
|---|---|
Четене .one файлове | Пълна поддръжка |
| PDF експортиране (чрез ReportLab) | Поддържано |
Записване обратно към .one | Не е реализирано |
| Криптирани документи | Не се поддържа (повдига IncorrectPasswordException) |
| HTML / image / ONE формати за запазване | Обявено за съвместимост с API; повдига UnsupportedSaveFormatException |
Налични ръководства
- Преглед на функциите: пълен списък с функции с доказателства
- Започване: предпоставки, инсталиране и първи стъпки
- Инсталиране: pip install и незадължителни зависимости