How to Write Headings and Text in Java
Aspose.Words FOSS for Java writes Word documents from code. This guide uses the DocumentBuilder class to write a heading and a paragraph into a new document and save it as a DOCX file, with the library from Maven Central. The example then also opens an existing file, Report.docx, and saves it as Markdown.
Step-by-Step Guide
Step 1: Install the Package
Add the package to your build. The library needs Java 8 or later.
<dependency>
<groupId>org.aspose</groupId>
<artifactId>aspose-words-foss</artifactId>
<version>26.3.0</version>
</dependency>Step 2: Import the Classes
All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.
Step 3: Write the Heading and the Paragraph
DocumentBuilder keeps a cursor in the document. writeln inserts a string and a paragraph break. The style comes from getParagraphFormat().setStyleIdentifier(...), using a StyleIdentifier value. The last two statements of the example open an existing file, Report.docx, and save it with a Markdown file name.
import com.aspose.words.*;
// Create a document from scratch.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.writeln("Hello from Aspose.Words FOSS!");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.BODY_TEXT);
builder.writeln("This document was created entirely in code, no Word installed.");
doc.save("Hello.docx");
// Convert an existing document to Markdown.
Document report = new Document("Report.docx");
report.save("Report.md");Common Issues and Fixes
The compiler reports cannot find symbol for StyleIdentifier. The com.aspose.words package is not imported. Add import com.aspose.words.*;.
The last statements throw a FileNotFoundException. They open Report.docx, which must exist in the directory the program runs in. The message reads “Can’t find file” followed by the name.
The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.
Frequently Asked Questions
What is the difference between write and writeln?
write inserts a string at the current position. writeln inserts a string and a paragraph break.
How do I make a line a heading?
Set StyleIdentifier.HEADING_1 on the paragraph format before writing the line.
Where is the file saved?
In files named Hello.docx and Report.md in the current working directory.