Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (143).NET Core  (23)Angular  (39)ASP.NET  (47)ASP.NET Core  (53)ASP.NET MVC  (83)Azure  (26)Blazor  (47)DocIO  (18)Essential JS 2  (64)Essential Studio  (159)Flutter  (52)JavaScript  (134)Microsoft  (96)PDF  (48)React  (29)Succinctly series  (118)Syncfusion  (399)TypeScript  (30)Uno Platform  (2)UWP  (4)Vue  (25)Webinar  (14)Windows Forms  (52)WPF  (92)Xamarin  (105)XlsIO  (20)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (99)Chart  (40)Cloud  (8)Company  (445)Dashboard  (4)Data Science  (3)Data Validation  (2)DataGrid  (31)Development  (233)Doc  (7)eBook  (89)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (13)Extensions  (7)File Manager  (3)Gantt  (6)Gauge  (4)Git  (3)Grid  (24)HTML  (8)Installer  (1)Knockout  (2)LINQPad  (1)Linux  (1)M-Commerce  (1)Metro Studio  (11)Mobile  (139)Mobile MVC  (9)OLAP server  (1)Orubase  (12)Partners  (20)PDF viewer  (15)Performance  (2)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (5)Road Map  (9)Scheduler  (15)SfDataGrid  (7)Silverlight  (21)Sneak Peek  (12)Solution Services  (2)Spreadsheet  (2)SQL  (4)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (9)Tips and Tricks  (15)UI  (62)Uncategorized  (68)Unix  (2)User interface  (48)Visual State Manager  (1)Visual Studio  (12)Visual Studio Code  (7)Web  (96)What's new  (61)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Introducing the New Java Word Processing Library

Introducing the New Java Word Processing Library

We are excited to unveil our very first Java component to the Java developer community. It’s Java Word Library in our 2020 Volume 3 release.

In this article, I’ll show you how to create, edit, and convert document formats like DOCX, DOCM, DOTX, WordML, HTML, TXT in Java applications using Syncfusion’s Java Word Library (Essential DocIO). This library doesn’t require Microsoft Word or Office interop dependencies.

This new library comes with the following features:

  • Create Word documents from scratch.
  • Create or edit Word documents and convert them to most commonly used file formats such as HTML or TXT and vice versa.
  • Create reports by performing simple, group, and nested mail merge.
  • Insert bookmarks and navigate to corresponding bookmarks to insert, replace, and delete contents.
  • Insert and edit legacy form fields.
  • Create functional forms with content controls like plain text, rich text, pictures, check boxes, combo boxes, drop-down lists, and a date picker.
  • Merge multiple documents into a single document with several formatting options like using destination styles and keeping source formatting.
  • Split a document into multiple small documents based on sections, placeholder text, or any other document element.
  • Preserve, accept, and reject changes that are tracked within a Word document.
  • Customize the appearance of the text with several text-level formatting options: font family, size, style, underline, strikethrough, text color, highlight, subscript, superscript, and so on.
  • Customize the appearance of a paragraph with several paragraph-level formatting options: indents, alignment, spacing, tab stops, text direction, and more.
  • Organize items or create an outline of a document with bullets and numbers ranging from single-level to multilevel lists.
  • Create and apply styles to ensure consistency within a document.
  • Create or edit documents with text in any supported language. Use left-to-right or right-to-left text.
  • Create a link in a document for quick access to webpages, files, email, or bookmarks.
  • Insert images in a document with all the common layout options like text wrap, position, and size. Use all common image formats like PNG, BMP, JPEG, TIFF, GIF, EMF, WMF, and SVG.
  • Insert tables to organize your information in rows and columns. Customize the look and feel of tables using built-in and custom table styles.
  • Create and insert comments in a document to add notes while reviewing. Also, edit and remove an existing comment in a document.
  • Create and manipulate text boxes, shapes, and group shapes in DOCX and WordML format documents.
  • Add information like title, author, branding, and the page number to a header or footer to repeat it at the top and bottom of every page. Create all header and footer types, such as a different first page and different odd and even pages.
  • Design the layout of document pages using page size, margins, orientation, borders, background, and more.
  • Organize the document contents with sections for grouping contents and making the contents start on a new page, odd page, even page, or continue in the same page.
  • Read and write built-in and custom document properties.

