개발자 가이드
Aspose.Note FOSS for Python is a free, open-source library for reading Microsoft OneNote .one Microsoft Office에 대한 의존성 없이 섹션 파일을 처리합니다. 깨끗한 공개 API를 제공하며 aspose.note 패키지는 Aspose.Note for .NET 인터페이스를 모델로 합니다. 이 라이브러리는 문서 자동화, 콘텐츠 인덱싱, 데이터 추출 파이프라인 및 보관 워크플로에 적합합니다.
이 개발자 가이드는 버전 26.3.1에서 제공되는 전체 공개 API 범위를 다루며, 주요 기능마다 실행 가능한 코드 예제를 포함합니다.
문서 로드
로드 .one 파일 경로 또는 바이너리 스트림에서 파일을 로드합니다. 해당 Document 클래스는 모든 작업의 진입점입니다.
파일 경로에서 로드
from aspose.note import Document
doc = Document("MyNotes.one")바이너리 스트림에서 로드
클라우드 스토리지, HTTP 응답, 또는 메모리 버퍼에서 읽을 때 유용합니다:
from pathlib import Path
from aspose.note import Document
with Path("MyNotes.one").open("rb") as f:
doc = Document(f)로드 옵션
사용 LoadOptions 로드 시 선택적 매개변수를 설정합니다:
from aspose.note import Document, LoadOptions
opts = LoadOptions()
opts.LoadHistory = True # Include page history in the DOM
doc = Document("MyNotes.one", opts)참고: DocumentPassword 에 존재합니다 LoadOptions API 호환성을 위해 제공되지만, 암호화된 문서는 지원되지 않습니다. 암호화된 파일을 로드하려고 하면 예외가 발생합니다 IncorrectPasswordException.
문서 구조 (DOM)
OneNote 문서 모델은 트리 구조입니다:
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각 노드는 다음을 노출합니다 ParentNode 및 Document 루트까지 올라가는 속성. 복합 노드는 자식 반복을 지원합니다, FirstChild, LastChild, AppendChildLast, InsertChild, RemoveChild, 그리고 GetChildNodes(Type).
페이지 반복
페이지는 다음의 직접 자식입니다 Document. 이를 직접 반복하거나 사용합니다 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}]")페이지 메타데이터:
| 속성 | 유형 | 설명 |
|---|---|---|
Title | `Title | None` |
Author | `str | None` |
CreationTime | `datetime | None` |
LastModifiedTime | `datetime | None` |
Level | `int | None` |
텍스트 추출
전체 일반 텍스트 추출
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))서식 실행 검사
각각 RichText 목록을 포함합니다 TextRun 세그먼트. 각 실행은 자체적인 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)}]")하이퍼링크 추출
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)이미지 추출
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})")이미지 속성: FileName, Bytes, Width, Height, AlternativeTextTitle, AlternativeTextDescription, HyperlinkUrl, Tags.
표 파싱
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)첨부 파일
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}")태그 및 번호 매기기 목록
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}")번호 매기기 목록 검사
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}")DocumentVisitor 패턴
사용 DocumentVisitor 전체 문서 트리를 순회하는 방문자를 구현하려면:
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}")PDF 내보내기
PDF 내보내기에는 선택적 ReportLab 종속성이 필요합니다. 다음 명령으로 설치하십시오:
pip install "aspose-note[pdf]"기본 PDF 내보내기
from aspose.note import Document, SaveFormat
doc = Document("MyNotes.one")
doc.Save("output.pdf", SaveFormat.Pdf)옵션이 있는 PDF 내보내기
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()참고: PdfSaveOptions.PageIndex 및 PageCount 필드가 존재하지만 v26.3.1에서는 PDF 내보내기로 전달되지 않습니다. 전체 문서는 항상 내보내집니다.
현재 제한 사항
| 영역 | 상태 |
|---|---|
읽기 .one 파일 | 완전 지원 |
| PDF 내보내기 (ReportLab을 통해) | 지원 |
다시 쓰기 .one | 구현되지 않음 |
| 암호화된 문서 | 지원되지 않음 (예외 발생 IncorrectPasswordException) |
| HTML / 이미지 / ONE 저장 형식 | API 호환성을 위해 선언됨; 예외 발생 UnsupportedSaveFormatException |