การสร้างหรือโหลดเอกสาร

เกือบทุกงานที่คุณต้องการดำเนินการด้วยAspose.Wordsเกี่ยวข้องกับการโหลดเอกสาร คลาสDocumentแทนเอกสารที่โหลดลงในหน่วยความจำ เอกสารมีหลายตัวสร้างมากเกินไปช่วยให้คุณสามารถสร้างเอกสารที่ว่างเปล่าหรือการโ เอกสารสามารถโหลดในรูปแบบโหลดใดๆที่สนับสนุนโดยAspose.Words สำหรับรายการของรูปแบบการโหลดที่รองรับทั้งหมดโปรดดูที่การแจงนับLoadFormat.

สร้างเอกสารใหม่

เราจะเรียกตัวสร้างDocumentโดยไม่มีพารามิเตอร์ในการสร้างเอกสารที่ว่างเปล่าใหม่. ถ้าคุณต้องการสร้างเอกสารแบบโปรแกรมวิธีที่ง่ายที่สุดคือใช้คลาสDocumentBuilderเพื่อเพิ่มเนื้อหาของเ.

ตัวอย่างรหัสต่อไปนี้แสดงวิธีการสร้างเอกสารโดยใช้ตัวสร้างเอกสาร:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateDocument.class);
// Load the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("hello world");
doc.save(dataDir + "output.docx");

ป้อนเอกสาร

เมื่อต้องการโหลดเอกสารที่มีอยู่ในรูปแบบใดๆของLoadFormatให้ส่งชื่อไฟล์หรือสตรีมไปยังตัวสร้างเอ รูปแบบของเอกสารที่โหลดจะถูกกำหนดโดยอัตโนมัติโดยส่วนขยาย.

โหลดจากแฟ้ม

ผ่านชื่อแฟ้มเป็นสตริงไปยังตัวสร้างเอกสารเพื่อเปิดเอกสารที่มีอยู่จากแฟ้ม.

ตัวอย่างรหัสต่อไปนี้แสดงวิธีการเปิดเอกสารจากแฟ้ม:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// For complete examples and data files, please go to
// https://github.com/aspose-words/Aspose.Words-for-Java
String fileName = "Document.docx";
// Load the document from the absolute path on disk.
Document doc = new Document(dataDir + fileName);

คุณสามารถดาวน์โหลดไฟล์แม่แบบของตัวอย่างนี้ได้จาก Aspose.Words GitHub.

โหลดจากสตรีม

เมื่อต้องการเปิดเอกสารจากสตรีมเพียงผ่านวัตถุสตรีมที่ประกอบด้วยเอกสารลงในตัวสร้.

ตัวอย่างรหัสต่อไปนี้แสดงวิธีการเปิดเอกสารจากสตรีม:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// For complete examples and data files, please go to
// https://github.com/aspose-words/Aspose.Words-for-Java
String filename = "Document.docx";
// Open the stream. Read only access is enough for Aspose.Words to load a
// document.
InputStream in = new FileInputStream(dataDir + filename);
// Load the entire document into memory.
Document doc = new Document(in);
System.out.println("Document opened. Total pages are " + doc.getPageCount());
// You can close the stream now, it is no longer needed because the document is
// in memory.
in.close();