Create a new Word document using the Eclipse IDE

You can create a new Word document with all common document elements like text, images, hyperlinks, tables, bookmarks, comments, various types of fields, and content control in Java using the Syncfusion Word Library.

Step 1 : File > New > Java Project. The New Java Project wizard dialog appears, letting you specify the configuration of the project.
Create a new Java project

Step 2: Add external .jar files (“syncfusion-docio.jar” , “syncfusion-javahelper.jar“) to your project. Refer to the External Jars Required page to get dependent .jar files.
Add external .jar files ("syncfusion-docio.jar" , "syncfusion-javahelper.jar") to your projectStep 3: Include the following namespaces in the HelloWorld.java file.

Java
import java.io.File;
import java.io.FileInputStream;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.*;
import com.syncfusion.javahelper.system.drawing.*;

Step 4: Add the following code in the main method to create a Word document programmatically in Java.

//Create a new document.
WordDocument document = new WordDocument();
//Add a new section to the document.
WSection section = (WSection) document.addSection();
//Set margins of the section.
section.getPageSetup().getMargins().setAll((float) 72);
//Set page size of the section.
section.getPageSetup().setPageSize(new SizeFSupport(612, 792));
//Create paragraph styles.
WParagraphStyle style = createParagraphStyle(document);
//Create paragraph and apply formatting.
createParagraph(section);
//Create table and apply formatting.
createTable(section);
//Save and close the document.
document.save("GettingStarted.docx");
document.close();
System.out.println("Word document generated successfully.");

Adding text and images to the Word document

The following code example explains how to add paragraphs with text and images to a Word document.

/**
 *
 * Create paragraph and apply formatting.
 * 
 * @param section represents the section of a Word document.
 */
static IWParagraph createParagraph(WSection section) throws Exception 
{
    IWParagraph paragraph = section.getHeadersFooters().getHeader().addParagraph();
    //Append picture to the paragraph.
    WPicture picture = (WPicture) paragraph.appendPicture(new FileInputStream(getDataDir("AdventureCycle.jpg")));
    picture.setTextWrappingStyle(TextWrappingStyle.InFrontOfText);
    picture.setVerticalOrigin(VerticalOrigin.Margin);
    picture.setVerticalPosition((float) -45);
    picture.setHorizontalOrigin(HorizontalOrigin.Column);
    picture.setHorizontalPosition(263.5f);
    picture.setWidthScale((float) 20);
    picture.setHeightScale((float) 15);
    paragraph.applyStyle("Normal");
    paragraph.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);
    //Add text to the paragraph.
    WTextRange textRange = (WTextRange) paragraph.appendText("Adventure Works Cycles");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Calibri");
    textRange.getCharacterFormat().setTextColor((ColorSupport.getRed()).clone());

    //Append paragraph.
    paragraph = section.addParagraph();
    paragraph.applyStyle("Heading 1");
    paragraph.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Center);

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Adventure Works Cycles");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 18f, "Calibri");

    //Append paragraph.
    paragraph = section.addParagraph();
    paragraph.getParagraphFormat().setFirstLineIndent((float) 36);
    paragraph.getBreakCharacterFormat().setFontSize(12f);

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Adventure Works Cycles, the fictitious company on which the Adventure Works sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.");
    textRange.getCharacterFormat().setFontSize(12f);

    //Append paragraph.
    paragraph = section.addParagraph();
    paragraph.getParagraphFormat().setFirstLineIndent((float) 36);
    paragraph.getBreakCharacterFormat().setFontSize(12f);

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.");
    textRange.getCharacterFormat().setFontSize(12f);

    //Append paragraph.
    paragraph = section.addParagraph();
    paragraph.applyStyle("Heading 1");
    paragraph.getParagraphFormat().setHorizontalAlignment(HorizontalAlignment.Left);

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Product Overview");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 16f, "Calibri");
    return paragraph;
}

