기능 개요 — 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-notePDF 내보내기 지원을 위해 (ReportLab 필요):
pip install "aspose-note[pdf]"요구 사항: Python 3.10 이상. Microsoft Office 설치가 필요하지 않습니다.
기능 및 역량
.one 파일 로드
파일 경로나 모든 바이너리 스트림(파일 핸들, io.BytesIO, HTTP 응답 본문, 클라우드 스토리지 스트림).
Document.FileFormatOneNote 파일 형식 버전(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,FileFormatPage: 직접적인 자식Document; 노출합니다Title,Author,CreationTime,LastModifiedTime,LevelTitle: 노출합니다TitleText,TitleDate,TitleTime(전체RichText노드)Outline: 위치 컨테이너, 포함HorizontalOffset,VerticalOffset,MaxWidth,MaxHeight,MinWidth,ReservedWidth,IndentPositionOutlineElement: 리프 컨테이너; 노출합니다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 노드가 노출하는:
Text: str: 전체 일반 텍스트 문자열TextRuns: list[TextRun]: 형식화된 세그먼트 목록Tags: list[NoteTag]: 이 블록에 연결된 OneNote 태그Append(text, style=None): 메모리 내에서 텍스트 런 추가Replace(old_value, new_value): 메모리 내 문자열 치환
각 TextRun 다음과 같이 포함한다:
| 속성 | 유형 | 설명 |
|---|---|---|
Text | str | 세그먼트 텍스트 |
Style | TextStyle | 서식 메타데이터 |
TextStyle 속성:
| 속성 | 유형 |
|---|---|
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}")이미지 추출
Image 노드는 모든 포함된 이미지에 대한 원시 바이트와 메타데이터를 노출합니다:
| 속성 | 유형 | 설명 |
|---|---|---|
FileName | `str | None` |
Bytes | bytes | 원시 이미지 데이터 |
Width, Height | `float | None` |
AlternativeTextTitle | `str | None` |
AlternativeTextDescription | `str | None` |
HyperlinkUrl | `str | None` |
Tags | list[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 | `str | None` |
Bytes | bytes | 원시 파일 데이터 |
Tags | list[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 전체 테이블 구조를 노출합니다:
| 클래스 | 주요 속성 |
|---|---|
Table | Columns: list[TableColumn] (각 TableColumn 은(는) .Width 및 .LockedWidth), IsBordersVisible: bool, Tags: list[NoteTag] |
TableRow | 셀을 반복합니다 via 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 노드 via their .Tags 속성. OutlineElement 은(는) .Tags 속성. NoteTag 속성:
| 속성 | 유형 | 설명 |
|---|---|---|
Icon | `int | None` |
Label | `str | None` |
FontColor | `int | None` |
Highlight | `int | None` |
CreationTime | `datetime | None` |
CompletedTime | `datetime | None` |
팩토리 메서드: 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 | `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}")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
| 옵션 | 유형 | 설명 |
|---|---|---|
PageIndex | int | 필드가 존재합니다; v26.3.1에서 PDF 내보내기로 전달되지 않음 (효과 없음) |
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()포맷 및 열거형 참조
SaveFormat
| 값 | 상태 |
|---|---|
SaveFormat.Pdf | 구현됨 (ReportLab 필요) |
FileFormat
Document.FileFormat OneNote 파일 형식 버전을 최선으로 추정하여 표시합니다. 열거형은 세 가지 값을 선언합니다:
| 값 | 설명 |
|---|---|
FileFormat.OneNote2010 | OneNote 2010 형식 |
FileFormat.OneNoteOnline | OneNote Online 형식 |
FileFormat.OneNote2007 | 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
현재 제한 사항
| 제한 | 세부 정보 |
|---|---|
| 읽기 전용 | 다시 쓰기 대상 .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 저장 시 런타임에 import 오류가 발생합니다.