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.FileFormat cung 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.LoadHistory cờ đ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, FileFormat
  • Page: con trực tiếp của Document; hiển thị Title, Author, CreationTime, LastModifiedTime, Level
  • Title: hiển thị TitleText, TitleDate, TitleTime (tất cả RichText các nút)
  • Outline: container vị trí với HorizontalOffset, VerticalOffset, MaxWidth, MaxHeight, MinWidth, ReservedWidth, IndentPosition
  • OutlineElement: 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ínhMô tả
FirstChild, LastChildTruy 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 nodeDuyệ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ạng
  • Tags: list[NoteTag]: thẻ OneNote gắn vào khối này
  • Append(text, style=None): thêm một đoạn văn bản vào bộ nhớ tạm
  • Replace(old_value, new_value): thay thế chuỗi trong bộ nhớ tạm

Mỗi TextRun có:

Thuộc tínhKiểuMô tả
TextstrVăn bản phân đoạn
StyleTextStyleSiêu dữ liệu định dạng

TextStyle thuộc tính:

Thuộc tínhKiểu
IsBold, IsItalic, IsUnderline, IsStrikethroughbool
IsSuperscript, IsSubscriptbool
FontName`str
FontSize`float
FontColor, Highlight`int
Language`int
IsHyperlinkbool
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ínhKiểuMô tả
FileName`strNone`
BytesbytesDữ liệu hình ảnh thô
Width, Height`floatNone`
AlternativeTextTitle`strNone`
AlternativeTextDescription`strNone`
HyperlinkUrl`strNone`
Tagslist[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ínhKiểuMô tả
FileName`strNone`
BytesbytesDữ liệu tệp thô
Tagslist[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ớpThuộc tính chính
TableColumns: list[TableColumn] (mỗi TableColumn.Width.LockedWidth), IsBordersVisible: bool, Tags: list[NoteTag]
TableRowDuyệt các ô qua GetChildNodes(TableCell)
TableCellChứ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ínhKiểuMô tả
Icon`intNone`
Label`strNone`
FontColor`intNone`
Highlight`intNone`
CreationTime`datetimeNone`
CompletedTime`datetimeNone`

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ínhKiểuMô tả
Format`strNone`
Restart`intNone`
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ọnKiểuMô tả
PageIndexintTrườ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`intNone`
ImageCompression`AnyNone`
JpegQuality`intNone`
PageSettings`AnyNone`
PageSplittingAlgorithm`AnyNone`
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ỉ đọcGhi 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ấtKhác SaveFormat các giá trị tăng UnsupportedSaveFormatException
Cần ReportLab cho PDFCà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ằng if x is not None hoặc if x trướ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 node khi bạn chỉ cần các con trực tiếp.
  • Xử lý mã hoá trên Windows: Trên Windows, sys.stdout có thể sử dụng một trang mã kế thừa. Thêm sys.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ập SaveFormat.Pdf chức năng mà không cài đặt trước pip 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.
 Tiếng Việt