Adding tables to the Word document

Tables are another important element in documents that contain a set of data arranged in rows and columns. You can create simple or complex tables using the Java Word Library.

The following code example creates a simple table in the Word document and adds content to each cell.

/**
* Creates table and apply formatting.
* 
* @param section rRepresents the section of a Word document.
*/
static IWTable createTable(WSection section) throws Exception 
{
    //Append table.
    IWTable table = section.addTable();
    table.resetCells(3, 2);
    table.getTableFormat().getBorders().setBorderType(BorderStyle.None);
    table.getTableFormat().setIsAutoResized(true);

    //Append paragraph.
    IWParagraph paragraph = table.get(0, 0).addParagraph();
    paragraph.getParagraphFormat().setAfterSpacing((float) 0);
    paragraph.getBreakCharacterFormat().setFontSize(12f);

    //Append picture to paragraph.
    IWPicture picture = (WPicture) paragraph.appendPicture(new FileInputStream(getDataDir("Mountain-200.jpg")));
    picture.setTextWrappingStyle(TextWrappingStyle.TopAndBottom);
    picture.setVerticalOrigin(VerticalOrigin.Paragraph);
    picture.setVerticalPosition(4.5f);
    picture.setHorizontalOrigin(HorizontalOrigin.Column);
    picture.setHorizontalPosition(-2.15f);
    picture.setWidthScale((float) 79);
    picture.setHeightScale((float) 79);

    //Append paragraph.
    paragraph = table.get(0, 1).addParagraph();
    paragraph.applyStyle("Heading 1");
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    paragraph.appendText("Mountain-200");

    //Append paragraph.
    paragraph = table.get(0, 1).addParagraph();
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    appendCharacterFormatToText(paragraph.getBreakCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    WTextRange textRange = (WTextRange) paragraph.appendText("Product No: BK-M68B-38\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Size: 38\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Weight: 25\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Price: $2,294.99\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Append paragraph.
    paragraph = table.get(0, 1).addParagraph();
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    paragraph.getBreakCharacterFormat().setFontSize(12f);

    //Append paragraph.
    paragraph = table.get(1, 0).addParagraph();
    paragraph.applyStyle("Heading 1");
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    paragraph.appendText("Mountain-300 ");

    //Append paragraph.
    paragraph = table.get(1, 0).addParagraph();
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    appendCharacterFormatToText(paragraph.getBreakCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Product No: BK-M47B-38\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Size: 35\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Weight: 22\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Price: $1,079.99\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Append paragraph.
    paragraph = table.get(1, 0).addParagraph();
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    paragraph.getBreakCharacterFormat().setFontSize(12f);

    //Append paragraph.
    paragraph = table.get(1, 1).addParagraph();
    paragraph.applyStyle("Heading 1");
    paragraph.getParagraphFormat().setLineSpacing(12f);

    //Append picture to the paragraph.
    picture = (WPicture) paragraph.appendPicture(new FileInputStream(getDataDir("Mountain-300.jpg")));
    picture.setTextWrappingStyle(TextWrappingStyle.TopAndBottom);
    picture.setVerticalOrigin(VerticalOrigin.Paragraph);
    picture.setVerticalPosition(8.2f);
    picture.setHorizontalOrigin(HorizontalOrigin.Column);
    picture.setHorizontalPosition(-14.95f);
    picture.setWidthScale((float) 75);
    picture.setHeightScale((float) 75);

    //Append paragraph.
    paragraph = table.get(2, 0).addParagraph();
    paragraph.applyStyle("Heading 1");
    paragraph.getParagraphFormat().setLineSpacing(12f);

    //Append picture to the paragraph.
    picture = (WPicture) paragraph.appendPicture(new FileInputStream(getDataDir("Road-550-W.jpg")));
    picture.setTextWrappingStyle(TextWrappingStyle.TopAndBottom);
    picture.setVerticalOrigin(VerticalOrigin.Paragraph);
    picture.setVerticalPosition(3.75f);
    picture.setHorizontalOrigin(HorizontalOrigin.Column);
    picture.setHorizontalPosition(-5f);
    picture.setWidthScale((float) 92);
    picture.setHeightScale((float) 92);

    //Append paragraph.
    paragraph = table.get(2, 1).addParagraph();
    paragraph.applyStyle("Heading 1");
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    paragraph.appendText("Road-150 ");

    //Append paragraph.
    paragraph = table.get(2, 1).addParagraph();
    appendParagraphFormatToParagraph(paragraph.getParagraphFormat(), (float) 0, 12f);
    appendCharacterFormatToText(paragraph.getBreakCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Product No: BK-R93R-44\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Size: 44\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Weight: 14\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Add text to the paragraph.
    textRange = (WTextRange) paragraph.appendText("Price: $3,578.27\r");
    appendCharacterFormatToText(textRange.getCharacterFormat(), 12f, "Times New Roman");

    //Append paragraph.
    paragraph = table.get(2, 1).addParagraph();
    paragraph.applyStyle("Heading 1");
    paragraph.getParagraphFormat().setLineSpacing(12f);
    section.addParagraph();
    return table;
}

Styling the paragraph

The following code example explains how to create a paragraph style and apply formatting.

/**
* Create paragraph and apply formatting.
* 
* @param document represents the Word document.
*/
static WParagraphStyle createParagraphStyle(WordDocument document) throws Exception 
{
    //Apply the styles.
    WParagraphStyle style = (WParagraphStyle) document.addParagraphStyle("Normal");
    WCharacterFormat characterFormat = style.getCharacterFormat();
    WParagraphFormat paragraphFormat = style.getParagraphFormat();
    appendCharacterFormatToText(style.getCharacterFormat(), 11f, "Calibri");
    paragraphFormat.setBeforeSpacing((float) 0);
    paragraphFormat.setAfterSpacing((float) 8);
    paragraphFormat.setLineSpacing(13.8f);
    style = (WParagraphStyle) document.addParagraphStyle("Heading 1");
    characterFormat = style.getCharacterFormat();
    paragraphFormat = style.getParagraphFormat();
    style.applyBaseStyle("Normal");
    appendCharacterFormatToText(style.getCharacterFormat(), 16f, "Calibri Light");
    characterFormat.setTextColor((ColorSupport.fromArgb(46, 116, 181)).clone());
    paragraphFormat.setBeforeSpacing((float) 12);
    paragraphFormat.setAfterSpacing((float) 0);
    paragraphFormat.setKeep(true);
    paragraphFormat.setKeepFollow(true);
    paragraphFormat.setOutlineLevel(OutlineLevel.Level1);
    return style;
}

/**
* Apply characterFormat
*/
static void appendCharacterFormatToText(WCharacterFormat characterFormat, float fontSize, String fontName) throws Exception 
{
    characterFormat.setFontSize(fontSize);
    characterFormat.setFontName(fontName);
}

/**
* Apply paragraphFormat
*/
static void appendParagraphFormatToParagraph(WParagraphFormat paragraphFormat, float afterSpacingValue, float lineSpacingValue) throws Exception 
{
    paragraphFormat.setAfterSpacing(afterSpacingValue);
    paragraphFormat.setLineSpacing(lineSpacingValue);
}   

You can download the complete working example from this GitHub.

The resultant Word document looks as follows.

Word document created with new Java Word Library
Word document created with new Java Word Library

Create a purchase order report

Syncfusion’s Java Word Library has powerful mail merge APIs to generate personalized reports like letters, invoices, payroll, and email content. It saves you effort and time by helping you to automate the generation of personalized Word documents programmatically in Java. The resultant documents can be saved as Word documents (DOCX, DOCM, DOTX, WordML), HTML, and TXT.

You can execute mail merge for nested groups or regions in a Word document. It replaces all the merge fields within nested regions with relational (hierarchical) data by repeating nested regions of the document automatically for each record in the data source.

Step 1 : File > New > Java Project. The New Java Project wizard dialog appears, letting you specify configurations for the project.
New Java Project wizard dialog

Step 2: Add external .jar files (“syncfusion-docio.jar” , “syncfusion-javahelper.jar“) to your project. Refer to the External Jars Required page for the dependent .jar files.
Add external .jar files ("syncfusion-docio.jar" , "syncfusion-javahelper.jar") to your project.Step 3: Include the following namespaces in the MailMerge.java file.

Java
import java.io.File;
import java.io.FileInputStream;
import com.syncfusion.docio.*;
import com.syncfusion.javahelper.system.*;
import com.syncfusion.javahelper.system.drawing.*;

Step 4: Add the following code in main method to create a purchase order report in Java using the mail merge functionality of Syncfusion Word Library.

//Creates new Word document instance for Word processing.
WordDocument document = new WordDocument();
//Opens the template Word document.
String basePath = getDataDir("Template.docx");
document.open(basePath, FormatType.Docx);
//Retrieves the mail merge data.
MailMergeDataTable dataTable = getMailMergeDataTable();
//Executes nested Mail merge using implicit relational data.
document.getMailMerge().executeNestedGroup(dataTable);
//Removes empty page at the end of Word document.
removeEmptyPage(document);
//Saves the document in the given name and format.
document.save("Report.docx", FormatType.Docx);
//Release the resources occupied by the WordDocument instance.
document.close();

Please refer to the following  Java code definition of the getMailMergeDataTable method, which provides data for mail merge. You can download the XML file from CustomerDetails.xml.

/**
* 
* Gets the mail merge data table.
* 
* @return
*/
private static MailMergeDataTable getMailMergeDataTable() throws Exception
{
    // Gets the customer details implicit as "IEnumerable" collection.
    ListSupport<CustomerDetails> customers = new ListSupport<CustomerDetails>(CustomerDetails.class);
    FileStreamSupport stream = new FileStreamSupport(getDataDir("CustomerDetails.xml"), FileMode.OpenOrCreate);
    XmlReaderSupport reader = XmlReaderSupport.create(stream);
    while (reader.getNodeType().getEnumValue() != XmlNodeType.Element.getEnumValue())
        reader.read();
    reader.read();
    while (reader.getNodeType().getEnumValue() == XmlNodeType.Whitespace.getEnumValue())
        reader.read();
    while (!(reader.getLocalName() == "CustomerDetails"))
    {
        if (reader.getNodeType().getEnumValue() == XmlNodeType.Element.getEnumValue())
        {
            switch ((reader.getLocalName()) == null ? "string_null_value" : (reader.getLocalName())) 
           {
                case "Customers":
                    customers.add(getCustomer(reader));
                    break;
           }
        }
        else
        {
            reader.read();
            if ((reader.getLocalName() == "CustomerDetails")
                && reader.getNodeType().getEnumValue() == XmlNodeType.EndElement.getEnumValue())
                break;
        }
    }
    reader.close();
    stream.close();
    // Creates an instance of "MailMergeDataTable" by specifying mail merge group
    // name and "IEnumerable" collection.
    MailMergeDataTable dataTable = new MailMergeDataTable("Customers", customers);
    return dataTable;
}

You can download the complete working example from this GitHub repository.

The resultant Word document will be similar to the one in the following screenshot.

Purchase order report created using mail merge in Java
Purchase order report created using mail merge in Java

Conclusion

Thank you for taking the time to read this blog. I hope you now understand how to create Word documents with text, images, and tables, and how to create a purchase order using the mail merge feature using the Syncfusion Java Word Library. Take a moment to peruse the documentation, where you’ll find other options and features, all with accompanying code examples. Explore Java Word demos for more Word document processing examples using Syncfusion Java Word Library.

Currently, we have provided most of the basic Word processing features in our Java library. We will implement more features in our upcoming releases. Feel free to download the product setup. If you’re not yet a Syncfusion user, you can download a free, 30-day trial here.

If you have any questions about the features of this new Java library, please let us know in the comments below. You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top