Java API for Various Document Formats
Aspose.Words for Java is an advanced Java Word processing API that enables you to perform a great range of document processing tasks directly within your Java applications. Aspose.Words for Java API supports processing word (DOC, DOCX, OOXML, RTF) HTML, OpenDocument, PDF, EPUB, XPS, SWF and all image formats. With Aspose.Words you can generate, modify, and convert documents without using Microsoft Word.
Directory | Description |
---|---|
Examples | A collection of Java examples that help you learn the product features. |
Plugins | Plugins that will demonstrate one or more features of Aspose.Words for Java. |
Word API Features
Rendering and Printing
- Layout document into pages with high fidelity (exactly like Microsoft Word® would do that) to all the formats below.
- Render individual pages or complete documents to
PDF
,XPS
, orSWF
. - Render document pages to raster images (Multipage
TIFF
,PNG
,JPEG
,BMP
). - Render pages to a Java Graphics object to a specific size.
- Print document pages using the Java printing infrastructure.
- Update TOC, page numbers, and other fields before rendering or printing.
- 3D Effects Rendering through the
OpenGL
.
Document Content Features
- Access, create, and modify various document elements.
- Access and modify all document elements using
XmlDocument
-like classes and methods. - Copy and move document elements between documents.
- Join and split documents.
- Specify document protection, open protected, and encrypted documents.
- Find and replace text, enumerate over document content.
- Preserve or extract OLE objects and ActiveX controls from the document.
- Preserve or remove VBA macros from the document. Preserve VBA macros digital signature.
Reporting Features
- Support of C# syntax and LINQ extension methods directly in templates (even for
ADO.NET
data sources). - Support of repeatable and conditional document blocks (loops and conditions) for tables, lists, and common content.
- Support of dynamically generated charts and images.
- Support of insertion of outer documents and
HTML
blocks into a document. - Support of multiple data sources (including of different types) for the generation of a single document.
- Built-in support of data relations (master-detail).
- Comprehensive support of various data manipulations such as grouping, sorting, filtering, and others directly in templates.
For a more comprehensive list of features, please visit Feature Overview.
Read & Write Document Formats
Microsoft Word: DOC, DOCX, RTF, DOT, DOTX, DOTM, DOCM FlatOPC, FlatOpcMacroEnabled, FlatOpcTemplate, FlatOpcTemplateMacroEnabled
OpenOffice: ODT, OTT
WordprocessingML: WordML
Web: HTML, MHTML
Fixed Layout: PDF
Text: TXT
Other: MD
Save Word Files As
Fixed Layout: XPS, OpenXPS, PostScript (PS)
Images: TIFF, JPEG, PNG, BMP, SVG, EMF, GIF
Web: HtmlFixed
Others: PCL, EPUB, XamlFixed, XamlFlow, XamlFlowPack
Read File Formats
MS Office: DocPreWord60
eBook: MOBI
Supported Environments
- Microsoft Windows: Windows Desktop & Server (x86, x64)
- macOS: Mac OS X
- Linux: Ubuntu, OpenSUSE, CentOS, and others
- Java Versions:
J2SE 7.0 (1.7)
,J2SE 8.0 (1.8)
or above.
Get Started with Aspose.Words for Java
Aspose hosts all Java APIs at the Aspose Repository. You can easily use Aspose.Words for Java API directly in your Maven projects with simple configurations. For the detailed instructions please visit Installing Aspose.Words for Java from Maven Repository documentation page.
Printing Multiple Pages on One Sheet using Java
// Open the document. Document doc = new Document(dataDir + "TestFile.doc"); // Create a print job to print our document with. PrinterJob pj = PrinterJob.getPrinterJob(); // Initialize an attribute set with the number of pages in the document. PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet(); attributes.add(new PageRanges(1, doc.getPageCount())); // Pass the printer settings along with the other parameters to the print document. MultipagePrintDocument awPrintDoc = new MultipagePrintDocument(doc, 4, true, attributes); // Pass the document to be printed using the print job. pj.setPrintable(awPrintDoc); pj.print();
Product Page | Docs | Demos | API Reference | Examples | Blog | Search | Free Support | Temporary License
Aspose-dotCMS-Export-To-Word-v1.0.0
7 years ago
Export to Word Plugin for dotCMS allow users to export online content into Word Processing document using Aspose.Words for Java. It dynamically exports the content of the Web page to a Word Processing document and then automatically downloads the file to the disk location selected by the user in just couple of seconds. The generated Word processing document can then be opened using any Word Processing Application such as Microsoft Word or Apache OpenOffice etc.
Installing
Once downloaded, please follow these steps to install the plugin into your dotCMS website:
- Log into your site as either admin or another super-user level account.
- Go to the dotCMS Dynamic Plugin portlet under the System tab and click on the «Upload Plugin» button and then choose the AsposeDotCMSExportToWord JAR file.
OR
Copy the AsposeDotCMSExportToWord JAR file inside the Felix OSGI container (dotCMS/felix/load). - Please add the following 2 exported packages either by changing the file: dotCMS/WEB-INF/felix/osgi-extra.conf or using the dotCMS UI (System -> Dynamic Plugins -> Exported Packages).
- javax.xml.stream
- javax.xml.namespace
Using
After you have installed the Export to Word OSGI plugin, it is really simple to start using it on your website. Please follow these simple steps to get started:
- Make sure you are logged-in to dotCMS with a Host or Admin level account.
- Navigate to the page whose content you want to export to a Word Processing document.
- Add following HTML code in your page content.
<form action="/app/exporttoword" method="POST">
<input type="hidden" name="page_url" value=$dotPageContent.url />
<input type="submit" value="Export to Word" style="float: right;" />
</form>
This will add Export to Word button on the page and clicking a button will dynamically exports the content of the page into a Word Processing document.
How to apply Aspose License?
This Plugin uses an evaluation version of Aspose.Words. Once you are happy with your evaluation, you can purchase a license at the Aspose website.
To remove evaluation message and feature limitations, product license should be applied. You will receive a license file after you have purchased the product. Please follow the steps below to apply the license
- Make sure the license file is named as Aspose.Words.Java.lic.
- Place Aspose.Words.Java.lic file in the folder that contains the Aspose.Words.jar
- Use following code for activating the license:
License license = new License();
license.setLicense("Aspose.Words.Java.lic");
Please check this article for further details.
Supported Platforms
In order to deploy Export to Word OSGI/Dynamic Plugin you need to have the following requirements met:
- dotCMS 2.2 +
Please feel free to contact us if you wish to install this plugin on older versions of dotCMS.
Aspose.Words-Java-for-Eclipse-(Maven)-v1.0.0
7 years ago
This is new Plugin for Eclipse IDE by Aspose. The Plugin intended for developers using Maven platform for Java developments and want to use Aspose.Words for Java in their projects.
NOTE: Aspose.Words for Java is Java API developed by Aspose that offers easy Microsoft Word document creation and manipulation right from within Java Projects. For the API detailed features list check the link.
The release contains the following features:
Aspose.Words Maven Project (wizard)
- By using this wizard plugin creates Maven project for using Aspose.Words for Java from New -> Project -> Maven-> Aspose.Words Maven Project
- The wizard will also give option for downloading latest available Code Examples for using the API.
Aspose.Words Code Example (wizard)
- By using this wizard plugin lets you copy the downloaded Code Examples into your project for using Aspose.Words for Java from New -> Other -> Java -> Aspose.Words Code Example
- The wizard will also look for and updates for newly available Code Examples from Aspose.Words for Java examples repository.
(Selected Code Examples (category) source codes will be copied under «com.aspose.words.examples» package. Resources needed for running examples will be copied to the corresponding directory (package) within «src/main/resources»).
Other Features
- Supports latest Eclipse Mars.1 (4.5.1) version
- Compatible with Mac, Linux Flavors and Windows
- Native IDE user experience
- Open Source
Code Examples
The Aspose.Words Code Example wizard currently integrates the following Aspose.Words Code Examples with the Eclipse IDE
- Quick Start
- Append Documents
- Apply License
- Find And Replace
- Hello World
- Load And Save To Disk
- Load And Save To Stream
- Simple MailMerge
- Update Fields
- Loading and Saving
- Check Format
- Image To PDF
- Load Text
- Page Splitter
- Split Into HTML Pages
- Word 2 Help
- Programming Documents
- Bookmarks
- Comments
- Document
- Fields
- Find & Replace
- Images
- Joining Appending
- Styles
- Tables
- Mail Merge
- Apply Custom Logic To Empty Regions
- MailMerge Form Fields
- Multiple Docs In MailMerge
- MustacheTemplate Syntax
- Nested MailMerge
- Remove Empty Regions
- XML MailMerge
- Rendering and Printing
- Document Preview And Print.
- Print Preview Dialog
- Print Preview Dialog
- Render Shapes
- Save As Multipage TIFF
- Document Explorer (Gui Based)
Aspose.Words_Java_for_Jython-v1.0.0
7 years ago
Demonstrates the Aspose.Words for Java API usage within Jython.
Aspose.Words for Java API is very rich in features, however this release provides usage examples for following features:
Quick Start
- Append Documents
- DocToPdf
- Apply License
- Find And Replace
- Hello World
- Load And Save To Disk
- Load And Save To Stream
- Simple Mail Merge
- Update Fields
- Working With Nodes
Programming with Document
- Joining And Appending
- Working With Comments
- Working With Bookmarks
- Working With Document
- Working With Fields
- Working With Images
- Working With Styles
- Working With Tables
Loading And Saving
- Check File Format
- Convert To Other Formats
- Check Digital Signatures
- Load Text File
Rendering and Printing
- Render Shapes
- Save Document as Multipage TIFF
Aspose.Words-Java-for-NetBeans-8.1-(Maven)-v1.0.0.0
7 years ago
This is new Plugin for NetBeans IDE by Aspose. The Plugin intended for developers using Maven platform for Java developments and want to use Aspose.Words for Java in their projects.
NOTE: Aspose.Words for Java is Java API developed by Aspose that offers easy Microsoft Word document creation and manipulation right from within Java Projects. For the API detailed features list check the link.
The release contains the following features:
Aspose.Words Maven Project (wizard)
- By using this wizard plugin creates Maven project for using Aspose.Words for Java from New Project -> Maven-> Aspose.Words Maven Project
- The wizard will also give option for downloading latest available Code Examples for using the API.
Aspose.Words Code Example (wizard)
- By using this wizard plugin lets you copy the downloaded Code Examples into your project for using Aspose.Words for Java from New File -> Java -> Aspose.Words Code Example
- The wizard will also look for and updates for newly available Code Examples from Aspose.Words for Java examples repository.
(Selected Code Examples (category) source codes will be copied under «com.aspose.words.examples» package. Resources needed for running examples will be copied to the corresponding directory (package) within «src/main/resources»).
Other Features
- Supports latest NetBeans 8.1 version
- Compatible with Mac, Linux Flavors and Windows
- Native IDE user experience
- Open Source
Code Examples
The Aspose.Words Code Example wizard currently integrates the following Aspose.Words Code Examples with the NetBeans IDE
- Quick Start
- Append Documents
- Apply License
- Find And Replace
- Hello World
- Load And Save To Disk
- Load And Save To Stream
- Simple MailMerge
- Update Fields
- Loading and Saving
- Check Format
- Image To PDF
- Load Text
- Page Splitter
- Split Into HTML Pages
- Word 2 Help
- Programming Documents
- Bookmarks
- Comments
- Document
- Fields
- Find & Replace
- Images
- Joining Appending
- Styles
- Tables
- Mail Merge
- Apply Custom Logic To Empty Regions
- MailMerge Form Fields
- Multiple Docs In MailMerge
- MustacheTemplate Syntax
- Nested MailMerge
- Remove Empty Regions
- XML MailMerge
- Rendering and Printing
- Document Preview And Print.
- Print Preview Dialog
- Print Preview Dialog
- Render Shapes
- Save As Multipage TIFF
- Document Explorer (Gui Based)
Aspose.Words-Java-for-NetBeans-8.0-(Maven)-v1.0.0.0
7 years ago
This is new Plugin for NetBeans IDE by Aspose. The Plugin intended for developers using Maven platform for Java developments and want to use Aspose.Words for Java in their projects.
NOTE: Aspose.Words for Java is Java API developed by Aspose that offers easy Microsoft Word document creation and manipulation right from within Java Projects. For the API detailed features list check the link.
The release contains the following features:
Aspose.Words Maven Project (wizard)
- By using this wizard plugin creates Maven project for using Aspose.Words for Java from New Project -> Maven-> Aspose.Words Maven Project
- The wizard will also give option for downloading latest available Code Examples for using the API.
Aspose.Words Code Example (wizard)
- By using this wizard plugin lets you copy the downloaded Code Examples into your project for using Aspose.Words for Java from New File -> Java -> Aspose.Words Code Example
- The wizard will also look for and updates for newly available Code Examples from Aspose.Words for Java examples repository.
(Selected Code Examples (category) source codes will be copied under «com.aspose.words.examples» package. Resources needed for running examples will be copied to the corresponding directory (package) within «src/main/resources»).
Other Features
- Supports NetBeans 8.0 version
- Compatible with Mac, Linux Flavors and Windows
- Native IDE user experience
- Open Source
Code Examples
The Aspose.Words Code Example wizard currently integrates the following Aspose.Words Code Examples with the NetBeans IDE
- Quick Start
- Append Documents
- Apply License
- Find And Replace
- Hello World
- Load And Save To Disk
- Load And Save To Stream
- Simple MailMerge
- Update Fields
- Loading and Saving
- Check Format
- Image To PDF
- Load Text
- Page Splitter
- Split Into HTML Pages
- Word 2 Help
- Programming Documents
- Bookmarks
- Comments
- Document
- Fields
- Find & Replace
- Images
- Joining Appending
- Styles
- Tables
- Mail Merge
- Apply Custom Logic To Empty Regions
- MailMerge Form Fields
- Multiple Docs In MailMerge
- MustacheTemplate Syntax
- Nested MailMerge
- Remove Empty Regions
- XML MailMerge
- Rendering and Printing
- Document Preview And Print.
- Print Preview Dialog
- Print Preview Dialog
- Render Shapes
- Save As Multipage TIFF
- Document Explorer (Gui Based)
Aspose.Words_Java_for_Docx4j-v1.0.0
7 years ago
This version of the plugin is enriched with the following examples that are helpful for developers who want to compare Docx4j with Aspose.Words OR migrate from Docx4j to Aspose.Words. We have restructured examples and now developers can use it via Maven.
Aspose.Words vs Docx4j
Examples for code comparison in Aspose.Words and Docx4j:
Working with Bookmarks
- Add Bookmarks
- Delete Bookmarks
Working with Document
- Accessing Document Properties
- Convert Document to HTML
- Working with Comments
- Insert Image
- Merge Documents
- Create New Document
- Add Watermark in Document
- Insert Hyperlink to Document
- Convert Document to PDF
- Insert Table of Contents in Document
Working with Header and Footer
- Insert Header
- Insert Footer
- Remove Header Footer from Documents
Missing Features of Docx4j
Examples for code with missing features in Docx4j in comparison with Aspose.Words:
Working with Documents
- Clone Documents
- Moving the Cursor in Document
- Protect Documents
- Check Format Compatibility
- Working with Digital Signatures
- Load Text File
- Specify Default Fonts
- Set Page Borders
- Track Changes in Documents
- Using Control Characters
Working with Tables
- Autofit Setting to Tables
- Joining Tables in Document
- Split Tables
- Repeat Table Header Rows on Pages
Mail Merge
- Mail Merge from XML Data Source
Aspose.Words_Java_for_Apache_POI_WP-v1.0.0
7 years ago
This initial version is enriched with the following examples that are helpful for developers who want to compare Apache POI WP with Aspose.Words for Java OR migrate from Apache POI WP to Aspose.Words for Java.
Aspose.Words vs Apache POI WP
Working with Documents
- Create New Word Document
- Convert Word Doc to Other Formats
- Get Document Properties
- Format Text in Document
- Open Existing Document
- Save Document
Working with Images
- Insert Image
- Extract Images from Word Document
Working with Headers and Footers
- Working with Headers
- Working with Footers
Working with Ranges
- Access Ranges in Document
- Delete Ranges in Document
- Insert Before and After Ranges
Working with Tables
- Create Tables
- Format Table in Document
Features of Aspose.Words missing in Apache POI WP
Working with Document
- Append Documents
- Clone Documents
- Protect Documents
- Track Changes in Documents
- Working with Bookmarks
- Add Watermark
- Check Format Compatibility
- Working with Digital Signatures
- Insert Picture in Word Document
- Insert Barcode on Each Page
Working with Text
- Find and Replace Text in Documents
- Insert Comments
- Specify Default Fonts
- Extract Comments from Document
- Remove Comments from Document
Working with Tables
- Joining Tables
- Split Table
- Autofit Setting to Tables
Mail Merge
- Mail Merge from XML Data Source
Working with Fields
- Insert Fields in Documents
- Remove Fields from Document
Other Examples
- Set Page Borders
- Moving the Cursor
- Using Control Characters
Aspose.Words_Java_for_IntelliJ_IDEA(Maven)-v1.0.0.0
7 years ago
:sparkles: What’s New
The release contains the following wizards:
- Aspose.Words Maven Project wizard
- Aspose.Words Examples wizard
Aspose.Words Maven Project wizard creates Aspose.Words for Java API Maven project for using Aspose.Words for Java API.
Aspose.Words Examples wizard lets you import / copy downloaded Examples Source Codes into the project along with the required resources for the execution of examples.
The wizard currently integrates the following Aspose.Words examples with the IntelliJ IDEA:
- Quick Start
- Loading and Saving
- Programming Documents
- Bookmarks
- Comments
- Document
- Fields
- Find and Replace
- Images
- Joining and Appending
- Styles
- Tables
- Mail Merge
- Rendering and Printing
- Document Explorer (Gui Based)
Please also check this Blog Post on Aspose blogs for the plugin release v1.0.0.0
Aspose.Words_Java_vs_Docx4j_v1.2
7 years ago
Release contain the open source code comparison examples among features of Aspose.Words Java and Docx4j — Dealing Microsoft Word and OpenOffice Documents.
:sparkles: What’s New
Following Examples:
- Add Watermark in Document
- Insert Hyperlink to Document
- Convert Document to PDF
- Insert Table of Contents in Document
- Remove Header Footer from Documents
:sparkles: Existing Examples
Working with Bookmarks
- Add Bookmarks
- Delete Bookmarks
Working with Document
- Accessing Document Properties
- Convert Document to HTML
- Working with Comments
- Insert Image
- Merge Documents
- Create New Document
Working with Header and Footer
- Insert Header
- Insert Footer
Feedback and Suggestions
- Many more examples are available at Aspose Docs.
- Raise your queries and suggest more examples via Aspose Forums or via this social coding site.
Aspose.Words_Java_for_Python-v1.0.0
7 years ago
Aspose.Words Java for Python
Aspose Words Java for Python is a Python project that demonstrates / provides the Aspose.Words for Java API usage examples in Python by using Jpype.
You will need to install Jpype before using any of the Aspose provided Java APIs in Python e.g Aspose.Words, Aspose.Cells and Aspose.Slides etc.
For the configuration/setup of Jpype, please see:
http://jpype.readthedocs.org/en/latest/userguide.html
To download Aspose.Words for Java API to be used with these examples through Jpype
Please navigate to:
http://www.aspose.com/community/files/72/java-components/aspose.words-for-java/
For most complete documentation of the project, check Aspose.Words Java for Python confluence wiki link:
http://www.aspose.com/docs/display/wordsjava/6.+Aspose.Words+Java+For+Python
-
- GitLab: the DevOps platform
- Explore GitLab
- Install GitLab
- How GitLab compares
- Get started
- GitLab docs
- GitLab Learn
- Pricing
- Talk to an expert
-
/
-
Help
- Help
- Support
-
Community forum
- Submit feedback
- Contribute to GitLab
- Switch to GitLab Next
-
Projects
Groups
Topics
Snippets -
Register - Sign in
Aspose-Words-for-Java
Project ID: 26921097
Star
0
Aspose.Words for Java examples, plugins and showcases
Find file
Download source code
tar.gz
tar.bz2
tar
Clone
-
Clone with SSH
-
Clone with HTTPS
-
Open in your IDE
Visual Studio Code (SSH)Visual Studio Code (HTTPS)IntelliJ IDEA (SSH)IntelliJ IDEA (HTTPS)
- Copy SSH clone URLgit@gitlab.com:pegoopik/Aspose-Words-for-Java.git
- Copy HTTPS clone URLhttps://gitlab.com/pegoopik/Aspose-Words-for-Java.git
- README
- MIT License
Aspose.Words for Java is a feature-rich Word processing API. It allows you to generate, modify, convert, render and print documents in Java applications without using Microsoft Word. The API provides the capabilities to access and manipulate formatting properties of all document elements, high-quality conversions to multiple formats, rendering individual pages or complete documents to different file formats, generating reports with data from various data sources or business objects and much more. Aspose.Words for Java supports all popular Word Processing file formats and also allows you to export or convert Word documents to fixed-layout formats and most commonly used image/multimedia formats.
Click for more
Supported File Formats
Input/Output
- Microsoft Word: DOC, DOCX, RTF, DOT, DOTX, DOTM, DOCM FlatOPC, FlatOpcMacroEnabled, FlatOpcTemplate, FlatOpcTemplateMacroEnabled
- OpenOffice: ODT, OTT
- WordprocessingML: WordML
- Web: HTML, MHTML
- Text: TXT
Output Only
- Fixed Layout: PDF, PDF/A, XPS, OpenXPS, PostScript (PS)
- Graphics: TIFF, JPEG, PNG, BMP, SVG, EMF, GIF
- Web: HtmlFixed
- Others: PCL, EPUB, XamlFixed, XamlFlow, XamlFlowPack
Input Only
- MOBI
- DocPreWord60
Advanced Java Word Document API Features
- Convert a…
Latest News
Aspose.Words for Java V23.4
Adds the ability to set the distance between a table and surrounding text.
New Version | April 11, 2023 — 15:43
Aspose.Words for Java V23.3
You can now specify whether to adjust sentence and word spacing when importing documents.
New Version | March 20, 2023 — 15:58
Aspose.Words for Java V23.2
Significantly improves chart rendering and adds support for importing and exporting MOBI format.
New Version | February 21, 2023 — 15:41
Aspose.Words for Java V23.1
Adds the ability to generate TOC (table of contents) for AZW3 documents.
New Version | January 25, 2023 — 10:38
Aspose.Words for Java V22.12
Improves support for margins and PDF rendering.
New Version | December 14, 2022 — 11:05
Aspose.Words for Java V22.11
Adds custom color/grayscale printing mode.
New Version | November 18, 2022 — 9:40
Prices from: US$ 1,163.03
Developer Small Business License: One Developer and One Deployment Location — A Developer Small Business License allows One developer to create an unlimited number of end user software using the…
Got a Question?
Live Chat with our Aspose licensing specialists now.
As official and authorized distributors, ComponentSource supplies you with legitimate licenses directly from Aspose.
Component Type
- Java Class
Recent Awards
Customer Reviews
Most recent positive review
United Kingdomover 2 years ago
At Ten-25 we want to empower our customers to be the absolute best they can be, to play our part in the supply chain of their world. Thanks to Aspose.Words for JAVA, we have been able to take a big… Read more
Most recent critical review
There are no negative reviews for this product.
Aspose Fill word Data
This paper describes how to generate word documents using aspose and provides a tool class for reference.
Catalog
-
Aspose Fill word Data
-
1. Create a word template
- 1.1 Define a single variable
- 1.2 Define set variables
- 1.3 Demo Template Document Download
-
2. Getting Started
- 2.1 Preparing for use
- 2.2 Import Tool Class
- 2.3 Start using
- 2.4 Result Display
-
3. Notes
- 3.1 Watermark Description
- 3.2 How to add a license
-
1. Create a word template
1. Create a word template
1.1 Define a single variable
- In a word document, in the menu bar, click Insert->Document Parts->Fields in turn;
- Next, select the MergeField field in the pop-up box and fill in the domain name in the domain properties. The domain name is the variable name. Click OK when you have finished filling out the domain name.
Generate the style as shown, that is, add successfully
1.2 Define set variables
When a single variable doesn’t meet our needs, we need to define a set variable. I’ll take employee salary statistics for example, and there will be multiple data in one table.At this point, we should insert the List data into the template file.
- Template keywords: TableStart: Collection name, TableEnd: Collection name
- Similarly, select MergeField in the text field, starting with TableStart, followed by a colon:, and then defining the name of the collection.Note that TableStart means the beginning of a collection, so where we end the collection, we need to add the end identifier TableEnd.
-
The variable between TableStart and TableEnd is the variable name for each property in the collection.
Once added, as shown in the diagram
End of Word Template Writing
1.3 Demo Template Document Download
Click here to download the presentation document
2. Getting Started
In my company, the contract is a micro-service, so it is a little tidy, simplify the operation related to documents, and integrate them into a class for your reference.
2.1 Preparing for use
- Import the package of aspose, I am using version 16.8.0 of aspose-words, because it is provided by the company, I will not upload, you can go online to search for a download.
- Remove the watermark operation, you can also go online to search for a license.xml download.(Details can be referred to as: 3.1 Watermark Description)
2.2 Import Tool Class
package com.chimmhuang.util; import com.aspose.words.Document; import com.aspose.words.SaveFormat; import com.aspose.words.SaveOptions; import com.aspose.words.net.System.Data.DataRow; import com.aspose.words.net.System.Data.DataTable; import org.springframework.util.CollectionUtils; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Chimm Huang * @date 2020/01/22 */ public class ContractUtil { private ContractUtil() { } /** * Fill in the word template (object data format) * * @param modelWordByte word Template Binary * @param obj Data to fill * @return word binary after combining data */ public static byte[] fillWordDataByDomain(byte[] modelWordByte, Object obj) { try { Class<?> aClass = obj.getClass(); Field[] fields = aClass.getDeclaredFields(); Map<String, Object> data = new HashMap<>(fields.length); for (Field field : fields) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), aClass); Method method = pd.getReadMethod(); String key = field.getName(); Object value = method.invoke(obj); if (value != null) { data.put(key, value); } } return fillWordDataByMap(modelWordByte, data); } catch (Exception e) { return new byte[0]; } } /** * Fill in the word template (map data format) * * @param file word Binary * @param data Data to fill * @return word binary after combining data */ public static byte[] fillWordDataByMap(byte[] file, Map<String, Object> data) throws Exception { byte[] ret = null; if (CollectionUtils.isEmpty(data)) { return ret; } try (InputStream is = new ByteArrayInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream()) { Document doc = new Document(is); Map<String, String> toData = new HashMap<>(); for (Map.Entry<String, Object> en : data.entrySet()) { String key = en.getKey(); Object value = en.getValue(); if (value instanceof List) { //Write table data DataTable dataTable = fillListData((List) value, key); doc.getMailMerge().executeWithRegions(dataTable); } String valueStr = String.valueOf(en.getValue()); if (value == null || value.equals("null")) { continue; } toData.put(key, valueStr); } String[] fieldNames = new String[toData.size()]; String[] values = new String[toData.size()]; int i = 0; for (Map.Entry<String, String> entry : toData.entrySet()) { fieldNames[i] = entry.getKey(); values[i] = entry.getValue(); i++; } //Merge data doc.getMailMerge().execute(fieldNames, values); doc.save(out, SaveOptions.createSaveOptions(SaveFormat.DOCX)); ret = out.toByteArray(); } return ret; } /** * Encapsulate list data into word templates (word tables) * * @param list data * @param tableName Table List Variable Name * @return word Table Data DataTable */ private static DataTable fillListData(List<Object> list, String tableName) throws IntrospectionException, InvocationTargetException, IllegalAccessException { //Create a DataTable and bind fields DataTable dataTable = new DataTable(tableName); for (Object obj : list) { //Create a DataRow to encapsulate this row of data DataRow dataRow = dataTable.newRow(); Class<?> objClass = obj.getClass(); Field[] fields = objClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; dataTable.getColumns().add(fields[i].getName()); PropertyDescriptor pd = new PropertyDescriptor(field.getName(), objClass); Method method = pd.getReadMethod(); dataRow.set(i,method.invoke(obj)); } dataTable.getRows().add(dataRow); } return dataTable; } // private static License license = null; /** * Load license * Since aspose is charged, watermarks will appear if there is no license. */ // static { // try { // InputStream is = ContractUtil.class.getResourceAsStream("/license.xml"); // license = new License(); // license.setLicense(is); // } catch (Exception e) { // throw new RuntimeException("Failed to load aspose certificate file automatically!"); // } // } }
2.3 Start using
- First, let’s define the data that corresponds to the template. First, let’s define the data for [Employee Pay Information] Worker in the list.
package com.chimmhuang.pojo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; /** * Employee Salary Information * * @author Chimm Huang */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Worker { /** Employee Name */ private String name; /** Age */ private Integer age; /** Gender */ private String sex; /** wages */ private BigDecimal salary; }
- Next, we define the basic data for the entire template: SalaryData
package com.chimmhuang.pojo; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.util.List; /** * Document Template Data * * @author Chimm Huang */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class SalaryData { /** Corporate name */ private String companyName; /** Employee salary list */ private List<Worker> workerList; /** Total wages */ private BigDecimal totalSalary; }
- Once you have defined the above data, you can start filling in the data, and the tool class provides two filling methods
- One is to pass Object data for data filling
- Another is to transfer Map data for data filling
I’m here to fill in the data in the first way, and I personally recommend domain s.
package com.chimmhuang.run; import com.chimmhuang.pojo.SalaryData; import com.chimmhuang.pojo.Worker; import com.chimmhuang.util.ContractUtil; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; /** * @author Chimm Huang */ public class App { public static void main(String[] args) throws IOException { // Encapsulate employee pay information Worker worker1 = Worker.builder() .name("Zhang San") .age(18) .sex("male") .salary(BigDecimal.valueOf(1000)) .build(); Worker worker2 = Worker.builder() .name("Li Si") .age(16) .sex("female") .salary(BigDecimal.valueOf(2000)) .build(); List<Worker> workerList = Arrays.asList(worker1, worker2); // Calculate total wages BigDecimal totalSalary = workerList.stream() .map(Worker::getSalary) .reduce(BigDecimal.ZERO, BigDecimal::add); // Encapsulate document template data SalaryData data = SalaryData.builder() .companyName("Wang Duoyu Co., Ltd.") .workerList(workerList) .totalSalary(totalSalary) .build(); // Read Template File byte[] modelByte = Files.readAllBytes(Paths.get("C:\Users\huangshuai\Desktop\Template.docx")); // Call the tool class to get the file after populating the data byte[] resultByte = ContractUtil.fillWordDataByDomain(modelByte, data); // Processing the binary file, which is processed here as output to the desktop File resultFile = new File("C:\Users\huangshuai\Desktop\Employee Salary Statistics.docx"); FileOutputStream fos = new FileOutputStream(resultFile); fos.write(resultByte); fos.close(); } }
2.4 Result Display
3. Notes
3.1 Watermark Description
Looking at the picture above, it is not difficult to see that the document is also generated with a series of red fonts.
Since aspose is charged for fees, you need to add license.xml to remove the watermark. Since I use the company’s credentials, I will not upload them. If you need, you can choose to purchase the service of aspose or search for a license.xml online.
3.2 How to add a license
I have provided a static initialization method in the tool class. Once you have downloaded the license.xml, you can put it in the corresponding directory and remove the comments.