Create or Load a Document

Almost any task that you want to perform with Aspose.Words involves loading a document. The Document class represents a document loaded into memory. The document has several overloaded constructors allowing you to create a blank document or to load it from a file or stream. The document can be loaded in any load format supported by Aspose.Words. For the list of all supported load formats, see the LoadFormat enumeration.

Create a New Document

We will call the Document constructor without parameters to create a new blank document. If you want to generate a document programmatically, the simplest way is to use the DocumentBuilder class to add document contents.

The following code example shows how to create a document using the document builder:

// 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");

Load a Document

To load an existing document in any of the LoadFormat formats, pass the file name or the stream into one of the Document constructors. The format of the loaded document is automatically determined by its extension.

Load from a File

Pass a file name as a string to the Document constructor to open an existing document from a file.

The following code example shows how to open a document from a file:

// 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);

You can download the template file of this example from Aspose.Words GitHub.

Load from a Stream

To open a document from a stream, simply pass a stream object that contains the document into the Document constructor.

The following code example shows how to open a document from a stream:

// 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();