功能概览 — Aspose.Note FOSS for Python
Aspose.Note FOSS for Python (package aspose-note,,版本 26.3.1)提供一个 Python API 用于读取 Microsoft OneNote .one 节文件并将其导出为 PDF。以下列出的所有功能均已通过仓库源代码、README 和示例脚本进行验证。.
安装与设置
从 PyPI 安装::
pip install aspose-notePDF 导出支持(需要 ReportLab)::
pip install "aspose-note[pdf]"要求:Python 3.10 或更高版本。不需要安装 Microsoft Office。.
功能与特性
.one 文件加载
从文件路径或任何二进制流(文件句柄,, io.BytesIO,,HTTP 响应体,云存储流).
Document.FileFormat提供对 OneNote 文件格式版本的尽力指示(OneNote2010、OneNoteOnline 或 OneNote2007)- 基于流的加载消除了内存或网络工作流中的磁盘 I/O
LoadOptions.LoadHistory标志控制是否在 DOM 中包含页面历史记录
from aspose.note import Document
##From a file path
doc = Document("notebook.one")
##From a binary stream
with open("notebook.one", "rb") as f:
doc = Document(f)文档 DOM 遍历
完整的 OneNote 文档以已键入的 Python 对象树形式公开。每个节点继承自 Node 或 CompositeNode:
Document::根;公开DisplayName,CreationTime,FileFormatPage::的直接子节点Document;;公开Title,Author,CreationTime,LastModifiedTime,LevelTitle::公开TitleText,TitleDate,TitleTime(全部RichText节点)Outline::具有位置的容器,包含HorizontalOffset,VerticalOffset,MaxWidth,MaxHeight,MinWidth,ReservedWidth,IndentPositionOutlineElement::叶子容器;公开NumberList
导航方法在 CompositeNode:
| 方法 / 属性 | 描述 |
|---|---|
FirstChild, LastChild | 直接子级访问 |
GetChildNodes(Type) | 递归、类型过滤的搜索 |
AppendChildLast(node) | 在末尾添加子节点 |
AppendChildFirst(node) | 在开头添加子节点 |
InsertChild(index, node) | 在位置插入 |
RemoveChild(node) | 移除子节点 |
for child in node | 遍历直接子节点 |
from aspose.note import Document, Page, Outline, OutlineElement, RichText
doc = Document("notebook.one")
for page in doc.GetChildNodes(Page):
title_text = page.Title.TitleText.Text if page.Title and page.Title.TitleText else ""
print(f"Page: {title_text}")
for outline in page.GetChildNodes(Outline):
for oe in outline.GetChildNodes(OutlineElement):
for rt in oe.GetChildNodes(RichText):
print(f" {rt.Text}")富文本内容提取
RichText 节点暴露::
Text: str::完整纯文本字符串TextRuns: list[TextRun]::格式化片段列表Tags: list[NoteTag]::附加在此块的 OneNote 标签Append(text, style=None)::在内存中追加文本运行Replace(old_value, new_value)::内存中的字符串替换
每个 TextRun 携带::
| 属性 | 类型 | 描述 |
|---|---|---|
Text | str | 段落文本 |
Style | TextStyle | 格式化元数据 |
TextStyle 属性:
| 属性 | 类型 |
|---|---|
IsBold, IsItalic, IsUnderline, IsStrikethrough | bool |
IsSuperscript, IsSubscript | bool |
FontName | `str |
FontSize | `float |
FontColor, Highlight | `int |
Language | `int |
IsHyperlink | bool |
HyperlinkAddress | `str |
from aspose.note import Document, RichText
doc = Document("notebook.one")
for rt in doc.GetChildNodes(RichText):
for run in rt.TextRuns:
if run.Style.IsHyperlink:
print(f"Hyperlink: {run.Text} -> {run.Style.HyperlinkAddress}")
if run.Style.IsBold:
print(f"Bold text: {run.Text}")图像提取
Image 节点公开每个嵌入图像的原始字节和元数据::
| 属性 | 类型 | 描述 |
|---|---|---|
FileName | `str | None` |
Bytes | bytes | 原始图像数据 |
Width, Height | `float | None` |
AlternativeTextTitle | `str | None` |
AlternativeTextDescription | `str | None` |
HyperlinkUrl | `str | None` |
Tags | list[NoteTag] | 附加的 OneNote 标签 |
from aspose.note import Document, Image
doc = Document("notebook.one")
for i, img in enumerate(doc.GetChildNodes(Image), start=1):
filename = img.FileName or f"image_{i}.bin"
with open(filename, "wb") as f:
f.write(img.Bytes)
print(f"Saved: {filename} ({img.Width} x {img.Height} pts)")附件文件提取
AttachedFile 节点公开嵌入的文件附件::
| 属性 | 类型 | 描述 |
|---|---|---|
FileName | `str | None` |
Bytes | bytes | 原始文件数据 |
Tags | list[NoteTag] | 附加的 OneNote 标签 |
from aspose.note import Document, AttachedFile
doc = Document("notebook.one")
for i, af in enumerate(doc.GetChildNodes(AttachedFile), start=1):
filename = af.FileName or f"attachment_{i}.bin"
with open(filename, "wb") as f:
f.write(af.Bytes)表格解析
Table, TableRow,,并且 TableCell 暴露完整的表结构::
| 类 | 关键属性 |
|---|---|
Table | Columns: list[TableColumn] (每个 TableColumn 有 .Width 并且 .LockedWidth), IsBordersVisible: bool, Tags: list[NoteTag] |
TableRow | 通过遍历单元格 GetChildNodes(TableCell) |
TableCell | 包含 RichText, Image,,以及其他内容节点 |
from aspose.note import Document, Table, TableRow, TableCell, RichText
doc = Document("notebook.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)
values = [
" ".join(rt.Text for rt in cell.GetChildNodes(RichText)).strip()
for cell in cells
]
print(f"Row {r}:", values)OneNote 标签检查
NoteTag 出现在 RichText, Image, AttachedFile,,并且 Table 节点通过它们的 .Tags 属性。. OutlineElement 没有 .Tags 属性。. NoteTag 属性:
| 属性 | 类型 | 描述 |
|---|---|---|
Icon | `int | None` |
Label | `str | None` |
FontColor | `int | None` |
Highlight | `int | None` |
CreationTime | `datetime | None` |
CompletedTime | `datetime | None` |
工厂方法:: NoteTag.CreateYellowStar() 创建一个标准的黄色星形标签节点。.
from aspose.note import Document, RichText
doc = Document("notebook.one")
for rt in doc.GetChildNodes(RichText):
for tag in rt.Tags:
print(f"Tag: {tag.Label} (icon={tag.Icon}, completed={tag.CompletedTime})")编号列表支持
OutlineElement.NumberList 公开::
| 属性 | 类型 | 描述 |
|---|---|---|
Format | `str | None` |
Restart | `int | None` |
from aspose.note import Document, OutlineElement
doc = Document("notebook.one")
for oe in doc.GetChildNodes(OutlineElement):
nl = oe.NumberList
if nl:
print(f"format={nl.Format!r}")DocumentVisitor 遍历
DocumentVisitor 提供用于结构化全文档遍历的访问者模式。覆盖任意 VisitXxxStart / VisitXxxEnd 方法以拦截特定节点类型::
VisitDocumentStart(doc)/VisitDocumentEnd(doc)VisitPageStart(page)/VisitPageEnd(page)VisitTitleStart(title)/VisitTitleEnd(title)VisitOutlineStart(outline)/VisitOutlineEnd(outline)VisitOutlineElementStart(oe)/VisitOutlineElementEnd(oe)VisitRichTextStart(rt)/VisitRichTextEnd(rt)VisitImageStart(img)/VisitImageEnd(img)
from aspose.note import Document, DocumentVisitor, Page, RichText, Image
class MySummaryVisitor(DocumentVisitor):
def __init__(self):
self.pages, self.texts, self.images = 0, 0, 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("notebook.one")
v = MySummaryVisitor()
doc.Accept(v)
print(f"Pages={v.pages} RichText={v.texts} Images={v.images}")PDF 导出
使用 将已加载的文档保存为 PDF Document.Save(). 通过可选的 ReportLab 后端支持。.
from aspose.note import Document, SaveFormat
doc = Document("notebook.one")
doc.Save("output.pdf", SaveFormat.Pdf)PdfSaveOptions
| 选项 | 类型 | 描述 |
|---|---|---|
PageIndex | int | 字段存在;; 在 v26.3.1 中未转发至 PDF 导出器 (没有效果) |
PageCount | `int | None` |
ImageCompression | `Any | None` |
JpegQuality | `int | None` |
PageSettings | `Any | None` |
PageSplittingAlgorithm | `Any | None` |
import io
from aspose.note import Document, SaveFormat
from aspose.note.saving import PdfSaveOptions
doc = Document("notebook.one")
##Save to file
doc.Save("output.pdf", SaveFormat.Pdf)
##Save to in-memory stream
buf = io.BytesIO()
doc.Save(buf, PdfSaveOptions())
pdf_bytes = buf.getvalue()格式和枚举参考
SaveFormat
| 值 | 状态 |
|---|---|
SaveFormat.Pdf | 已实现(需要 ReportLab) |
FileFormat
Document.FileFormat 提供对 OneNote 文件格式版本的最佳努力指示。该枚举声明了三个值::
| 值 | 描述 |
|---|---|
FileFormat.OneNote2010 | OneNote 2010 格式 |
FileFormat.OneNoteOnline | OneNote Online 格式 |
FileFormat.OneNote2007 | OneNote 2007 格式 |
NodeType
NodeType.Document, NodeType.Page, NodeType.Outline, NodeType.OutlineElement, NodeType.RichText, NodeType.Image, NodeType.Table, NodeType.AttachedFile
HorizontalAlignment
HorizontalAlignment.Left, HorizontalAlignment.Center, HorizontalAlignment.Right
当前限制
| 限制 | 细节 |
|---|---|
| 只读 | 写回至 .one 尚未实现该格式 |
| 无加密 | 加密文档会引发 IncorrectPasswordException |
| 仅支持 PDF 导出 | 其他 SaveFormat 值会引发 UnsupportedSaveFormatException |
| 需要 ReportLab 才能生成 PDF | 安装 pip install "aspose-note[pdf]" 单独 |
GetPageHistory 返回单元素列表 | 完整页面历史遍历是存根;返回 [page] |
DetectLayoutChanges() | 兼容性存根;不执行任何操作 |
技巧与最佳实践
- 检查 None:
Page.Title,Title.TitleText,OutlineElement.NumberList,,并且大多数元数据字段可以None.。始终使用if x is not None或if x在访问属性之前。. - 使用
GetChildNodes(Type)用于递归搜索,而不是手动遍历树。它会搜索整个子树。. - 遍历直接子节点 使用
for child in node当您只需要直接子节点时。. - 处理 Windows 上的编码::在 Windows 上,,
sys.stdout可能使用旧的代码页。添加sys.stdout.reconfigure(encoding="utf-8", errors="replace")在启动时用于打印 Unicode 文本。. - 安装
[pdf]额外的::不要导入SaveFormat.Pdf功能,除非先安装pip install "aspose-note[pdf]".。如果没有 ReportLab,保存为 PDF 时会在运行时抛出导入错误。.