文檔半島外圍網上直營>>Aspose.Words開發者指南>>Java版Word開發工具Aspose.Words基礎教程:創建或加載文檔
Java版Word開發工具Aspose.Words基礎教程:創建或加載文檔
Aspose.Words for Java是功能豐富的文字處理API,開發人員可以在自己的Java應用程序中嵌入生成,修改,轉換,呈現和打印Microsoft Word支持的所有格式的功能。它不依賴于Microsoft Word,但是它提供了Microsoft Word通過其API支持的功能。
>>Aspose.Words for Java已經更新至v20.7,有97項改進和修復,點擊下載體驗
創建一個新文件
我們將調用 不帶參數的 Document構造函數來創建一個新的空白文檔。如果要以編程方式生成文檔,最簡單的方法是使用 DocumentBuilder 類添加文檔內容。以下代碼示例顯示了如何使用文檔構建器創建文檔:
// 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");
注意默認值:
- 一個空白文檔包含一個帶有默認參數的部分,一個空段落和一些文檔樣式。實際上,此文檔與在Microsoft Word中創建“新文檔”的結果相同。
- 文檔紙張尺寸為PaperSize.Letter
載入文件——從文件加載
要以任何LoadFormat 格式加載現有文檔 ,請將文件名或流傳遞到其中一個Document構造函數中。加載文檔的格式由其擴展名自動確定。
將文件名作為字符串傳遞給Document構造函數以從文件中打開現有文檔。下面的代碼示例演示如何從文件中打開文檔:
String fileName = "Document.docx"; // Load the document from the absolute path on disk. Document doc = new Document(dataDir + fileName);
載入文件——從流加載
要從流中打開文檔,只需將包含文檔的流對象傳遞到Document構造函數中。下面的代碼示例演示如何從流中打開文檔:
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();
還想要更多嗎?您可以點擊閱讀【2020 · Aspose最新資源整合】,查找需要的教程資源。如果您有任何疑問或需求,請隨時加入Aspose技術交流群(642018183),我們很高興為您提供查詢和咨詢。