วิธีสร้างแบบ Light Document ใน Python
วิธีสร้างแบบ Light Document ใน Python
โมเดลเอกสารเบา (LDM) เป็นการแสดงตัวของ Python ของ FOSS Aspose.Words ของเอกสาร Word คู่มือนี้แสดงวิธีการอัตราบรรจุไฟล์ DOCX และแปลงมันเป็น PDF เป็น PDF. LDM โดยใช้ DocumentReader และของมัน to_light_document() วิธีการจาก LdmBuilderMixin.
Prerequisites
| Requirement | Detail |
|---|---|
| Python | 3.9 or later |
| Package | aspose-words-foss (มีใบอนุญาตจาก MIT) |
| Input | A การทําการ .docx แฟลิก |
pip install aspose-words-fossขั้นตอน 1 นําเข้า DocumentReader
from aspose.words_foss import DocumentReaderDocumentReader อนุญาตจาก LdmBuilderMixin, ซึ่งให้บริการที่ to_light_document() วิธีการ.
ขั้นตอน 2 อัตราการอัพโหลดไฟล์ DOCX
การใช้งาน load_file() สําหรับเส้นทางไฟล์, load_stream() สําหรับวัตถุแบบไฟล์ หรือ load_bytes() สําหรับไบต์ที่ไม่ถูกผลิต:
reader = DocumentReader()
reader.load_file("data/my_document.docx")ขั้นตอนที่ 3 สร้าง LDM
Call to_light_document() เพื่อแปลง DOCX ที่ถูกบรรจุเป็น LDM Document:
doc = reader.to_light_document()
print("Page count:", doc.page_count)
print("Sections:", len(doc.sections))
print("Paragraphs:", len(doc.all_paragraphs))ขั้นตอนที่ 4 ตรวจสอบเอกสาร
LDM Document เปิดเผยต้นเอกสารทั้งหมด. จุดเข้าที่ทั่วไป:
# Read full text
print(doc.text[:300])
# Iterate sections
for section in doc.sections:
print("Section paragraphs:", len(section.paragraphs))
# Find headings (up to H2)
for heading in doc.headings(max_level=2):
print("Heading:", heading.text)ขั้นตอน 5 เขียนกลับเป็น DOCX (เลือก)
หลังจากตรวจสอบหรือปรับเปลี่ยน LDM, ใช้ LdmDocxWriter เพื่อผลิตไฟล์ DOCX:
from aspose.words_foss import LdmDocxWriter
writer = LdmDocxWriter()
writer.write(doc, "output/result.docx")ขั้นตอนต่อไป
- การเขียนไฟล์ DOCX ด้วย LdmDocxWriter API การเขียนเต็ม
- การทํางานกับส่วนของเอกสาร การนําทางในส่วนและข้อความ