機能概要 — Aspose.Note FOSS for Python

Aspose.Note FOSS for Python (package aspose-note, version 26.3.1) は Microsoft OneNote のセクションファイルを読み取るための Python API を提供します .one セクションファイルを PDF にエクスポートします。以下に列挙されたすべての機能は、リポジトリのソースコード、README、サンプルスクリプトと照らし合わせて検証されています。.

インストールとセットアップ

PyPI からインストール:

pip install aspose-note

PDF エクスポートをサポートするには(ReportLab が必要です):

pip install "aspose-note[pdf]"

要件: Python 3.10 以降。Microsoft Office のインストールは不要です。.


機能と能力

.one ファイルのロード

Microsoft OneNote のセクションファイルをファイルパスまたは任意のバイナリストリーム(ファイルハンドル、, 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)

Document DOM のトラバーサル

完全な OneNote ドキュメントは型付けされた Python オブジェクトのツリーとして公開されます。すべてのノードは以下から継承します Node または CompositeNode:

  • Document::ルート;公開する DisplayName, CreationTime, FileFormat
  • Page::の直接子 Document;;公開する Title, Author, CreationTime, LastModifiedTime, Level
  • Title: 公開 TitleText, TitleDate, TitleTime (すべて RichText ノード)
  • Outline: 位置コンテナ HorizontalOffset, VerticalOffset, MaxWidth, MaxHeight, MinWidth, ReservedWidth, IndentPosition
  • OutlineElement: リーフコンテナ; 公開 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 nodes expose:

  • Text: str: 完全なプレーンテキスト文字列
  • TextRuns: list[TextRun]: フォーマット済みセグメントのリスト
  • Tags: list[NoteTag]: このブロックに付随する OneNote タグ
  • Append(text, style=None): メモリ内でテキストランを追加
  • Replace(old_value, new_value): メモリ内文字列置換

TextRun 含む:

プロパティタイプ説明
Textstrセグメントテキスト
StyleTextStyleフォーマットメタデータ

TextStyle プロパティ:

プロパティタイプ
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}")

画像抽出

Image ノードはすべての埋め込み画像の生バイトとメタデータを公開します:

プロパティタイプ説明
FileName`strNone`
Bytesbytes生画像データ
Width, Height`floatNone`
AlternativeTextTitle`strNone`
AlternativeTextDescription`strNone`
HyperlinkUrl`strNone`
Tagslist[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`strNone`
Bytesbytes生ファイルデータ
Tagslist[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 テーブル全体の構造を公開する:

クラスキー プロパティ
TableColumns: 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`intNone`
Label`strNone`
FontColor`intNone`
Highlight`intNone`
CreationTime`datetimeNone`
CompletedTime`datetimeNone`

ファクトリーメソッド: 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`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}")

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

オプションタイプ説明
PageIndexintフィールドが存在します; v26.3.1 では PDF エクスポーターに転送されません (効果なし)
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()

フォーマットと列挙体のリファレンス

SaveFormat

ステータス
SaveFormat.Pdf実装済み(ReportLab が必要)

FileFormat

Document.FileFormat OneNote ファイル形式バージョンのベストエフォートな指標を提供します。この列挙型は 3 つの値を宣言しています::

説明
FileFormat.OneNote2010OneNote 2010 形式
FileFormat.OneNoteOnlineOneNote Online 形式
FileFormat.OneNote2007OneNote 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
PDFにはReportLabが必要ですインストール 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 に保存すると実行時にインポートエラーが発生します。.
 日本語