Guida per sviluppatori

Aspose.Note FOSS for Python is a free, open-source library for reading Microsoft OneNote .one file di sezione senza alcuna dipendenza da Microsoft Office. Fornisce un’API pubblica pulita sotto il aspose.note pacchetto, modellato sul Aspose.Note per l’interfaccia .NET. La libreria è adatta per l’automazione dei documenti, l’indicizzazione dei contenuti, le pipeline di estrazione dati e i flussi di lavoro di archiviazione.

Questa guida per sviluppatori copre l’intera superficie dell’API pubblica disponibile nella versione 26.3.1, con esempi di codice eseguibili per ogni funzionalità principale.

Caricamento del documento

Carica un .one file da un percorso o da un flusso binario. Il Document classe è il punto di ingresso per tutte le operazioni.

Carica da un percorso file

from aspose.note import Document

doc = Document("MyNotes.one")

Carica da un flusso binario

Utile quando si legge da storage cloud, risposte HTTP o buffer in memoria:

from pathlib import Path
from aspose.note import Document

with Path("MyNotes.one").open("rb") as f:
    doc = Document(f)

Opzioni di caricamento

Usa LoadOptions per impostare parametri opzionali al momento del caricamento:

from aspose.note import Document, LoadOptions

opts = LoadOptions()
opts.LoadHistory = True   # Include page history in the DOM
doc = Document("MyNotes.one", opts)

Nota: DocumentPassword esiste su LoadOptions per compatibilità API, ma i documenti crittografati non sono supportati. Tentare di caricare un file crittografato solleva IncorrectPasswordException.


Struttura del documento (DOM)

Il modello di documento OneNote è un albero:

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

Ogni nodo espone ParentNode e un Document proprietà che risale alla radice. I nodi compositi supportano l’iterazione dei figli, FirstChild, LastChild, AppendChildLast, InsertChild, RemoveChild, e GetChildNodes(Type).


Iterazione delle pagine

Pages sono i figli diretti di Document. Iterali direttamente o usa 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}]")

Metadati della pagina:

ProprietàTipoDescrizione
Title`TitleNone`
Author`strNone`
CreationTime`datetimeNone`
LastModifiedTime`datetimeNone`
Level`intNone`

Estrazione del testo

Estrai tutto il testo semplice

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))

Ispeziona le sequenze di formattazione

Ogni RichText contiene un elenco di TextRun segmenti. Ogni esecuzione porta il proprio 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)}]")

Estrai i collegamenti ipertestuali

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)

Estrazione delle immagini

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})")

Proprietà dell’immagine: FileName, Bytes, Width, Height, AlternativeTextTitle, AlternativeTextDescription, HyperlinkUrl, Tags.


Analisi delle tabelle

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)

File allegati

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}")

Tag e elenchi numerati

Ispeziona gli elementi 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}")

Ispeziona gli elenchi numerati

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}")

Pattern DocumentVisitor

Usa DocumentVisitor per implementare un visitatore che percorre l’intero albero del documento:

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}")

Esportazione PDF

L’esportazione PDF richiede la dipendenza opzionale ReportLab. Installala con:

pip install "aspose-note[pdf]"

Esportazione PDF di base

from aspose.note import Document, SaveFormat

doc = Document("MyNotes.one")
doc.Save("output.pdf", SaveFormat.Pdf)

Esportazione PDF con opzioni

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()

Nota: PdfSaveOptions.PageIndex e PageCount i campi esistono ma non vengono inoltrati all’esportatore PDF nella v26.3.1. L’intero documento viene sempre esportato.


Limitazioni attuali

AreaStato
Lettura .one fileCompletamente supportato
Esportazione PDF (via ReportLab)Supportato
Scrittura su .oneNon implementato
Documenti crittografatiNon supportato (solleva IncorrectPasswordException)
Formati di salvataggio HTML / immagine / ONEDichiarato per compatibilità API; solleva UnsupportedSaveFormatException

Guide disponibili


Vedi anche

 Italiano