LdmDocxWriter를 사용한 DOCX 파일 쓰기
LdmDocxWriter을(를) 사용하여 DOCX 파일 작성
LdmDocxWriter은(는) light_document_model.Document (LDM) 객체를 DOCX 파일로 변환합니다. 이는 DOCX 파일을 읽어 LDM 트리로 노출하는 DocumentReader의 쓰기 대응 기능입니다. 이 둘이 함께 라운드트립 파이프라인을 형성합니다: DocumentReader 입력, LdmDocxWriter 출력.
전제 조건
| 요구 사항 | 세부 사항 |
|---|---|
| Python | 3.9 이상 |
| Package | aspose-words-foss (MIT 라이선스) |
| Input | 하나의 light_document_model.Document 인스턴스 |
pip install aspose-words-foss파일 경로에 쓰기
LdmDocxWriter.write(doc, output_path)은(는) 지정된 경로에 LDM 문서를 DOCX 파일로 직렬화합니다. 경로의 상위 디렉터리가 존재하지 않으면 호출 시 FileNotFoundError이(가) 발생합니다.
from aspose.words_foss import DocumentReader, LdmDocxWriter
# Load a DOCX and obtain its LDM representation
reader = DocumentReader()
reader.load_file("input/original.docx")
ldm_doc = reader.to_light_document()
# Write the LDM document back to a DOCX file
writer = LdmDocxWriter()
writer.write(ldm_doc, "output/result.docx")
print("Written to output/result.docx")바이트에 쓰기 (메모리 내 출력)
LdmDocxWriter.write_to_bytes(doc)은 DOCX 콘텐츠를 bytes 객체로 반환합니다. 파일을 네트워크로 전송하거나 데이터베이스에 저장하거나 파일 시스템에 쓰는 것을 완전히 피해야 할 때 사용하십시오.
from aspose.words_foss import DocumentReader, LdmDocxWriter
reader = DocumentReader()
reader.load_file("input/report.docx")
ldm_doc = reader.to_light_document()
writer = LdmDocxWriter()
docx_bytes = writer.write_to_bytes(ldm_doc)
print(f"DOCX bytes: {len(docx_bytes)}")
# Save manually if desired
with open("output/report_copy.docx", "wb") as f:
f.write(docx_bytes)라운드 트립 패턴
가장 일반적인 사용 사례는 읽기-수정-쓰기 라운드 트립입니다:
from aspose.words_foss import DocumentReader, LdmDocxWriter
reader = DocumentReader()
reader.load_file("input/template.docx")
ldm_doc = reader.to_light_document()
# Inspect or modify the LDM here
print("Sections:", len(ldm_doc.sections))
print("Paragraphs:", len(ldm_doc.all_paragraphs))
writer = LdmDocxWriter()
writer.write(ldm_doc, "output/modified.docx")손실 쓰기 경고
LdmDocxWriter이 DOCX 형식에서 LDM 구성을 충실히 표현할 수 없을 때 DocxWriterLossyWarning을 발생시킵니다. Python의 warnings 모듈을 사용하여 이러한 항목을 캡처하고 어떤 내용이 누락되었는지 감사할 수 있습니다:
import warnings
from aspose.words_foss import DocumentReader, LdmDocxWriter, DocxWriterLossyWarning
reader = DocumentReader()
reader.load_file("input/complex.docx")
ldm_doc = reader.to_light_document()
writer = LdmDocxWriter()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", DocxWriterLossyWarning)
writer.write(ldm_doc, "output/complex_out.docx")
for warning in w:
print("Lossy:", warning.message)팁 및 모범 사례
- 문서를
LdmDocxWriter에 전달하기 전에 항상DocumentReader.to_light_document()을 호출하십시오 — 작성자는 원시DocumentReader가 아니라 LDMDocument를 기대합니다. - 임시 파일 관리를 피하기 위해 웹 핸들러에서
write_to_bytes()을 사용하십시오. - 라이브러리를 업그레이드할 때 라운드트립 회귀를 감지하기 위해 테스트에서
DocxWriterLossyWarning를 확인하십시오. LdmDocxWriter.options는 라이터 수준 구성에 사용할 수 있습니다; 인스턴스화 후 객체를 검사하여 사용 가능한 설정을 확인하십시오.
공통 문제
| 문제 | 원인 | 수정 |
|---|---|---|
FileNotFoundError write()에 | 상위 디렉터리가 존재하지 않습니다 | write()을 호출하기 전에 Path.mkdir(parents=True, exist_ok=True)을 사용하여 출력 디렉터리를 생성하십시오 |
DocxWriterLossyWarning 생성됨 | DOCX에서 LDM 구성 요소를 표현할 수 없습니다 | 경고 메시지를 검토하십시오; 손실을 수용하거나 쓰기 전에 LDM을 조정하십시오 |
| 빈 출력 DOCX | LDM 문서에 섹션이나 단락이 없습니다 | 로드 후 ldm_doc.sections와 ldm_doc.all_paragraphs가 비어 있지 않은지 확인하십시오 |
FAQ
LDM (light_document_model)이란 무엇입니까?
LDM은 Aspose.Words FOSS의 추상화된, Python 네이티브 Word 문서 표현입니다. 이는 문서 로직을 DOCX 바이너리 형식에서 분리하여 프로그래밍 방식으로 문서 구조를 검사하고 조작하기 쉽게 만듭니다.
DOCX 대신 PDF로 쓸 수 있나요?
예 — 같은 패키지의 LdmPdfWriter.write(doc, output_path)를 PDF 출력에 사용하거나, Markdown에는 LdmMarkdownWriter.write(doc, output_path)를 사용하십시오.
write_to_bytes()은 출력 경로가 필요합니까?
아니요. write_to_bytes(doc)은 LDM 문서만 받아들이며 파일 시스템과의 상호작용 없이 bytes 객체를 반환합니다.
API Reference 요약
| 클래스 / 메서드 | 설명 |
|---|---|
LdmDocxWriter | LDM Document를 DOCX 파일로 변환합니다 |
LdmDocxWriter.write(doc, output_path) | DOCX를 지정된 파일 경로에 씁니다 |
LdmDocxWriter.write_to_bytes(doc) | DOCX 내용을 bytes로 반환합니다 |
LdmDocxWriter.options | 작성기 구성 옵션 |
DocxWriterLossyWarning | 쓰기 중 LDM 구성이 누락될 때 발생하는 경고 |
DocumentReader | DOCX 파일을 읽고 LDM 표현을 구축합니다 |
DocumentReader.to_light_document() | 로드된 문서를 LDM Document으로 반환합니다 |