Tổng quan tính năng — Aspose.Note FOSS cho Python
Aspose.Note FOSS for Python (package aspose-note, phiên bản 26.3.1) cung cấp một API Python để đọc Microsoft OneNote .one các tệp phần và xuất chúng ra PDF. Tất cả các tính năng được liệt kê dưới đây đã được xác minh dựa trên mã nguồn của kho, README và các script mẫu.
Cài đặt và Thiết lập
Cài đặt từ PyPI:
pip install aspose-noteĐể hỗ trợ xuất PDF (cần ReportLab):
pip install "aspose-note[pdf]"Yêu cầu: Python 3.10 trở lên. Không cần cài đặt Microsoft Office.
Tính năng và Khả năng
.Tải tệp .one
Tải các tệp phần Microsoft OneNote từ đường dẫn tệp hoặc bất kỳ luồng nhị phân nào (trình xử lý tệp, io.BytesIO, nội dung phản hồi HTTP, luồng lưu trữ đám mây).
Document.FileFormatcung cấp một chỉ báo nỗ lực tốt nhất về phiên bản định dạng tệp OneNote (OneNote2010, OneNoteOnline hoặc OneNote2007)- Việc tải dựa trên luồng loại bỏ I/O đĩa cho các quy trình làm việc trong bộ nhớ hoặc qua mạng
LoadOptions.LoadHistorycờ điều khiển việc lịch sử trang có được bao gồm trong DOM hay không
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)Duyệt DOM tài liệu
Toàn bộ tài liệu OneNote được hiển thị dưới dạng cây các đối tượng Python có kiểu. Mỗi nút kế thừa từ Node hoặc CompositeNode:
Document: gốc; hiển thịDisplayName,CreationTime,FileFormatPage: con trực tiếp củaDocument; hiển thịTitle,Author,CreationTime,LastModifiedTime,LevelTitle: hiển thịTitleText,TitleDate,TitleTime(tất cảRichTextcác nút)Outline: container vị trí vớiHorizontalOffset,VerticalOffset,MaxWidth,MaxHeight,MinWidth,ReservedWidth,IndentPositionOutlineElement: container lá; hiển thịNumberList
Các phương pháp điều hướng trên CompositeNode:
| Phương thức / Thuộc tính | Mô tả |
|---|---|
FirstChild, LastChild | Truy cập trực tiếp vào phần tử con |
GetChildNodes(Type) | Tìm kiếm đệ quy, lọc theo kiểu |
AppendChildLast(node) | Thêm phần tử con vào cuối |
AppendChildFirst(node) | Thêm phần tử con vào đầu |
InsertChild(index, node) | Chèn vào vị trí |
RemoveChild(node) | Xóa một phần tử con |
for child in node | Duyệt các phần tử con trực tiếp |
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}")Trích xuất nội dung văn bản giàu định dạng
RichText các nút cung cấp:
Text: str: chuỗi văn bản thuần đầy đủTextRuns: list[TextRun]: danh sách các đoạn đã định dạngTags: list[NoteTag]: thẻ OneNote gắn vào khối nàyAppend(text, style=None): thêm một đoạn văn bản vào bộ nhớ tạmReplace(old_value, new_value): thay thế chuỗi trong bộ nhớ tạm
Mỗi TextRun có:
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
Text | str | Văn bản phân đoạn |
Style | TextStyle | Siêu dữ liệu định dạng |
TextStyle thuộc tính:
| Thuộc tính | Kiểu |
|---|---|
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}")Trích xuất Hình ảnh
Image các nút cung cấp byte thô và siêu dữ liệu cho mỗi hình ảnh được nhúng:
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
FileName | `str | None` |
Bytes | bytes | Dữ liệu hình ảnh thô |
Width, Height | `float | None` |
AlternativeTextTitle | `str | None` |
AlternativeTextDescription | `str | None` |
HyperlinkUrl | `str | None` |
Tags | list[NoteTag] | Thẻ OneNote đính kèm |
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)")Trích xuất tệp đính kèm
AttachedFile các nút cung cấp các tệp đính kèm được nhúng:
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
FileName | `str | None` |
Bytes | bytes | Dữ liệu tệp thô |
Tags | list[NoteTag] | Thẻ OneNote đính kèm |
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)Phân tích Bảng
Table, TableRow, và TableCell hiển thị toàn bộ cấu trúc bảng:
| Lớp | Thuộc tính chính |
|---|---|
Table | Columns: list[TableColumn] (mỗi TableColumn có .Width và .LockedWidth), IsBordersVisible: bool, Tags: list[NoteTag] |
TableRow | Duyệt các ô qua GetChildNodes(TableCell) |
TableCell | Chứa RichText, Image, và các nút nội dung khác |
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)Kiểm tra thẻ OneNote
NoteTag xuất hiện trên RichText, Image, AttachedFile, và Table các nút qua .Tags thuộc tính. OutlineElement không có một .Tags thuộc tính. NoteTag thuộc tính:
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
Icon | `int | None` |
Label | `str | None` |
FontColor | `int | None` |
Highlight | `int | None` |
CreationTime | `datetime | None` |
CompletedTime | `datetime | None` |
Phương thức nhà máy: NoteTag.CreateYellowStar() tạo một nút thẻ sao vàng tiêu chuẩn.
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})")Hỗ trợ danh sách có số thứ tự
OutlineElement.NumberList công khai:
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
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}")Duyệt DocumentVisitor
DocumentVisitor cung cấp mẫu visitor cho việc duyệt tài liệu đầy đủ có cấu trúc. Ghi đè bất kỳ VisitXxxStart / VisitXxxEnd phương thức nào để chặn các loại nút cụ thể:
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}")Xuất PDF
Lưu tài liệu đã tải vào dưới dạng PDF bằng Document.Save(). Được hỗ trợ thông qua backend ReportLab tùy chọn.
from aspose.note import Document, SaveFormat
doc = Document("notebook.one")
doc.Save("output.pdf", SaveFormat.Pdf)PdfSaveOptions
| Tùy chọn | Kiểu | Mô tả |
|---|---|---|
PageIndex | int | Trường tồn tại; không được chuyển tiếp tới bộ xuất PDF trong v26.3.1 (không có tác dụng) |
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()Tham chiếu Định dạng và Enum
SaveFormat
| Giá trị | Trạng thái |
|---|---|
SaveFormat.Pdf | Đã triển khai (cần ReportLab) |
FileFormat
Document.FileFormat cung cấp chỉ báo nỗ lực tốt nhất về phiên bản định dạng tệp OneNote. Enum khai báo ba giá trị:
| Giá trị | Mô tả |
|---|---|
FileFormat.OneNote2010 | Định dạng OneNote 2010 |
FileFormat.OneNoteOnline | Định dạng OneNote Online |
FileFormat.OneNote2007 | Định dạng 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
Các hạn chế hiện tại
| Hạn chế | Chi tiết |
|---|---|
| Chỉ đọc | Ghi lại vào .one định dạng chưa được triển khai |
| Không mã hoá | Tài liệu được mã hoá gây ra IncorrectPasswordException |
| Chỉ PDF để xuất | Khác SaveFormat các giá trị tăng UnsupportedSaveFormatException |
| Cần ReportLab cho PDF | Cài đặt pip install "aspose-note[pdf]" riêng biệt |
GetPageHistory trả về danh sách một phần tử | Việc duyệt lịch sử toàn trang là một stub; trả về [page] |
DetectLayoutChanges() | Đoạn stub tương thích; không thực hiện |
Mẹo và Thực hành Tốt nhất
- Kiểm tra giá trị None:
Page.Title,Title.TitleText,OutlineElement.NumberList, và hầu hết các trường metadata có thểNone. Luôn bảo vệ bằngif x is not Nonehoặcif xtrước khi truy cập các thuộc tính. - Sử dụng
GetChildNodes(Type)để tìm kiếm đệ quy thay vì tự động duyệt cây. Nó tìm kiếm toàn bộ nhánh con. - Lặp qua các con trực tiếp với
for child in nodekhi bạn chỉ cần các con trực tiếp. - Xử lý mã hoá trên Windows: Trên Windows,
sys.stdoutcó thể sử dụng một trang mã kế thừa. Thêmsys.stdout.reconfigure(encoding="utf-8", errors="replace")khi khởi động khi in văn bản Unicode. - Cài đặt
[pdf]thêm: Không nhậpSaveFormat.Pdfchức năng mà không cài đặt trướcpip install "aspose-note[pdf]". Nếu không có ReportLab, việc lưu dưới dạng PDF sẽ gây ra lỗi import tại thời gian chạy.