Aspose.Words

Load or Create a Document

The Document class represents a document loaded into memory. Document has several overloaded constructors allowing you to create a blank document or to load it from a file or stream.

Creating a New Document

Call the Document.#ctor constructor without parameters to create a new blank document:

Example DocumentCtor

Shows how to create a blank document. Note the blank document contains one section and one paragraph.

[Java]

 

Document doc = new Document();

 

 

The document paper size is PaperSize.Letter by default.

If you want to generate a document programmatically, the most reasonable step after creation is to use DocumentBuilder to add document contents.

Example DocumentBuilderAndSave

Shows how to create build a document using a document builder.

[Java]

 

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);

 

builder.writeln("Hello World!");

 

doc.save(getMyDir() + "DocumentBuilderAndSave Out.docx");

 

 

Opening from a File

Pass a file name as a string to the Document.#ctor(String) constructor to open an existing document from a file:

Example OpenFromFile

Opens a document from a file.

[Java]

 

// Open a document. The file is opened read only and only for the duration of the constructor.

Document doc = new Document(getMyDir() + "Document.doc");

 

 

Opening from a Stream

Simply pass a stream object that contains a document to the Document.#ctor(Stream) constructor:

Example OpenFromStream

Opens a document from a stream.

[Java]

 

// Open the stream. Read only access is enough for Aspose.Words to load a document.

InputStream stream = new FileInputStream(getMyDir() + "Document.doc");

 

// Load the entire document into memory.

Document doc = new Document(stream);

 

// You can close the stream now, it is no longer needed because the document is in memory.

stream.close();

 

// ... do something with the document

 

 

Opening Encrypted Documents

You can open Word documents encrypted with a password. To do that, use the special constructor overload, which accepts a LoadOptions object. This object contains the LoadOptions.Password property which specifies the password string.

Example OpenEncrypted

Loads a Microsoft Word document encrypted with a password.

[Java]

 

Document doc = new Document(getMyDir() + "Document.LoadEncrypted.doc", new LoadOptions("qwerty"));