Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active September 26, 2020 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/aa75ee5112aca57022c741270ff8cbc4 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/aa75ee5112aca57022c741270ff8cbc4 to your computer and use it in GitHub Desktop.
This Gist contains code snippets for examples of Aspose.Words for Java.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
This Gist contains code snippets for examples of Aspose.Words for Java.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
DocumentBuilder builder = new DocumentBuilder();
Field field = builder.insertField("=1", null);
field.setLocaleId(1027);
// 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(UseOfficeMathProperties.class);
Document doc = new Document(dataDir + "MathEquations.docx");
OfficeMath officeMath = (OfficeMath)doc.getChild(NodeType.OFFICE_MATH, 0, true);
// Gets/sets Office Math display format type which represents whether an equation is displayed inline with the text or displayed on its own line.
officeMath.setDisplayType(OfficeMathDisplayType.DISPLAY); // or OfficeMathDisplayType.Inline
// Gets/sets Office Math justification.
officeMath.setJustification(OfficeMathJustification.LEFT); // Left justification of Math Paragraph.
doc.save(dataDir + "MathEquations_out.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document(dataDir + "RemoveTableRows.doc");
DataSet data = new DataSet();
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS | MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS | MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
doc.getMailMerge().setMergeDuplicateRegions(true);
doc.getMailMerge().executeWithRegions(data);
doc.save(dataDir + "RemoveTableRows_Out.doc");
// Create a new empty document. It has one section.
Document doc = new Document();
// The section is the first child node of the document.
Node section = doc.getFirstChild();
// The section's parent node is the document.
System.out.println("Section parent is the document: " + (doc == section.getParentNode()));
Document doc = new Document(dataDir + "Document.doc");
Paragraph paragraph = (Paragraph)doc.getChild(NodeType.PARAGRAPH, 0, true);
NodeCollection children = paragraph.getChildNodes();
for (Node child : (Iterable<Node>) children) {
// Paragraph may contain children of various types such as runs, shapes and so on.
if (child.getNodeType() == NodeType.RUN) {
// Say we found the node that we want, do something useful.
Run run = (Run)child;
System.out.println(run.getText());
}
}
Document doc = new Document(dataDir + "Document.doc");
Paragraph paragraph = (Paragraph)doc.getChild(NodeType.PARAGRAPH, 0, true);
NodeCollection children = paragraph.getChildNodes();
for (int i = 0; i < children.getCount(); i++) {
Node child = children.get(i);
// Paragraph may contain children of various types such as runs, shapes and so on.
if (child.getNodeType() == NodeType.RUN) {
// Say we found the node that we want, do something useful.
Run run = (Run)child;
System.out.println(run.getText());
}
}
Document doc = new Document();
Paragraph para = new Paragraph(doc);
Section section = doc.getLastSection();
section.getBody().appendChild(para);
Document doc = new Document();
// Returns NodeType.Document
int type = doc.getNodeType();
// Open a file from disk.
Document doc = new Document();
// Creating a new node of any type requires a document passed into the constructor.
Paragraph para = new Paragraph(doc);
// The new paragraph node does not yet have a parent.
System.out.println("Paragraph has no parent node: " + (para.getParentNode() == null));
// But the paragraph node knows its document.
System.out.println("Both nodes' documents are the same: " + (para.getDocument() == doc));
// The fact that a node always belongs to a document allows us to access and modify
// properties that reference the document-wide data such as styles or lists.
para.getParagraphFormat().setStyleName("Heading 1");
// Now add the paragraph to the main text of the first section.
doc.getFirstSection().getBody().appendChild(para);
// The paragraph node is now a child of the Body node.
System.out.println("Paragraph has a parent node: " + (para.getParentNode() != null));
public static void main(String[] args) throws Exception {
String dataDir = Utils.getSharedDataDir(ChildNodes.class) + "DocumentObjectModel/";
recurseAllNodes(dataDir);
}
public static void recurseAllNodes(String dataDir) throws Exception {
// Open a document
Document doc = new Document(dataDir + "Node.RecurseAllNodes.doc");
// Invoke the recursive function that will walk the tree.
traverseAllNodes(doc);
}
/**
* A simple function that will walk through all children of a specified node
* recursively and print the type of each node to the screen.
*/
public static void traverseAllNodes(CompositeNode parentNode) throws Exception {
// This is the most efficient way to loop through immediate children of a node.
for (Node childNode = parentNode.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) {
// Do some useful work.
System.out.println(Node.nodeTypeToString(childNode.getNodeType()));
// Recurse into the node if it is a composite node.
if (childNode.isComposite())
traverseAllNodes((CompositeNode) childNode);
}
}
Document doc = new Document();
// Quick typed access to the first child Section node of the Document.
Section section = doc.getFirstSection();
// Quick typed access to the Body child node of the Section.
Body body = section.getBody();
// Quick typed access to all Table child nodes contained in the Body.
TableCollection tables = body.getTables();
for (Table table : tables) {
// Quick typed access to the first row of the table.
if (table.getFirstRow() != null)
table.getFirstRow().remove();
// Quick typed access to the last row of the table.
if (table.getLastRow() != null)
table.getLastRow().remove();
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(BubbleChart.class);
String fileName = "BubbleChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// Load the template document.
Document doc = new Document(dataDir + "template_cleanup.docx");
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
//engine.setOptions(ReportBuildOptions.REMOVE_EMPTY_PARAGRAPHS);
engine.buildReport(doc, Common.GetClients());
dataDir = dataDir + "output.docx";
doc.save(dataDir, SaveFormat.DOCX);
// The path to the documents directory.
String dataDir = Utils.getDataDir(BulletedList.class);
String fileName = "BulletedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetClients());
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
List<PointData> data = new ArrayList<PointData>();
data.add(new PointData("12:00:00 AM", 10, 2));
data.add(new PointData("01:00:00 AM", 15, 4));
data.add(new PointData("02:00:00 AM", 23, 7));
List<String> seriesNames = Arrays.asList("Flow","Rainfall");
Document doc = new Document(dataDir + "ChartTemplate.docx");
ReportingEngine engine = new ReportingEngine();
engine.buildReport(doc, new Object[] { data, seriesNames }, new String[] { "data", "seriesNames" });
doc.save(dataDir + "ChartTemplate_Out.docx");
// The path to the documents directory.
String dataDir = Utils.getDataDir(ChartWithFilteringGroupingOrdering.class);
String fileName = "ChartWithFilteringGroupingOrdering.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
public class Client
{
private String Name;
public final String getName()
{
return Name;
}
public final void setName(String value)
{
Name = value;
}
}
public class Common {
public static List<Manager> managers = new ArrayList<Manager>();
/// <summary>
/// Return first manager from Managers which is an enumeration of instances of the Manager class.
/// </summary>
public static Manager GetManager(){
for (Manager manager : GetManagers()) {
return manager;
}
return null;
}
/// <summary>
/// Return an dataset of the Client class.
/// </summary>
public static DataSet GetClients() throws Exception
{
// Create a new data set
DataSet dataSet = new DataSet("DS");
// Add a new table to store clients
DataTable dt = new DataTable("clients");
// Add columns
dt.getColumns().add("Name");
dataSet.getTables().add(dt);
// Populate the data in table
for (Manager manager : GetManagers()) {
List<Contract> listOfContracts = manager.getContracts();
for (Contract contract : listOfContracts) {
DataRow row = dt.newRow();
row.set("Name", contract.getClient().getName());
dt.getRows().add(row);
}
}
return dataSet;
}
/// <summary>
/// Return an enumeration of instances of the Manager class.
/// </summary>
public static List<Manager> GetManagers() {
Manager manager = new Manager();
manager.setName("John Smith");
manager.setAge(36);
manager.setPhoto(Photo());
Contract contract1 = new Contract();
Client client1 = new Client();
client1.setName("A Company");
contract1.setClient(client1);
contract1.setManager(manager);
contract1.setPrice(1200000);
contract1.setDate(new Date(2015, 1, 1));
Contract contract2 = new Contract();
Client client2 = new Client();
client2.setName("B Ltd.");
contract2.setClient(client2);
contract2.setManager(manager);
contract2.setPrice(750000);
contract2.setDate(new Date(2015, 4, 1));
Contract contract3 = new Contract();
Client client3 = new Client();
client3.setName("C & D");
contract3.setClient(client3);
contract3.setManager(manager);
contract3.setPrice(350000);
contract3.setDate(new Date(2015, 7, 1));
ArrayList<Contract> contracts = new ArrayList<Contract>();
contracts.add(contract1);
contracts.add(contract2);
contracts.add(contract3);
manager.setContracts(contracts);
managers.add(manager);
manager = new Manager();
manager.setName("Tony Anderson");
manager.setAge(37);
manager.setPhoto(Photo());
Contract contract4 = new Contract();
Client client4 = new Client();
client4.setName("E Corp.");
contract4.setClient(client4);
contract4.setManager(manager);
contract4.setPrice(650000);
Date date = new Date(2015, 2, 1);
contract4.setDate(date);
Contract contract5 = new Contract();
Client client5 = new Client();
client5.setName("F & Partners");
contract5.setClient(client5);
contract5.setManager(manager);
contract5.setPrice(550000);
contract5.setDate(new Date(2015, 8, 1));
ArrayList<Contract> contracts2 = new ArrayList<Contract>();
contracts2.add(contract4);
contracts2.add(contract5);
manager.setContracts(contracts2);
managers.add(manager);
manager = new Manager();
manager.setName("July James");
manager.setAge(38);
manager.setPhoto(Photo());
Contract contract6 = new Contract();
Client client6 = new Client();
client6.setName("G & Co.");
contract6.setClient(client6);
contract6.setManager(manager);
contract6.setPrice(350000);
contract6.setDate(new Date(2015, 2, 1));
Contract contract7 = new Contract();
Client client7 = new Client();
client7.setName("H Group");
contract7.setClient(client7);
contract7.setManager(manager);
contract7.setPrice(250000);
contract7.setDate(new Date(2015, 5, 1));
Contract contract8 = new Contract();
Client client8 = new Client();
client8.setName("I & Sons");
contract8.setClient(client8);
contract8.setManager(manager);
contract8.setPrice(100000);
contract8.setDate(new Date(2015, 7, 1));
Contract contract9 = new Contract();
Client client9 = new Client();
client9.setName("J Ent.");
contract9.setClient(client9);
contract9.setManager(manager);
contract9.setPrice(100000);
contract9.setDate(new Date(2015, 8, 1));
ArrayList<Contract> contracts3 = new ArrayList<Contract>();
contracts3.add(contract6);
contracts3.add(contract7);
contracts3.add(contract8);
contracts3.add(contract9);
manager.setContracts(contracts3);
managers.add(manager);
return managers;
}
/// <summary>
/// Return an array of photo bytes.
/// </summary>
private static byte[] Photo()
{
// The path to the documents directory.
String dataDir = Utils.getDataDir(Common.class);
File file = new File(dataDir + "photo.png");
return readContentIntoByteArray(file);
}
private static byte[] readContentIntoByteArray(File file)
{
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try
{
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
for (int i = 0; i < bFile.length; i++)
{
//System.out.print((char) bFile[i]);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return bFile;
}
/// <summary>
/// Return an dataset of the Contract class.
/// </summary>
public static DataSet GetContracts() throws Exception
{
// Create a new data set
DataSet ds = new DataSet("ds");
// Add a new table to store contracts
DataTable dtContracts = new DataTable("Contracts");
// Add a new table to store managers
DataTable dtManagers = new DataTable("Managers");
// Add a new table to store clients
DataTable dtClients = new DataTable("Clients");
// Add columns to Managers table
dtManagers.getColumns().add("Id", int.class);
dtManagers.getColumns().add("Name");
dtManagers.getColumns().add("Age", int.class);
dtManagers.getColumns().add("Photo", byte[].class);
ds.getTables().add(dtManagers);
// Add columns to Contracts table
dtContracts.getColumns().add("Id", int.class);
dtContracts.getColumns().add("ClientId", int.class);
dtContracts.getColumns().add("ManagerId", int.class);
dtContracts.getColumns().add("Price", float.class);
dtContracts.getColumns().add("Date", Date.class);
ds.getTables().add(dtContracts);
// Add columns to Clients table
dtClients.getColumns().add("Id", int.class);
dtClients.getColumns().add("Name");
ds.getTables().add(dtClients);
ds.getRelations().add(dtClients,dtContracts, "Id","ClientId");
ds.getRelations().add(dtManagers,dtContracts, "Id","ManagerId");
int managerCounter = 1;
int contractCounter =1;
int clientCounter = 1;
for (Manager manager : GetManagers()) {
// Add data row to managers table.
DataRow managerRow = dtManagers.newRow();
managerRow.set("Id", managerCounter);
managerRow.set("Name", manager.getName());
managerRow.set("Age", manager.getAge());
managerRow.set("Photo", manager.getPhoto());
dtManagers.getRows().add(managerRow);
for (Contract contract : manager.getContracts()) {
DataRow contractRow = dtContracts.newRow();
DataRow clientRow = dtClients.newRow();
clientRow.set("Id", clientCounter);
clientRow.set("Name", contract.getClient().getName());
dtClients.getRows().add(clientRow);
contractRow.set("Id", contractCounter);
contractRow.set("ClientId", clientCounter);
contractRow.set("ManagerId", managerCounter);
contractRow.set("Price", contract.getPrice());
contractRow.set("Date", contract.getDate());
dtContracts.getRows().add(contractRow);
clientCounter += 1;
contractCounter += 1;
}
managerCounter += 1;
}
return ds;
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(CommonList.class);
String fileName = "CommonList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetContracts());
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(CommonMasterDetail.class);
String fileName = "CommonMasterDetail.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
public class Contract
{
private Manager Manager;
public final Manager getManager()
{
return Manager;
}
public final void setManager(Manager value)
{
Manager = value;
}
private Client Client;
public final Client getClient()
{
return Client;
}
public final void setClient(Client value)
{
Client = value;
}
private float Price;
public final float getPrice()
{
return Price;
}
public final void setPrice(float value)
{
Price = value;
}
private Date Date = new Date();
public final Date getDate()
{
return Date;
}
public final void setDate(Date value)
{
Date = value;
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(HelloWorld.class);
String fileName = "HelloWorld.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create an instance of sender class to set it's properties.
Sender sender = new Sender();
sender.setName("LINQ Reporting Engine");
sender.setMessage("Hello World");
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, sender, "sender");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(InParagraphList.class);
String fileName = "InParagraphList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetClients());
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(InTableList.class);
String fileName = "InTableList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(InTableMasterDetail.class);
String fileName = "InTableMasterDetail.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(InTableRow.class);
String fileName = "InTableRow.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
// engine.getKnownTypes().add(DateUtil.class);
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(InTableWithFilteringGroupingSorting.class);
String fileName = "InTableWithFilteringGroupingSorting.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetContracts(), "contracts");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
public class Manager
{
private String Name;
public final String getName()
{
return Name;
}
public final void setName(String value)
{
Name = value;
}
private int Age;
public final int getAge()
{
return Age;
}
public final void setAge(int value)
{
Age = value;
}
private byte[] Photo;
public final byte[] getPhoto()
{
return Photo;
}
public final void setPhoto(byte[] value)
{
Photo = value;
}
private List<Contract> Contracts;
public final List<Contract> getContracts()
{
return Contracts;
}
public final void setContracts(List<Contract> value)
{
Contracts = value;
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(MulticoloredNumberedList.class);
String fileName = "MulticoloredNumberedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetClients());
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(NumberedList.class);
String fileName = "NumberedList.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetClients());
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(PieChart.class);
String fileName = "PieChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ScatterChart.class);
String fileName = "ScatterChart.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetContracts(), "ds");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
public class Sender {
private String Name;
public final String getName()
{
return Name;
}
public final void setName(String value)
{
Name = value;
}
private String Message;
public final String getMessage()
{
return Message;
}
public final void setMessage(String value)
{
Message = value;
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingBackgroundColor.class);
String fileName = "SettingBackgroundColor.docx";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, new Object());
dataDir = dataDir + "SettingBackgroundColor_out.docx";
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(SingleRow.class);
String fileName = "SingleRow.doc";
// Load the template document.
Document doc = new Document(dataDir + fileName);
// Create a Reporting Engine.
ReportingEngine engine = new ReportingEngine();
// Execute the build report.
engine.buildReport(doc, Common.GetManager(), "manager");
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
// Save the finished document to disk.
doc.save(dataDir);
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AccessAndVerifySignature.class) + "LoadingSavingAndConverting/";
// The path to the document which is to be processed.
String filePath = dataDir + "Document.Signed.docx";
Document doc = new Document(filePath);
for (DigitalSignature signature : doc.getDigitalSignatures()) {
System.out.println("*** Signature Found ***");
System.out.println("Is valid: " + signature.isValid());
System.out.println("Reason for signing: " + signature.getComments()); // This property is available in MS Word documents only.
System.out.println("Time of signing: " + signature.getSignTime());
}
// 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(CheckFormatCompatibility.class);
String supportedDir = dataDir + "OutSupported" + File.separator;
String unknownDir = dataDir + "OutUnknown" + File.separator;
String encryptedDir = dataDir + "OutEncrypted" + File.separator;
String pre97Dir = dataDir + "OutPre97" + File.separator;
File[] fileList = new File(dataDir).listFiles();
// Loop through all found files.
for (File file : fileList) {
if (file.isDirectory())
continue;
// Extract and display the file name without the path.
String nameOnly = file.getName();
System.out.print(nameOnly);
// Check the file format and move the file to the appropriate folder.
String fileName = file.getPath();
FileFormatInfo info = FileFormatUtil.detectFileFormat(fileName);
// Display the document type.
switch (info.getLoadFormat()) {
case LoadFormat.DOC:
System.out.println("\tMicrosoft Word 97-2003 document.");
break;
case LoadFormat.DOT:
System.out.println("\tMicrosoft Word 97-2003 template.");
break;
case LoadFormat.DOCX:
System.out.println("\tOffice Open XML WordprocessingML Macro-Free Document.");
break;
case LoadFormat.DOCM:
System.out.println("\tOffice Open XML WordprocessingML Macro-Enabled Document.");
break;
case LoadFormat.DOTX:
System.out.println("\tOffice Open XML WordprocessingML Macro-Free Template.");
break;
case LoadFormat.DOTM:
System.out.println("\tOffice Open XML WordprocessingML Macro-Enabled Template.");
break;
case LoadFormat.FLAT_OPC:
System.out.println("\tFlat OPC document.");
break;
case LoadFormat.RTF:
System.out.println("\tRTF format.");
break;
case LoadFormat.WORD_ML:
System.out.println("\tMicrosoft Word 2003 WordprocessingML format.");
break;
case LoadFormat.HTML:
System.out.println("\tHTML format.");
break;
case LoadFormat.MHTML:
System.out.println("\tMHTML (Web archive) format.");
break;
case LoadFormat.ODT:
System.out.println("\tOpenDocument Text.");
break;
case LoadFormat.OTT:
System.out.println("\tOpenDocument Text Template.");
break;
case LoadFormat.DOC_PRE_WORD_60:
System.out.println("\tMS Word 6 or Word 95 format.");
break;
case LoadFormat.UNKNOWN:
default:
System.out.println("\tUnknown format.");
break;
}
// Now copy the document into the appropriate folder.
if (info.isEncrypted()) {
System.out.println("\tAn encrypted document.");
fileCopy(fileName, new File(encryptedDir, nameOnly).getPath());
} else {
switch (info.getLoadFormat()) {
case LoadFormat.DOC_PRE_WORD_60:
fileCopy(fileName, new File(pre97Dir + nameOnly).getPath());
break;
case LoadFormat.UNKNOWN:
fileCopy(fileName, new File(unknownDir + nameOnly).getPath());
break;
default:
fileCopy(fileName, new File(supportedDir + nameOnly).getPath());
break;
}
}
}
private static void fileCopy(String sourceFileName, String destinationFileName) throws Exception {
File sourceFile = new File(sourceFileName);
File destinationFile = new File(destinationFileName);
File directoryFile = new File(destinationFile.getParent());
if (!directoryFile.exists())
directoryFile.mkdir();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(destinationFile);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1)
fos.write(buffer, 0, bytesRead);
} finally {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
File[] fileList = new File(dataDir).listFiles();
String dataDir = Utils.getSharedDataDir(ConvertADocumentToMHTMLAndEmail.class) + "LoadingSavingAndConverting/";
// Load the document into Aspose.Words.
String srcFileName = dataDir + "Document.doc";
Document doc = new Document(srcFileName);
// Save to an output stream in MHTML format.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
doc.save(outputStream, SaveFormat.MHTML);
// Load the MHTML stream back into an input stream for use with Aspose.Email.
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
// Create an Aspose.Email MIME email message from the stream.
MailMessage message = MailMessage.load(inputStream);
message.setFrom(new MailAddress("your_from@email.com"));
message.getTo().add("your_to@email.com");
message.setSubject("Aspose.Words + Aspose.Email MHTML Test Message");
// Save the message in Outlook MSG format.
message.save(dataDir + "Message Out.msg", SaveOptions.getDefaultMsg());
// Load the document.
Document doc = new Document(dataDir + "Test File (doc).doc");
// Create a new memory stream.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// Save the document to stream.
doc.save(outStream, SaveFormat.DOCX);
// Convert the document to byte form.
byte[] docBytes = outStream.toByteArray();
// The bytes are now ready to be stored/transmitted.
// Now reverse the steps to load the bytes back into a document object.
ByteArrayInputStream inStream = new ByteArrayInputStream(docBytes);
// Load the stream into a new document object.
Document loadDoc = new Document(inStream);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertDocumentToEPUB.class);
// Open an existing document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Save the document in EPUB format.
doc.save(dataDir + "Document.EpubConversion_out_.epub");
// 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(ConvertDocumentToEPUBUysingDefaultSaveOptions.class);
// Open an existing document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
// Specify the desired encoding.
saveOptions.setEncoding(Charset.forName("UTF-8"));
// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.setDocumentSplitCriteria(DocumentSplitCriteria.HEADING_PARAGRAPH);
// Specify that we want to export document properties.
saveOptions.setExportDocumentProperties(true);
// Specify that we want to save in EPUB format.
saveOptions.setSaveFormat(SaveFormat.EPUB);
// Export the document as an EPUB file.
doc.save(dataDir + "Document.EpubConversion_out_.epub", saveOptions);
// 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(ConvertDocumentToEPUBUysingDefaultSaveOptions.class);
// Open an existing document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
// Specify the desired encoding.
saveOptions.setEncoding(Charset.forName("UTF-8"));
// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.setDocumentSplitCriteria(DocumentSplitCriteria.HEADING_PARAGRAPH);
// Specify that we want to export document properties.
saveOptions.setExportDocumentProperties(true);
// Specify that we want to save in EPUB format.
saveOptions.setSaveFormat(SaveFormat.EPUB);
// Export the document as an EPUB file.
doc.save(dataDir + "Document.EpubConversion_out_.epub", saveOptions);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertDocumentToEPUBUysingDefaultSaveOptions.class);
// Open an existing document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
// Specify the desired encoding.
saveOptions.setEncoding(Charset.forName("UTF-8"));
// Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.setDocumentSplitCriteria(DocumentSplitCriteria.HEADING_PARAGRAPH);
// Specify that we want to export document properties.
saveOptions.setExportDocumentProperties(true);
// Specify that we want to save in EPUB format.
saveOptions.setSaveFormat(SaveFormat.EPUB);
// Export the document as an EPUB file.
doc.save(dataDir + "Document.EpubConversion_out_.epub", saveOptions);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertDocumentToHtmlWithRoundtrip.class);
// Load the document.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlSaveOptions options = new HtmlSaveOptions();
//HtmlSaveOptions.ExportRoundtripInformation property specifies
//whether to write the roundtrip information when saving to HTML, MHTML or EPUB.
//Default value is true for HTML and false for MHTML and EPUB.
options.setExportRoundtripInformation(true);
doc.save(dataDir + "ExportRoundtripInformation_out_.html", options);
doc = new Document(dataDir + "ExportRoundtripInformation_out_.html");
//Save the document Docx file format
doc.save(dataDir + "TestFile_out_.docx", SaveFormat.DOCX);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertDocumentToPCL.class);
// Load the document from disk.
Document doc = new Document(dataDir + "Document.doc");
PclSaveOptions saveOptions = new PclSaveOptions();
saveOptions.setSaveFormat(SaveFormat.PCL);
saveOptions.setRasterizeTransformedElements(false);
// Export the document as an PCL file.
doc.save(dataDir + "Document.PclConversion_out.pcl", saveOptions);
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
*/
String dataDir = Utils.getDataDir(ConvertImageToPdf.class);
String inputFileName = dataDir + "Test.bmp";
String outputFileName = dataDir + "output.pdf";
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the approriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++) {
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));
// Insert the image into the document and position it at the top left corner of the page.
builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
doc.save(outputFileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
*/
String dataDir = Utils.getDataDir(ConvertImageToPdf.class);
String inputFileName = dataDir + "Test.bmp";
String outputFileName = dataDir + "output.pdf";
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the approriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++) {
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));
// Insert the image into the document and position it at the top left corner of the page.
builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
doc.save(outputFileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Open an existing document from disk.
Document doc = new Document(dataDir + "Document.EpubConversion.doc");
// Create a new instance of HtmlSaveOptions. This object allows us to set
// options that control
// how the output document is saved.
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
// Specify the desired encoding.
saveOptions.setEncoding(Charset.forName("UTF-8"));
// Specify at what elements to split the internal HTML at. This creates a new
// HTML within the EPUB
// which allows you to limit the size of each HTML part. This is useful for
// readers which cannot read
// HTML files greater than a certain size e.g 300kb.
saveOptions.setDocumentSplitCriteria(DocumentSplitCriteria.HEADING_PARAGRAPH);
// Specify that we want to export document properties.
saveOptions.setExportDocumentProperties(true);
// Specify that we want to save in EPUB format.
saveOptions.setSaveFormat(SaveFormat.EPUB);
// Export the document as an EPUB file.
doc.save(dataDir + "Document.EpubConversion_out.epub", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Load the document.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlSaveOptions options = new HtmlSaveOptions();
// HtmlSaveOptions.ExportRoundtripInformation property specifies
// whether to write the roundtrip information when saving to HTML, MHTML or EPUB.
// Default value is true for HTML and false for MHTML and EPUB.
options.setExportRoundtripInformation(true);
doc.save(dataDir + "ExportRoundtripInformation_out.html", options);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Load the document
Document doc = new Document(dataDir + "Document.doc");
// Save to an output stream in MHTML format.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
doc.save(outputStream, SaveFormat.MHTML);
// Load the MHTML stream back into an input stream for use with Aspose.Email.
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
// Create an Aspose.Email MIME email message from the stream.
MailMessage message = MailMessage.load(inputStream);
message.setFrom(new MailAddress("your_from@email.com"));
message.getTo().add("your_to@email.com");
message.setSubject("Aspose.Words + Aspose.Email MHTML Test Message");
// Save the message in Outlook MSG format.
message.save(dataDir + "Message Out.msg", SaveOptions.getDefaultMsg());
// Send the message using Aspose.Email
SmtpClient client = new SmtpClient();
client.setHost("your_smtp.com");
client.send(message);
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (docx).docx");
// Save the document into HTML.
doc.save(dataDir + "Document_out.html", SaveFormat.HTML);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the document which is to be processed.
Document doc = new Document(dataDir + "Document.doc");
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setExportFontResources(true);
saveOptions.setExportFontsAsBase64(true);
doc.save(dataDir + "ExportFontsAsBase64_out.html", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the document which is to be processed.
Document doc = new Document(dataDir + "Document.doc");
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setCssStyleSheetType(CssStyleSheetType.EXTERNAL);
saveOptions.setExportFontResources(true);
saveOptions.setResourceFolder(dataDir + "\\Resources");
doc.save(dataDir + "ExportResourcesUsingHtmlSaveOptions_out.html", saveOptions);
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
* @throws Exception
*/
public static void ConvertImageToPDF(String inputFileName, String outputFileName) throws Exception {
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the appropriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++) {
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));
// Insert the image into the document and position it at the top left corner of the page.
builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
}
if (iis != null) {
iis.close();
reader.dispose();
}
doc.save(outputFileName);
}
// Load the document from disk.
Document doc = new Document(dataDir + "Template.doc");
// Save the document in PDF format.
dataDir = dataDir + "output.pdf";
doc.save(dataDir);
// Convert image in a specified format to PDF.
ConvertImageToPDF(dataDir + "Test.jpg", dataDir + "TestJpg_out.pdf");
ConvertImageToPDF(dataDir + "Test.tiff", dataDir + "TestTif_out.pdf");
// 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");
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectDocumentSignatures.class);
// The path to the document which is to be processed.
String filePath = dataDir + "Document.Signed.docx";
FileFormatInfo info = FileFormatUtil.detectFileFormat(filePath);
if (info.hasDigitalSignature())
{
System.out.println(java.text.MessageFormat.format(
"Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.",
new File(filePath).getName()));
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectDocumentSignatures.class);
// The path to the document which is to be processed.
String filePath = dataDir + "Document.Signed.docx";
FileFormatInfo info = FileFormatUtil.detectFileFormat(filePath);
System.out.println("The document format is: " + FileFormatUtil.loadFormatToExtension(info.getLoadFormat()));
System.out.println("Document is encrypted: " + info.isEncrypted());
System.out.println("Document has a digital signature: " + info.hasDigitalSignature());
// 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(DigitallySignedPdf.class);
// The path to the document which is to be processed.
String filePath = dataDir + "Document.Signed.docx";
Document doc = new Document();
FileFormatInfo info = FileFormatUtil.detectFileFormat(filePath);
if (info.hasDigitalSignature())
{
System.out.println(java.text.MessageFormat.format(
"Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.",
new File(filePath).getName()));
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(DigitallySignedPdf.class);
// The path to the document which is to be processed.
String filePath = dataDir + "Document.Signed.docx";
Document doc = new Document();
FileFormatInfo info = FileFormatUtil.detectFileFormat(filePath);
if (info.hasDigitalSignature())
{
System.out.println(java.text.MessageFormat.format(
"Document {0} has digital signatures, they will be lost if you open/save this document with Aspose.Words.",
new File(filePath).getName()));
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(DisplayDocTitleInWindowTitlebar.class);
// Load the document.
Document doc = new Document(dataDir + "Test File (doc).doc");
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.setDisplayDocTitle(true);
// Save the document in PDF format.
doc.save(dataDir + "Test File.Pdf",saveOptions);
// Load the document from disk.
Document doc = new Document(dataDir + "Template.doc");
// Save the document in PDF format.
dataDir = dataDir + "output.pdf";
doc.save(dataDir);
// The path to the document which is to be processed.
String filePath = dataDir + "Document.doc";
Document doc = new Document(filePath);
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setExportFontResources(true);
saveOptions.setExportFontsAsBase64(true);
doc.save(dataDir + "ExportFontsAsBase64_out.html", saveOptions);
// The path to the document which is to be processed.
String filePath = dataDir + "Document.doc";
Document doc = new Document(filePath);
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setCssStyleSheetType(CssStyleSheetType.EXTERNAL);
saveOptions.setExportFontResources(true);
saveOptions.setResourceFolder(dataDir + "\\Resources");
doc.save(dataDir + "ExportResourcesUsingHtmlSaveOptions_out.html", saveOptions);
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetListOfFilesInFolder.class);
String supportedDir = dataDir + "OutSupported" + File.separator;
String unknownDir = dataDir + "OutUnknown" + File.separator;
String encryptedDir = dataDir + "OutEncrypted" + File.separator;
String pre97Dir = dataDir + "OutPre97" + File.separator;
File[] fileList = new File(dataDir).listFiles();
// Loop through all found files.
for (File file : fileList) {
if (file.isDirectory())
continue;
// Extract and display the file name without the path.
String nameOnly = file.getName();
System.out.print(nameOnly);
}
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
*/
public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
{
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the approriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
try
{
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
{
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));
// Insert the image into the document and position it at the top left corner of the page.
builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
}
}
finally {
if (iis != null) {
iis.close();
reader.dispose();
}
}
// Save the document to PDF.
doc.save(outputFileName);
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(ImageToPdf.class);
convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg_out_.pdf");
convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng_out_.pdf");
convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp_out_.pdf");
convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif_out_.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
*/
String dataDir = Utils.getDataDir(ImageToPdfMethod.class);
String inputFileName = dataDir + "Test.bmp";
String outputFileName = dataDir + "output.pdf";
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the approriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++) {
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));
// Insert the image into the document and position it at the top left corner of the page.
builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
doc.save(outputFileName);
public static double[] CalculateImageSize(BufferedImage img, double containerHeight, double containerWidth, double targetHeight, double targetWidth) throws Exception {
targetHeight = containerHeight;
targetWidth = containerWidth;
//Get size of an image
double imgHeight = ConvertUtil.pixelToPoint(img.getHeight());
double imgWidth = ConvertUtil.pixelToPoint(img.getWidth());
if (imgHeight < targetHeight && imgWidth < targetWidth)
{
targetHeight = imgHeight;
targetWidth = imgWidth;
}
else
{
//Calculate size of an image in the document
double ratioWidth = imgWidth / targetWidth;
double ratioHeight = imgHeight / targetHeight;
if (ratioWidth > ratioHeight)
targetHeight = (targetHeight * (ratioHeight / ratioWidth));
else
targetWidth = (targetWidth * (ratioWidth / ratioHeight));
}
double[] size = new double[2];
size[0] = targetWidth; //width
size[1] = targetHeight; //height
return(size);
}
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
*/
public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
{
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the approriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
try
{
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
{
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// Max page size
double maxPageHeight = 1584;
double maxPageWidth = 1584;
double currentImageHeight = ConvertUtil.pixelToPoint(image.getHeight());
double currentImageWidth = ConvertUtil.pixelToPoint(image.getWidth());
if (currentImageWidth >= maxPageWidth || currentImageHeight >= maxPageHeight)
{
// Get max image size.
double[] size = CalculateImageSize(image, maxPageHeight, maxPageWidth, currentImageHeight, currentImageWidth);
currentImageWidth = size[0];
currentImageHeight = size[1];
}
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(currentImageWidth);
ps.setPageHeight(currentImageHeight);
// Insert the image into the document and position it at the top left corner of the page.
Shape shape = builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
resizeLargeImage(shape);
}
}
finally {
if (iis != null) {
iis.close();
reader.dispose();
}
}
// Save the document to PDF.
doc.save(outputFileName);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
/**
* Converts an image to PDF using Aspose.Words for Java.
*
* @param inputFileName File name of input image file.
* @param outputFileName Output PDF file name.
*/
public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
{
// Create Aspose.Words.Document and DocumentBuilder.
// The builder makes it simple to add content to the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Load images from the disk using the approriate reader.
// The file formats that can be loaded depends on the image readers available on the machine.
ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
ImageReader reader = ImageIO.getImageReaders(iis).next();
reader.setInput(iis, false);
try
{
// Get the number of frames in the image.
int framesCount = reader.getNumImages(true);
// Loop through all frames.
for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
{
// Insert a section break before each new page, in case of a multi-frame image.
if (frameIdx != 0)
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// Select active frame.
BufferedImage image = reader.read(frameIdx);
// Max page size
double maxPageHeight = 1584;
double maxPageWidth = 1584;
double currentImageHeight = ConvertUtil.pixelToPoint(image.getHeight());
double currentImageWidth = ConvertUtil.pixelToPoint(image.getWidth());
if (currentImageWidth >= maxPageWidth || currentImageHeight >= maxPageHeight)
{
// Get max image size.
double[] size = CalculateImageSize(image, maxPageHeight, maxPageWidth, currentImageHeight, currentImageWidth);
currentImageWidth = size[0];
currentImageHeight = size[1];
}
// We want the size of the page to be the same as the size of the image.
// Convert pixels to points to size the page to the actual image size.
PageSetup ps = builder.getPageSetup();
ps.setPageWidth(currentImageWidth);
ps.setPageHeight(currentImageHeight);
// Insert the image into the document and position it at the top left corner of the page.
Shape shape = builder.insertImage(
image,
RelativeHorizontalPosition.PAGE,
0,
RelativeVerticalPosition.PAGE,
0,
ps.getPageWidth(),
ps.getPageHeight(),
WrapType.NONE);
resizeLargeImage(shape);
}
}
finally {
if (iis != null) {
iis.close();
reader.dispose();
}
}
// Save the document to PDF.
doc.save(outputFileName);
}
public static double[] CalculateImageSize(BufferedImage img, double containerHeight, double containerWidth, double targetHeight, double targetWidth) throws Exception {
targetHeight = containerHeight;
targetWidth = containerWidth;
//Get size of an image
double imgHeight = ConvertUtil.pixelToPoint(img.getHeight());
double imgWidth = ConvertUtil.pixelToPoint(img.getWidth());
if (imgHeight < targetHeight && imgWidth < targetWidth)
{
targetHeight = imgHeight;
targetWidth = imgWidth;
}
else
{
//Calculate size of an image in the document
double ratioWidth = imgWidth / targetWidth;
double ratioHeight = imgHeight / targetHeight;
if (ratioWidth > ratioHeight)
targetHeight = (targetHeight * (ratioHeight / ratioWidth));
else
targetWidth = (targetWidth * (ratioWidth / ratioHeight));
}
double[] size = new double[2];
size[0] = targetWidth; //width
size[1] = targetHeight; //height
return(size);
}
public static void resizeLargeImage(Shape image) throws Exception {
// Return if this shape is not an image.
if (!image.hasImage())
return;
// Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
PageSetup ps = image.getParentParagraph().getParentSection().getPageSetup();
double freePageWidth = image.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
double freePageHeight = image.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();
// Is one of the sides of this image too big for the page?
ImageSize size = image.getImageData().getImageSize();
boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight;
if (exceedsMaxPageSize) {
// Calculate the ratio to fit the page size based on which side is longer.
boolean widthLonger = (size.getWidthPoints() > size.getHeightPoints());
double ratio = widthLonger ? freePageWidth / size.getWidthPoints() : freePageHeight / size.getHeightPoints();
// Set the new size.
image.setWidth(size.getWidthPoints() * ratio);
image.setHeight(size.getHeightPoints() * ratio);
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(ImageToPdf.class);
convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg_out_.pdf");
convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng_out_.pdf");
convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp_out_.pdf");
convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif_out_.pdf");
public static void resizeLargeImage(Shape image) throws Exception {
// Return if this shape is not an image.
if (!image.hasImage())
return;
// Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
PageSetup ps = image.getParentParagraph().getParentSection().getPageSetup();
double freePageWidth = image.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
double freePageHeight = image.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();
// Is one of the sides of this image too big for the page?
ImageSize size = image.getImageData().getImageSize();
boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight;
if (exceedsMaxPageSize) {
// Calculate the ratio to fit the page size based on which side is longer.
boolean widthLonger = (size.getWidthPoints() > size.getHeightPoints());
double ratio = widthLonger ? freePageWidth / size.getWidthPoints() : freePageHeight / size.getHeightPoints();
// Set the new size.
image.setWidth(size.getWidthPoints() * ratio);
image.setHeight(size.getHeightPoints() * ratio);
}
}
LoadOptions options = new LoadOptions();
options.setAnnotationsAtBlockLevel(true);
Document doc = new Document(dataDir + "AnnotationsAtBlockLevel.docx", options);
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag sdt = (StructuredDocumentTag)doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG, true).get(0);
BookmarkStart start = builder.startBookmark("bm");
BookmarkEnd end = builder.endBookmark("bm");
sdt.getParentNode().insertBefore(start, sdt);
sdt.getParentNode().insertAfter(end, sdt);
//Save the document into DOCX
doc.save(dataDir + "AnnotationsAtBlockLevel_out.docx", SaveFormat.DOCX);
LoadOptions lo = new LoadOptions();
lo.setConvertShapeToOfficeMath(true);
// Specify load option to use previous default behaviour i.e. convert math shapes to office math ojects on loading stage.
Document doc = new Document(dataDir + "OfficeMath.docx", lo);
//Save the document into DOCX
doc.save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.DOCX);
Document doc = new Document(dataDir + "encrypted.odt", new com.aspose.words.LoadOptions("password"));
doc.save(dataDir + "out.odt", new OdtSaveOptions("newpassword"));
LoadOptions lo = new LoadOptions();
//Update the fields with the dirty attribute
lo.setUpdateDirtyFields(true);
//Load the Word document
Document doc = new Document(dataDir + "input.docx", lo);
//Save the document into DOCX
dataDir = dataDir + "output.docx";
doc.save(dataDir, SaveFormat.DOCX);
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadAndSave.class);
String fileName = "Test File (doc).doc";
// Load the document from disk.
Document doc = new Document(dataDir + fileName);
// Save the finished document to disk.
doc.save(dataDir + "output.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
/**
* Utility function that creates a connection to the Database.
*/
public static void createConnection(String dataBasePath) throws Exception
{
// Load a DB driver that is used by the demos
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// The path to the database on the disk.
File dataBase = new File(dataBasePath);
// Compose connection string.
String connectionString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + dataBase + ";UID=Admin";
// Create a connection to the database.
mConnection = DriverManager.getConnection(connectionString);
}
/**
* Executes a query on the database.
*/
protected static ResultSet executeQuery(String query) throws Exception
{
return createStatement().executeQuery(query);
}
/**
* Creates a new database statement.
*/
public static Statement createStatement() throws Exception
{
return mConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void deleteFromDatabase(String fileName) throws Exception
{
// Create the SQL command.
String commandString = "DELETE * FROM Documents WHERE FileName='" + fileName + "'";
// Execute the command.
createStatement().executeUpdate(commandString);
}
// 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(LoadAndSaveDocToDatabase.class);
String fileName = "Test File (doc).doc";
// Load the document from disk.
Document doc = new Document(dataDir + "");
// Store the document to the database.
storeToDatabase(doc);
// Read the document from the database and store the file to disk.
Document dbDoc = readFromDatabase(fileName);
// Save the retrieved document to disk.
String newFileName = new File(fileName).getName() + " from DB" + fileName.substring(fileName.lastIndexOf("."));
dbDoc.save(dataDir + newFileName);
// Delete the document from the database.
deleteFromDatabase(fileName);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static Document readFromDatabase(String fileName) throws Exception
{
// Create the SQL command.
String commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
// Retrieve the results from the database.
ResultSet resultSet = executeQuery(commandString);
// Check there was a matching record found from the database and throw an exception if no record was found.
if(!resultSet.isBeforeFirst())
throw new IllegalArgumentException(MessageFormat.format("Could not find any record matching the document \"{0}\" in the database.", fileName));
// Move to the first record.
resultSet.next();
// The document is stored in byte form in the FileContent column.
// Retrieve these bytes of the first matching record to a new buffer.
byte[] buffer = resultSet.getBytes("FileContent");
// Wrap the bytes from the buffer into a new ByteArrayInputStream object.
ByteArrayInputStream newStream = new ByteArrayInputStream(buffer);
// Read the document from the input stream.
Document doc = new Document(newStream);
// Return the retrieved document.
return doc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void storeToDatabase(Document doc) throws Exception
{
// Save the document to a OutputStream object.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
doc.save(outputStream, SaveFormat.DOC);
// Get the filename from the document.
String fileName = new File(doc.getOriginalFileName()).getName();
// Create the SQL command.
String commandString = "INSERT INTO Documents (FileName, FileContent) VALUES(?, ?)";
// Prepare the statement to store the data into the database.
PreparedStatement statement = mConnection.prepareStatement(commandString);
// Add the parameter value for FileName.
statement.setString(1, fileName);
// Add the parameter value for FileContent.
statement.setBinaryStream(2, new ByteArrayInputStream(outputStream.toByteArray()), outputStream.size());
// Execute and commit the changes.
statement.execute();
mConnection.commit();
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static void DeleteFromDatabase(String fileName, Connection mConnection) throws Exception {
// Create the SQL command.
String commandString = "DELETE FROM Documents WHERE FileName='" + fileName + "'";
Statement statement = mConnection.createStatement();
// Delete the record.
statement.execute(commandString);
}
String url1 = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123";
// Open a database connection.
Connection mConnection = DriverManager.getConnection(url1, user, password);
// Store the document to the database.
StoreToDatabase(doc, mConnection);
// Read the document from the database and store the file to disk.
Document dbDoc = ReadFromDatabase(dataDir + fileName, mConnection);
// Save the retrieved document to disk.
dbDoc.save(dataDir + fileName);
// Delete the document from the database.
DeleteFromDatabase(dataDir + fileName, mConnection);
// Close the connection to the database.
mConnection.close();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static Document ReadFromDatabase(String fileName, Connection mConnection) throws Exception {
// Create the SQL command.
String commandString = "SELECT * FROM Documents WHERE FileName=?";
PreparedStatement statement = mConnection.prepareStatement(commandString);
statement.setString(1, fileName);
Document doc = null;
ResultSet result = statement.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("FileContent");
InputStream inputStream = blob.getBinaryStream();
doc = new Document(inputStream);
inputStream.close();
System.out.println("File saved");
}
result.close();
return doc;
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void StoreToDatabase(Document doc, Connection mConnection) throws Exception {
// Create an output stream which uses byte array to save data
ByteArrayOutputStream aout = new ByteArrayOutputStream();
// Save the document to byte array
doc.save(aout, SaveFormat.DOCX);
// Get the byte array from output steam
// the byte array now contains the document
byte[] buffer = aout.toByteArray();
// Get the filename from the document.
String fileName = doc.getOriginalFileName();
String filePath = fileName.replace("\\", "\\\\");
// Create the SQL command.
String commandString = "INSERT INTO Documents (FileName, FileContent) VALUES('" + filePath + "', '" + buffer
+ "')";
Statement statement = mConnection.createStatement();
statement.executeUpdate(commandString);
}
HtmlLoadOptions lo = new HtmlLoadOptions();
lo.setPreferredControlType(HtmlControlType.STRUCTURED_DOCUMENT_TAG);
//Load the HTML document
Document doc = new Document(dataDir + "input.html", lo);
//Save the HTML document as DOCX
doc.save(dataDir + "output.docx", SaveFormat.DOCX);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getSharedDataDir(ConvertADocumentToMHTMLAndEmail.class) + "LoadingSavingAndConverting/";
HtmlLoadOptions lo = new HtmlLoadOptions();
lo.PreferredControlType = HtmlControlType.StructuredDocumentTag;
//Load the HTML document
Document doc = new Document(dataDir + "input.html", lo);
//Save the HTML document as DOCX
doc.save(dataDir + "output.docx", SaveFormat.DOCX);
System.out.println("Html form fields are exported as content control successfully.");
// 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(LoadAndSaveToStream.class);
String inputFile = "Test File (doc).doc";
String outputFile = "output.png";
InputStream in = new FileInputStream(dataDir + inputFile);
OutputStream out = new FileOutputStream(dataDir + outputFile);
Document doc = new Document(in);
// Save the finished document to disk.
doc.save(out, SaveFormat.PNG);
System.out.println("Document loaded and saved successfully.");
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadAndSaveToStream.class);
String inputFile = "Test File (doc).doc";
String outputFile = "output.png";
InputStream in = new FileInputStream(dataDir + inputFile);
OutputStream out = new FileOutputStream(dataDir + outputFile);
Document doc = new Document(in);
// Save the finished document to disk.
doc.save(out, SaveFormat.PNG);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Retrieve the blob from database
byte[] buffer = new byte[100];
// Now we have the document in a byte array buffer
// Create an input steam which uses byte array to read data
ByteArrayInputStream bin = new ByteArrayInputStream(buffer);
// Open the doucment from input stream
//Document doc = new Document(bin);
// Retrieve the blob from database
byte[] buffer = new byte[100];
// Now we have the document in a byte array buffer
// Create an input steam which uses byte array to read data
ByteArrayInputStream bin = new ByteArrayInputStream(buffer);
// Open the doucment from input stream
Document doc = new Document(bin);
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadEncryptedDoc.class);
// Load the encrypted document from the absolute path on disk.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// 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(LoadEncryptedDoc.class);
// Load the encrypted document from the absolute path on disk.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadEncryptedDocument.class);
String filename = "LoadEncrypted.docx";
Document doc = new Document(dataDir + filename, new LoadOptions("aspose"));
doc.save(dataDir + "output.doc");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static class DocumentLoadingWarningCallback implements IWarningCallback {
public void warning(WarningInfo info) {
// Prints warnings and their details as they arise during document loading.
System.out.println("WARNING: " + info.getWarningType() + " source:" + info.getSource());
System.out.println("\tDescription: " + info.getDescription());
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static class HtmlLinkedResourceLoadingCallback implements IResourceLoadingCallback {
public int resourceLoading(ResourceLoadingArgs args) throws Exception {
switch (args.getResourceType()) {
case ResourceType.CSS_STYLE_SHEET: {
System.out.println("External CSS Stylesheet found upon loading: " + args.getOriginalUri());
// CSS file will don't used in the document
return ResourceLoadingAction.SKIP;
}
case ResourceType.IMAGE: {
// Replaces all images with a substitute
String newImageFilename = "Logo.jpg";
System.out.println("\tImage will be substituted with: " + newImageFilename);
BufferedImage newImage = ImageIO
.read(new File(Utils.getDataDir(LoadOptionsCallbacks.class) + newImageFilename));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newImage, "jpg", baos);
baos.flush();
byte[] imageBytes = baos.toByteArray();
baos.close();
args.setData(imageBytes);
// New images will be used instead of presented in the document
return ResourceLoadingAction.USER_PROVIDED;
}
case ResourceType.DOCUMENT: {
System.out.println("External document found upon loading: " + args.getOriginalUri());
// Will be used as usual
return ResourceLoadingAction.DEFAULT;
}
default:
throw new Exception("Unexpected ResourceType value.");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Create a new LoadOptions object and set its ResourceLoadingCallback attribute
// as an instance of our IResourceLoadingCallback implementation
LoadOptions loadOptions = new LoadOptions();
loadOptions.setResourceLoadingCallback(new HtmlLinkedResourceLoadingCallback());
// When we open an Html document, external resources such as references to CSS
// stylesheet files and external images
// will be handled in a custom manner by the loading callback as the document is
// loaded
Document doc = new Document(dataDir + "Images.html", loadOptions);
doc.save(dataDir + "Document.LoadOptionsCallback_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Create a new LoadOptions object and set its WarningCallback property.
LoadOptions loadOptions = new LoadOptions();
loadOptions.setWarningCallback(new DocumentLoadingWarningCallback());
Document doc = new Document(dataDir + "input.docx", loadOptions);
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadTxt.class);
// The encoding of the text file is automatically detected.
Document doc = new Document(dataDir + "LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
doc.save(dataDir + "output.docx");
// 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(LoadTxt.class);
// The encoding of the text file is automatically detected.
Document doc = new Document(dataDir + "LoadTxt.txt");
// Save as any Aspose.Words supported format, such as DOCX.
doc.save(dataDir + "output.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Load the encrypted document from the absolute path on disk.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// 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);
// 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();
// The path to the documents directory.
String dataDir = Utils.getDataDir(OpenDocUsingStream.class);
String filename = "Test.docx";
InputStream in = new FileInputStream(dataDir + filename);
Document doc = new Document(in);
// The path to the documents directory.
String dataDir = Utils.getDataDir(OpenEncryptedDoc.class);
// Load the encrypted document from the absolute path on disk.
Document doc = new Document(dataDir + "LoadEncrypted.docx", new LoadOptions("aspose"));
// 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(OpenEncryptedDocument.class);
String filename = "LoadEncrypted.docx";
Document doc = new Document(dataDir + filename , new LoadOptions("aspose"));
doc.save(dataDir +"output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(OpenEncryptedDocument.class);
String filename = "LoadEncrypted.docx";
Document doc = new Document(dataDir + filename , new LoadOptions("aspose"));
doc.save(dataDir +"output.doc");
// 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(OpenFile.class);
String filename = "Test.docx";
Document doc = new Document(dataDir + filename);
class DocumentPageSplitter
{
private PageNumberFinder pageNumberFinder;
/// <summary>
/// Initializes a new instance of the <see cref="DocumentPageSplitter"/> class.
/// This method splits the document into sections so that each page begins and ends at a section boundary.
/// It is recommended not to modify the document afterwards.
/// </summary>
/// <param name="source">source document</param>
public DocumentPageSplitter(Document source) throws Exception
{
this.pageNumberFinder = PageNumberFinderFactory.create(source);
}
/// <summary>
/// Gets the document this instance works with.
/// </summary>
private Document getDocument() {
return this.pageNumberFinder.getDocument();
}
/// <summary>
/// Gets the document of a page.
/// </summary>
/// <param name="pageIndex">
/// 1-based index of a page.
/// </param>
/// <returns>
/// The <see cref="Document"/>.
/// </returns>
public Document getDocumentOfPage(int pageIndex) throws Exception
{
return this.getDocumentOfPageRange(pageIndex, pageIndex);
}
/// <summary>
/// Gets the document of a page range.
/// </summary>
/// <param name="startIndex">
/// 1-based index of the start page.
/// </param>
/// <param name="endIndex">
/// 1-based index of the end page.
/// </param>
/// <returns>
/// The <see cref="Document"/>.
/// </returns>
public Document getDocumentOfPageRange(int startIndex, int endIndex) throws Exception
{
Document result = (Document) this.getDocument().deepClone(false);
for (Section section : (Iterable<Section>) this.pageNumberFinder.retrieveAllNodesOnPages(startIndex, endIndex, NodeType.SECTION))
{
result.appendChild(result.importNode(section, true));
}
return result;
}
}
class PageNumberFinder {
// Maps node to a start/end page numbers. This is used to override baseline page numbers provided by collector when document is split.
private Hashtable nodeStartPageLookup = new Hashtable();
private Hashtable nodeEndPageLookup = new Hashtable();
private LayoutCollector collector;
// Maps page number to a list of nodes found on that page.
private Hashtable reversePageLookup;
/// <summary>
/// Initializes a new instance of the <see cref="PageNumberFinder"/> class.
/// </summary>
/// <param name="collector">A collector instance which has layout model records for the document.</param>
public PageNumberFinder(LayoutCollector collector) {
this.collector = collector;
}
/// <summary>
/// Gets the document this instance works with.
/// </summary>
public Document getDocument() {
return this.collector.getDocument();
}
/// <summary>
/// Retrieves 1-based index of a page that the node begins on.
/// </summary>
/// <param name="node">
/// The node.
/// </param>
/// <returns>
/// Page index.
/// </returns>
public int getPage(Node node) throws Exception {
return this.nodeStartPageLookup.containsKey(node) ?
(Integer) this.nodeStartPageLookup.get(node) : this.collector.getStartPageIndex(node);
}
/// <summary>
/// Retrieves 1-based index of a page that the node ends on.
/// </summary>
/// <param name="node">
/// The node.
/// </param>
/// <returns>
/// Page index.
/// </returns>
public int getPageEnd(Node node) throws Exception {
return this.nodeEndPageLookup.containsKey(node) ?
(Integer) this.nodeEndPageLookup.get(node) :
this.collector.getEndPageIndex(node);
}
/// <summary>
/// Returns how many pages the specified node spans over. Returns 1 if the node is contained within one page.
/// </summary>
/// <param name="node">
/// The node.
/// </param>
/// <returns>
/// Page index.
/// </returns>
public int pageSpan(Node node) throws Exception {
return this.getPageEnd(node) - this.getPage(node) + 1;
}
/// <summary>
/// Returns a list of nodes that are contained anywhere on the specified page or pages which match the specified node type.
/// </summary>
/// <param name="startPage">
/// The start Page.
/// </param>
/// <param name="endPage">
/// The end Page.
/// </param>
/// <param name="nodeType">
/// The node Type.
/// </param>
/// <returns>
/// The <see cref="IList"/>.
/// </returns>
public ArrayList retrieveAllNodesOnPages(int startPage, int endPage, int nodeType) throws Exception {
if (startPage < 1 || startPage > this.getDocument().getPageCount()) {
throw new IllegalStateException("'startPage' is out of range");
}
if (endPage < 1 || endPage > this.getDocument().getPageCount() || endPage < startPage) {
throw new IllegalStateException("'endPage' is out of range");
}
this.checkPageListsPopulated();
ArrayList pageNodes = new ArrayList();
for (int page = startPage; page <= endPage; page++) {
// Some pages can be empty.
if (!this.reversePageLookup.containsKey(page)) {
continue;
}
for (Node node : (Iterable<Node>) this.reversePageLookup.get(page)) {
if (node.getParentNode() != null
&& (nodeType == NodeType.ANY || node.getNodeType() == nodeType)
&& !pageNodes.contains(node)) {
pageNodes.add(node);
}
}
}
return pageNodes;
}
/// <summary>
/// Splits nodes which appear over two or more pages into separate nodes so that they still appear in the same way
/// but no longer appear across a page.
/// </summary>
public void splitNodesAcrossPages() throws Exception {
for (Paragraph paragraph : (Iterable<Paragraph>) this.getDocument().getChildNodes(NodeType.PARAGRAPH, true)) {
if (this.getPage(paragraph) != this.getPageEnd(paragraph)) {
this.splitRunsByWords(paragraph);
}
}
this.clearCollector();
// Visit any composites which are possibly split across pages and split them into separate nodes.
this.getDocument().accept(new SectionSplitter(this));
}
/// <summary>
/// This is called by <see cref="SectionSplitter"/> to update page numbers of split nodes.
/// </summary>
/// <param name="node">
/// The node.
/// </param>
/// <param name="startPage">
/// The start Page.
/// </param>
/// <param name="endPage">
/// The end Page.
/// </param>
void addPageNumbersForNode(Node node, int startPage, int endPage) {
if (startPage > 0) {
this.nodeStartPageLookup.put(node, startPage);
}
if (endPage > 0) {
this.nodeEndPageLookup.put(node, endPage);
}
}
private static boolean isHeaderFooterType(Node node) {
return node.getNodeType() == NodeType.HEADER_FOOTER || node.getAncestor(NodeType.HEADER_FOOTER) != null;
}
private void checkPageListsPopulated() throws Exception {
if (this.reversePageLookup != null) {
return;
}
this.reversePageLookup = new Hashtable();
// Add each node to a list which represent the nodes found on each page.
for (Node node : (Iterable<Node>) this.getDocument().getChildNodes(NodeType.ANY, true)) {
// Headers/Footers follow sections. They are not split by themselves.
if (isHeaderFooterType(node)) {
continue;
}
int startPage = this.getPage(node);
int endPage = this.getPageEnd(node);
for (int page = startPage; page <= endPage; page++) {
if (!this.reversePageLookup.containsKey(page)) {
this.reversePageLookup.put(page, new ArrayList());
}
((ArrayList) this.reversePageLookup.get(page)).add(node);
}
}
}
private void splitRunsByWords(Paragraph paragraph) throws Exception {
for (Run run : paragraph.getRuns()) {
if (this.getPage(run) == this.getPageEnd(run)) {
continue;
}
this.splitRunByWords(run);
}
}
private void splitRunByWords(Run run) {
String[] words = run.getText().split(" ");
List<String> list = Arrays.asList(words);
Collections.reverse(list);
String[] reversedWords = (String[]) list.toArray();
for (String word : reversedWords) {
int pos = run.getText().length() - word.length() - 1;
if (pos > 1) {
splitRun(run, run.getText().length() - word.length() - 1);
}
}
}
/// <summary>
/// Splits text of the specified run into two runs.
/// Inserts the new run just after the specified run.
/// </summary>
private static Run splitRun(Run run, int position) {
Run afterRun = (Run) run.deepClone(true);
afterRun.setText(run.getText().substring(position));
run.setText(run.getText().substring(0, position));
run.getParentNode().insertAfter(afterRun, run);
return afterRun;
}
private void clearCollector() throws Exception {
this.collector.clear();
this.getDocument().updatePageLayout();
this.nodeStartPageLookup.clear();
this.nodeEndPageLookup.clear();
}
}
class PageNumberFinderFactory
{
/* Simulation of static class by using private constructor */
private PageNumberFinderFactory()
{}
public static PageNumberFinder create(Document document) throws Exception
{
LayoutCollector layoutCollector = new LayoutCollector(document);
document.updatePageLayout();
PageNumberFinder pageNumberFinder = new PageNumberFinder(layoutCollector);
pageNumberFinder.splitNodesAcrossPages();
return pageNumberFinder;
}
}
class SectionSplitter extends DocumentVisitor {
private PageNumberFinder pageNumberFinder;
public SectionSplitter(PageNumberFinder pageNumberFinder) {
this.pageNumberFinder = pageNumberFinder;
}
public int visitParagraphStart(Paragraph paragraph) throws Exception {
return this.continueIfCompositeAcrossPageElseSkip(paragraph);
}
public int visitTableStart(Table table) throws Exception {
return this.continueIfCompositeAcrossPageElseSkip(table);
}
public int visitRowStart(Row row) throws Exception {
return this.continueIfCompositeAcrossPageElseSkip(row);
}
public int visitCellStart(Cell cell) throws Exception{
return this.continueIfCompositeAcrossPageElseSkip(cell);
}
public int visitStructuredDocumentTagStart(StructuredDocumentTag sdt) throws Exception {
return this.continueIfCompositeAcrossPageElseSkip(sdt);
}
public int visitSmartTagStart(SmartTag smartTag) throws Exception {
return this.continueIfCompositeAcrossPageElseSkip(smartTag);
}
public int visitSectionStart(Section section) throws Exception {
Section previousSection = (Section) section.getPreviousSibling();
// If there is a previous section attempt to copy any linked header footers otherwise they will not appear in an
// extracted document if the previous section is missing.
if (previousSection != null) {
HeaderFooterCollection previousHeaderFooters = previousSection.getHeadersFooters();
if (!section.getPageSetup().getRestartPageNumbering()) {
section.getPageSetup().setRestartPageNumbering(true);
section.getPageSetup().setPageStartingNumber(previousSection.getPageSetup().getPageStartingNumber() + this.pageNumberFinder.pageSpan(previousSection));
}
for (HeaderFooter previousHeaderFooter : (Iterable<HeaderFooter>) previousHeaderFooters) {
if (section.getHeadersFooters().getByHeaderFooterType(previousHeaderFooter.getHeaderFooterType()) == null) {
HeaderFooter newHeaderFooter = (HeaderFooter) previousHeaderFooters.getByHeaderFooterType(previousHeaderFooter.getHeaderFooterType()).deepClone(true);
section.getHeadersFooters().add(newHeaderFooter);
}
}
}
return this.continueIfCompositeAcrossPageElseSkip(section);
}
public int visitSmartTagEnd(SmartTag smartTag) throws Exception {
this.splitComposite(smartTag);
return VisitorAction.CONTINUE;
}
public int visitStructuredDocumentTagEnd(StructuredDocumentTag sdt) throws Exception {
this.splitComposite(sdt);
return VisitorAction.CONTINUE;
}
public int visitCellEnd(Cell cell) throws Exception {
this.splitComposite(cell);
return VisitorAction.CONTINUE;
}
public int visitRowEnd(Row row) throws Exception {
this.splitComposite(row);
return VisitorAction.CONTINUE;
}
public int visitTableEnd(Table table) throws Exception {
this.splitComposite(table);
return VisitorAction.CONTINUE;
}
public int visitParagraphEnd(Paragraph paragraph) throws Exception {
// If paragraph contains only section break, add fake run into
if (paragraph.isEndOfSection() && paragraph.getChildNodes().getCount() == 1 && "\f".equals(paragraph.getChildNodes().get(0).getText())) {
Run run = new Run(paragraph.getDocument());
paragraph.appendChild(run);
int currentEndPageNum = this.pageNumberFinder.getPageEnd(paragraph);
this.pageNumberFinder.addPageNumbersForNode(run, currentEndPageNum, currentEndPageNum);
}
for (Paragraph clonePara : (Iterable<Paragraph>) splitComposite(paragraph)) {
// Remove list numbering from the cloned paragraph but leave the indent the same
// as the paragraph is supposed to be part of the item before.
if (paragraph.isListItem()) {
double textPosition = clonePara.getListFormat().getListLevel().getTextPosition();
clonePara.getListFormat().removeNumbers();
clonePara.getParagraphFormat().setLeftIndent(textPosition);
}
// Reset spacing of split paragraphs in tables as additional spacing may cause them to look different.
if (paragraph.isInCell()) {
clonePara.getParagraphFormat().setSpaceBefore(0);
paragraph.getParagraphFormat().setSpaceAfter(0);
}
}
return VisitorAction.CONTINUE;
}
public int visitSectionEnd(Section section) throws Exception {
for (Section cloneSection : (Iterable<Section>) this.splitComposite(section)) {
cloneSection.getPageSetup().setSectionStart(SectionStart.NEW_PAGE);
cloneSection.getPageSetup().setRestartPageNumbering(true);
cloneSection.getPageSetup().setPageStartingNumber(section.getPageSetup().getPageStartingNumber() +
(section.getDocument().indexOf(cloneSection) - section.getDocument().indexOf(section)));
cloneSection.getPageSetup().setDifferentFirstPageHeaderFooter(false);
// corrects page break on end of the section
SplitPageBreakCorrector.processSection(cloneSection);
}
// corrects page break on end of the section
SplitPageBreakCorrector.processSection(section);
// Add new page numbering for the body of the section as well.
this.pageNumberFinder.addPageNumbersForNode(section.getBody(), this.pageNumberFinder.getPage(section), this.pageNumberFinder.getPageEnd(section));
return VisitorAction.CONTINUE;
}
private int continueIfCompositeAcrossPageElseSkip(CompositeNode composite) throws Exception {
return (this.pageNumberFinder.pageSpan(composite) > 1) ? VisitorAction.CONTINUE : VisitorAction.SKIP_THIS_NODE;
}
private ArrayList splitComposite(CompositeNode composite) throws Exception {
ArrayList splitNodes = new ArrayList</* unknown Type use JavaGenericArguments */>();
for (Node splitNode : (Iterable<Node>) this.findChildSplitPositions(composite)) {
splitNodes.add(this.splitCompositeAtNode(composite, splitNode));
}
return splitNodes;
}
private ArrayList findChildSplitPositions(CompositeNode node) throws Exception {
// A node may span across multiple pages so a list of split positions is returned.
// The split node is the first node on the next page.
ArrayList splitList = new ArrayList();
int startingPage = this.pageNumberFinder.getPage(node);
Node[] childNodes = node.getNodeType() == NodeType.SECTION
? ((Section) node).getBody().getChildNodes().toArray()
: node.getChildNodes().toArray();
for (Node childNode : childNodes) {
int pageNum = this.pageNumberFinder.getPage(childNode);
if (childNode instanceof Run) {
pageNum = this.pageNumberFinder.getPageEnd(childNode);
}
// If the page of the child node has changed then this is the split position. Add
// this to the list.
if (pageNum > startingPage) {
splitList.add(childNode);
startingPage = pageNum;
}
if (this.pageNumberFinder.pageSpan(childNode) > 1) {
this.pageNumberFinder.addPageNumbersForNode(childNode, pageNum, pageNum);
}
}
// Split composites backward so the cloned nodes are inserted in the right order.
Collections.reverse(splitList);
return splitList;
}
private CompositeNode splitCompositeAtNode(CompositeNode baseNode, Node targetNode) throws Exception {
CompositeNode cloneNode = (CompositeNode) baseNode.deepClone(false);
Node node = targetNode;
int currentPageNum = this.pageNumberFinder.getPage(baseNode);
// Move all nodes found on the next page into the copied node. Handle row nodes separately.
if (baseNode.getNodeType() != NodeType.ROW) {
CompositeNode composite = cloneNode;
if (baseNode.getNodeType() == NodeType.SECTION) {
cloneNode = (CompositeNode) baseNode.deepClone(true);
Section section = (Section) cloneNode;
section.getBody().removeAllChildren();
composite = section.getBody();
}
while (node != null) {
Node nextNode = node.getNextSibling();
composite.appendChild(node);
node = nextNode;
}
} else {
// If we are dealing with a row then we need to add in dummy cells for the cloned row.
int targetPageNum = this.pageNumberFinder.getPage(targetNode);
Node[] childNodes = baseNode.getChildNodes().toArray();
for (Node childNode : childNodes) {
int pageNum = this.pageNumberFinder.getPage(childNode);
if (pageNum == targetPageNum) {
cloneNode.getLastChild().remove();
cloneNode.appendChild(childNode);
} else if (pageNum == currentPageNum) {
cloneNode.appendChild(childNode.deepClone(false));
if (cloneNode.getLastChild().getNodeType() != NodeType.CELL) {
((CompositeNode) cloneNode.getLastChild()).appendChild(((CompositeNode) childNode).getFirstChild().deepClone(false));
}
}
}
}
// Insert the split node after the original.
baseNode.getParentNode().insertAfter(cloneNode, baseNode);
// Update the new page numbers of the base node and the clone node including its descendents.
// This will only be a single page as the cloned composite is split to be on one page.
int currentEndPageNum = this.pageNumberFinder.getPageEnd(baseNode);
this.pageNumberFinder.addPageNumbersForNode(baseNode, currentPageNum, currentEndPageNum - 1);
this.pageNumberFinder.addPageNumbersForNode(cloneNode, currentEndPageNum, currentEndPageNum);
for (Node childNode : (Iterable<Node>) cloneNode.getChildNodes(NodeType.ANY, true)) {
this.pageNumberFinder.addPageNumbersForNode(childNode, currentEndPageNum, currentEndPageNum);
}
return cloneNode;
}
}
class SplitPageBreakCorrector
{
private static final String PAGE_BREAK_STR = "\f";
private static final char PAGE_BREAK = '\f';
public static void processSection(Section section)
{
if (section.getChildNodes().getCount() == 0)
{
return;
}
Body lastBody = section.getBody();
if (lastBody == null)
{
return;
}
Run run = null;
for(Run r : (Iterable<Run>) lastBody.getChildNodes(NodeType.RUN, true)){
if (r.getText().endsWith(PAGE_BREAK_STR)) {
run = r;
break;
}
}
if (run != null)
{
removePageBreak(run);
}
return;
}
public static void removePageBreakFromParagraph(Paragraph paragraph)
{
Run run = (Run)paragraph.getFirstChild();
if (run.getText().equals(PAGE_BREAK_STR))
{
paragraph.removeChild(run);
}
}
private static void processLastParagraph(Paragraph paragraph)
{
Node lastNode = paragraph.getChildNodes().get(paragraph.getChildNodes().getCount() - 1);
if (lastNode.getNodeType() != NodeType.RUN)
{
return;
}
Run run = (Run)lastNode;
removePageBreak(run);
}
private static void removePageBreak(Run run)
{
Paragraph paragraph = run.getParentParagraph();
if (run.getText().equals(PAGE_BREAK_STR))
{
paragraph.removeChild(run);
}
else if (run.getText().endsWith(PAGE_BREAK_STR))
{
run.setText(run.getText().replaceAll("[" + PAGE_BREAK + "]+$", ""));
}
if (paragraph.getChildNodes().getCount() == 0)
{
CompositeNode parent = paragraph.getParentNode();
parent.removeChild(paragraph);
}
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(PageSplitter.class);
SplitAllDocumentsToPages(dataDir);
public static void SplitAllDocumentsToPages(String folderName) throws Exception
{
File[] files = new File(folderName).listFiles();
for (File file : files) {
if (file.isFile()) {
SplitDocumentToPages(file);
}
}
}
public static void SplitDocumentToPages(File docName) throws Exception
{
String folderName = docName.getParent();
String fileName = docName.getName();
String extensionName = fileName.substring(fileName.lastIndexOf("."));
String outFolder = new File(folderName, "Out").getAbsolutePath();
System.out.println("Processing document: " + fileName );
Document doc = new Document(docName.getAbsolutePath());
// Split nodes in the document into separate pages.
DocumentPageSplitter splitter = new DocumentPageSplitter(doc);
// Save each page to the disk as a separate document.
for (int page = 1; page <= doc.getPageCount(); page++)
{
Document pageDoc = splitter.getDocumentOfPage(page);
pageDoc.save(new File(outFolder, MessageFormat.format("{0} - page{1} Out{2}", fileName, page, extensionName)).getAbsolutePath());
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Create a new empty document
Document doc = new Document();
// Create an output stream which uses byte array to save data
ByteArrayOutputStream aout = new ByteArrayOutputStream();
// Save the document to byte array
doc.save(aout, SaveFormat.DOCX);
// Get the byte array from output steam
// the byte array now contains the document
byte[] buffer = aout.toByteArray();
// Save the document to database blob
// Create a new empty document
Document doc = new Document();
// Create an output stream which uses byte array to save data
ByteArrayOutputStream aout = new ByteArrayOutputStream();
// Save the document to byte array
doc.save(aout, SaveFormat.DOCX);
// Get the byte array from output steam
// the byte array now contains the document
byte[] buffer = aout.toByteArray();
// Save the document to database blob
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Here is an SVG image: ");
builder.insertHtml("<svg height='210' width='500'> <polygon points='100,10 40,198 190,78 10,78 160,198' style='fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;' /></svg> ");
HtmlSaveOptions options = new HtmlSaveOptions();
options.setMetafileFormat(HtmlMetafileFormat.SVG);
dataDir = dataDir + "ExportSVGinHTML_out.html";
doc.save(dataDir, options);
Document doc = new Document(dataDir + "Document.docx");
HtmlSaveOptions options = new HtmlSaveOptions();
options.setMetafileFormat(HtmlMetafileFormat.EMF_OR_WMF);
dataDir = dataDir + "SaveHtmlWithMetafileFormat_out.html";
doc.save(dataDir, options);
Document doc = new Document(dataDir + "Document.docx");
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setCssStyleSheetType(CssStyleSheetType.EXTERNAL);
saveOptions.setCssClassNamePrefix("pfx_");
dataDir = dataDir + "CssClassNamePrefix_out.html";
doc.save(dataDir, saveOptions);
Document doc = new Document(dataDir + "CidUrls.docx");
HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.MHTML);
saveOptions.setPrettyFormat(true);
saveOptions.setExportCidUrlsForMhtmlResources(true);
dataDir = dataDir + "SetExportCidUrlsForMhtmlResources_out.mhtml";
doc.save(dataDir, saveOptions);
Document doc = new Document(dataDir + "Test File (docx).docx");
HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.HTML);
saveOptions.setPrettyFormat(true);
saveOptions.setResolveFontNames(true);
dataDir = dataDir + "ResolveFontNames_out.html";
doc.save(dataDir, saveOptions);
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlFixedSaveOptions options = new HtmlFixedSaveOptions();
options.setUseTargetMachineFonts(true);
dataDir = dataDir + "Test File_out.html";
// Save the document to disk.
doc.save(dataDir, options);
// Load the document from disk.
Document doc = new Document(dataDir + "Test File (doc).doc");
HtmlFixedSaveOptions options = new HtmlFixedSaveOptions();
//Setting this property to true restores the old behavior (separate files) for compatibility with legacy code.
//Default value is false.
//All CSS rules are written into single file "styles.css
options.setSaveFontFaceCssSeparately(false);
dataDir = dataDir + "WriteAllCSSrulesinSingleFile_out.html";
// Save the document to disk.
doc.save(dataDir, options);
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("button") != null) {
// Get the output format selected by the user.
String formatType = "PDF";
Boolean openNewWindow = false;
try {
com.aspose.words.Document doc = new com.aspose.words.Document(MyDir+"Test File.docx");
String fileName = "outDocument"+"."+ formatType;
response.setContentType("application/pdf");
// Add the Response header
if (openNewWindow)
response.setHeader("content-disposition","attachment; filename=" + fileName);
else
response.addHeader("content-disposition","inline; filename=" + fileName);
doc.save(response.getOutputStream(),com.aspose.words.SaveFormat.PDF);
response.flushBuffer();
System.out.println("Process Completed Successfully");
} catch (Exception e) {
throw new RuntimeException("Process failed: " + e.getMessage());
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Specify LoadOptions to add Editing Language
LoadOptions loadOptions = new LoadOptions();
loadOptions.getLanguagePreferences().addEditingLanguage(EditingLanguage.JAPANESE);
Document doc = new Document(dataDir + "languagepreferences.docx", loadOptions);
int localeIdFarEast = doc.getStyles().getDefaultFont().getLocaleIdFarEast();
if (localeIdFarEast == (int) EditingLanguage.JAPANESE)
System.out.println("The document either has no any FarEast language set in defaults or it was set to Japanese originally.");
else
System.out.println("The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Specify LoadOptions to set Default Editing Language
LoadOptions loadOptions = new LoadOptions();
loadOptions.getLanguagePreferences().setDefaultEditingLanguage(EditingLanguage.RUSSIAN);
Document doc = new Document(dataDir + "languagepreferences.docx", loadOptions);
int localeId = doc.getStyles().getDefaultFont().getLocaleId();
if (localeId == (int) EditingLanguage.RUSSIAN)
System.out.println("The document either has no any language set in defaults or it was set to Russian originally.");
else
System.out.println("The document default language was set to another than Russian language originally, so it is not overridden.");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
LoadOptions lo = new LoadOptions();
lo.setConvertShapeToOfficeMath(true);
// Specify load option to use previous default behaviour i.e. convert math
// shapes to office math ojects on loading stage.
Document doc = new Document(dataDir + "OfficeMath.docx", lo);
// Save the document into DOCX
doc.save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.DOCX);
Document doc = new Document(dataDir + "encrypted.odt", new com.aspose.words.LoadOptions("password"));
doc.save(dataDir + "out.odt", new OdtSaveOptions("newpassword"));
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Set the Encoding attribute in a LoadOptions object to override the
// automatically chosen encoding with the one we know to be correct
LoadOptions loadOptions = new LoadOptions();
loadOptions.setEncoding(java.nio.charset.Charset.forName("UTF-8"));
Document doc = new Document(dataDir + "Encoded in UTF-8.txt", loadOptions);
LoadOptions lo = new LoadOptions();
// Update the fields with the dirty attribute
lo.setUpdateDirtyFields(true);
// Load the Word document
Document doc = new Document(dataDir + "input.docx", lo);
// Save the document into DOCX
dataDir = dataDir + "output.docx";
doc.save(dataDir, SaveFormat.DOCX);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Specify load option to specify MS Word version
LoadOptions loadOptions = new LoadOptions();
loadOptions.setMswVersion(MsWordVersion.WORD_2003);
Document doc = new Document(dataDir + "document.doc", loadOptions);
doc.save(dataDir + "Word2003_out.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Specify LoadOptions to set Temp Folder
LoadOptions lo = new LoadOptions();
lo.setTempFolder("C:\\TempFolder\\");
Document doc = new Document(dataDir + "document.doc", lo);
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "encrypted.odt");
System.out.println(info.isEncrypted());
// The path to the documents directory.
String dataDir = Utils.getDataDir(SpecifySaveOption.class);
String fileName = "TestFile RenderShape.docx";
// Load the document.
Document doc = new Document(dataDir + fileName);
// This is the directory we want the exported images to be saved to.
File imagesDir = new File(dataDir, "Images");
// The folder specified needs to exist and should be empty.
if(imagesDir.exists())
imagesDir.delete();
imagesDir.mkdir();
// Set an option to export form fields as plain text, not as HTML input elements.
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.HTML);
options.setExportTextInputFormFieldAsText(true);
options.setImagesFolder(imagesDir.getPath());
dataDir = dataDir + Utils.GetOutputFilePath(fileName);
doc.save(dataDir, options);
/**
* A custom data source for Aspose.Words mail merge.
* Returns topic objects.
*/
class TocMailMergeDataSource implements IMailMergeDataSource
{
TocMailMergeDataSource(ArrayList topics) throws Exception
{
mTopics = topics;
// Initialize to BOF.
mIndex = -1;
}
public boolean moveNext() throws Exception
{
if (mIndex < mTopics.size() - 1)
{
mIndex++;
return true;
}
else
{
// Reached EOF, return false.
return false;
}
}
@Override
public boolean getValue(String fieldName, Ref<Object> fieldValue) throws Exception
{
if ("TocEntry".equals(fieldName))
{
// The template document is supposed to have only one field called "TocEntry".
fieldValue.set(mTopics.get(mIndex));
return true;
}
else
{
fieldValue.set(null);
return false;
}
}
public String getTableName() throws Exception { return "TOC"; }
public IMailMergeDataSource getChildDataSource(String tableName) throws Exception
{
return null;
}
private final ArrayList mTopics;
private int mIndex;
}
/**
* A simple class to hold a topic title and HTML file name together.
*/
class Topic
{
Topic(String title, String fileName) throws Exception
{
mTitle = title;
mFileName = fileName;
}
String getTitle() throws Exception { return mTitle; }
String getFileName() throws Exception { return mFileName; }
private final String mTitle;
private final String mFileName;
}
/**
*This class takes a Microsoft Word document, splits it into topics at paragraphs formatted
* with the Heading 1 style and saves every topic as an HTML file.
*
* Also generates contents.html file that provides links to all saved topics.
*/
class Worker
{
/**
* Performs the Word to HTML conversion.
*
* @param srcFileName The MS Word file to convert.
* @param tocTemplate An MS Word file that is used as a template to build
* a table of contents. This file needs to have a mail merge region called "TOC" defined
* and one mail merge field called "TocEntry".
* @param dstDir The output directory where to write HTML files. Must exist.
*/
void execute(String srcFileName, String tocTemplate, String dstDir) throws Exception
{
mDoc = new Document(srcFileName);
mTocTemplate = tocTemplate;
mDstDir = dstDir;
ArrayList topicStartParas = selectTopicStarts();
insertSectionBreaks(topicStartParas);
ArrayList topics = saveHtmlTopics();
saveTableOfContents(topics);
}
/**
* Selects heading paragraphs that must become topic starts.
* We can't modify them in this loop, we have to remember them in an array first.
*/
private ArrayList selectTopicStarts() throws Exception
{
NodeCollection paras = mDoc.getChildNodes(NodeType.PARAGRAPH, true);
ArrayList topicStartParas = new ArrayList();
for (Paragraph para : (Iterable<Paragraph>) paras)
{
int style = para.getParagraphFormat().getStyleIdentifier();
if (style == StyleIdentifier.HEADING_1)
topicStartParas.add(para);
}
return topicStartParas;
}
/**
* Inserts section breaks before the specified paragraphs.
*/
private void insertSectionBreaks(ArrayList topicStartParas) throws Exception
{
DocumentBuilder builder = new DocumentBuilder(mDoc);
for (Paragraph para : (Iterable<Paragraph>) topicStartParas)
{
Section section = para.getParentSection();
// Insert section break if the paragraph is not at the beginning of a section already.
if (para != section.getBody().getFirstParagraph())
{
builder.moveTo(para.getFirstChild());
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// This is the paragraph that was inserted at the end of the now old section.
// We don't really need the extra paragraph, we just needed the section.
section.getBody().getLastParagraph().remove();
}
}
}
/**
* Splits the current document into one topic per section and saves each topic
* as an HTML file. Returns a collection of Topic objects.
*/
private ArrayList saveHtmlTopics() throws Exception
{
ArrayList topics = new ArrayList();
for (int sectionIdx = 0; sectionIdx < mDoc.getSections().getCount(); sectionIdx++)
{
Section section = mDoc.getSections().get(sectionIdx);
String paraText = section.getBody().getFirstParagraph().getText();
// The text of the heading paragaph is used to generate the HTML file name.
String fileName = makeTopicFileName(paraText);
if ("".equals(fileName))
fileName = "UNTITLED SECTION " + sectionIdx;
fileName = new File(mDstDir, fileName + ".html").getPath();
// The text of the heading paragraph is also used to generate the title for the TOC.
String title = makeTopicTitle(paraText);
if ("".equals(title))
title = "UNTITLED SECTION " + sectionIdx;
Topic topic = new Topic(title, fileName);
topics.add(topic);
saveHtmlTopic(section, topic);
}
return topics;
}
/**
* Leaves alphanumeric characters, replaces white space with underscore
* and removes all other characters from a string.
*/
private static String makeTopicFileName(String paraText) throws Exception
{
StringBuilder b = new StringBuilder();
for (int i = 0; i < paraText.length(); i++)
{
char c = paraText.charAt(i);
if (Character.isLetterOrDigit(c))
b.append(c);
else if (c == ' ')
b.append('_');
}
return b.toString();
}
/**
* Removes the last character (which is a paragraph break character from the given string).
*/
private static String makeTopicTitle(String paraText) throws Exception
{
return paraText.substring((0), (0) + (paraText.length() - 1));
}
/**
* Saves one section of a document as an HTML file.
* Any embedded images are saved as separate files in the same folder as the HTML file.
*/
private static void saveHtmlTopic(Section section, Topic topic) throws Exception
{
Document dummyDoc = new Document();
dummyDoc.removeAllChildren();
dummyDoc.appendChild(dummyDoc.importNode(section, true, ImportFormatMode.KEEP_SOURCE_FORMATTING));
dummyDoc.getBuiltInDocumentProperties().setTitle(topic.getTitle());
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setPrettyFormat(true);
// This is to allow headings to appear to the left of main text.
saveOptions.setAllowNegativeIndent(true);
saveOptions.setExportHeadersFootersMode(ExportHeadersFootersMode.NONE);
dummyDoc.save(topic.getFileName(), saveOptions);
}
/**
* Generates a table of contents for the topics and saves to contents.html.
*/
private void saveTableOfContents(ArrayList topics) throws Exception
{
Document tocDoc = new Document(mTocTemplate);
// We use a custom mail merge even handler defined below.
tocDoc.getMailMerge().setFieldMergingCallback(new HandleTocMergeField());
// We use a custom mail merge data source based on the collection of the topics we created.
tocDoc.getMailMerge().executeWithRegions(new TocMailMergeDataSource(topics));
tocDoc.save(new File(mDstDir, "contents.html").getPath());
}
private class HandleTocMergeField implements IFieldMergingCallback
{
public void fieldMerging(FieldMergingArgs e) throws Exception
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.getDocument());
// Our custom data source returns topic objects.
Topic topic = (Topic)e.getFieldValue();
// We use the document builder to move to the current merge field and insert a hyperlink.
mBuilder.moveToMergeField(e.getFieldName());
mBuilder.insertHyperlink(topic.getTitle(), topic.getFileName(), false);
// Signal to the mail merge engine that it does not need to insert text into the field
// as we've done it already.
e.setText("");
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
{
// Do nothing.
}
private DocumentBuilder mBuilder;
}
private Document mDoc;
private String mTocTemplate;
private String mDstDir;
}
/**
* Central storage for regular expressions used in the project.
*/
class RegularExpressions
{
// This class is static. No instance creation is allowed.
private RegularExpressions() throws Exception {}
/**
* Regular expression specifying html title (framing tags excluded).
*/
public static Pattern getHtmlTitle() throws Exception
{
if (gHtmlTitle == null)
{
gHtmlTitle = Pattern.compile(HTML_TITLE_PATTERN,
Pattern.CASE_INSENSITIVE);
}
return gHtmlTitle;
}
/**
* Regular expression specifying html head.
*/
public static Pattern getHtmlHead() throws Exception
{
if (gHtmlHead == null)
{
gHtmlHead = Pattern.compile(HTML_HEAD_PATTERN,
Pattern.CASE_INSENSITIVE);
}
return gHtmlHead;
}
/**
* Regular expression specifying space right after div keyword in the first div declaration of html body.
*/
public static Pattern getHtmlBodyDivStart() throws Exception
{
if (gHtmlBodyDivStart == null)
{
gHtmlBodyDivStart = Pattern.compile(HTML_BODY_DIV_START_PATTERN,
Pattern.CASE_INSENSITIVE);
}
return gHtmlBodyDivStart;
}
private static final String HTML_TITLE_PATTERN = "(?<=\\<title\\>).*?(?=\\</title\\>)";
private static Pattern gHtmlTitle;
private static final String HTML_HEAD_PATTERN = "\\<head\\>.*?\\</head\\>";
private static Pattern gHtmlHead;
private static final String HTML_BODY_DIV_START_PATTERN = "(?<=\\<body\\>\\s{0,200}\\<div)\\s";
private static Pattern gHtmlBodyDivStart;
}
/**
* This is the main class.
* Loads Word document(s), splits them into topics, saves HTML files and builds content.xml.
*/
class TopicCollection
{
/**
* Ctor.
*
* @param htmlTemplatesDir The directory that contains header.html, banner.html and footer.html files.
*
* @param fixUrl The url that will be removed from any hyperlinks that start with this url.
* This allows turning some absolute URLS into relative ones.
*/
public TopicCollection(String htmlTemplatesDir, String fixUrl) throws Exception
{
mTopics = new ArrayList();
mFixUrl = fixUrl;
mHtmlHeader = readFile(htmlTemplatesDir + "header.html");
mHtmlBanner = readFile(htmlTemplatesDir + "banner.html");
mHtmlFooter = readFile(htmlTemplatesDir + "footer.html");
}
/**
* Processes all DOC files found in the specified directory.
* Loads and splits each document into separate topics.
*/
public void addFromDir(String dirName) throws Exception
{
FilenameFilter fileFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".doc");
}
};
for (File filename : new File(dirName).listFiles(fileFilter))
addFromFile(filename.getAbsolutePath());
}
/**
* Processes a specified DOC file. Loads and splits into topics.
*/
public void addFromFile(String fileName) throws Exception
{
Document doc = new Document(fileName);
insertTopicSections(doc);
addTopics(doc);
}
/**
* Saves all topics as HTML files.
*/
public void writeHtml(String outDir) throws Exception
{
for (TopicWord2Help topic : (Iterable<TopicWord2Help>) mTopics)
{
if (!topic.isHeadingOnly())
topic.writeHtml(mHtmlHeader, mHtmlBanner, mHtmlFooter, outDir);
}
}
/**
* Saves the content.xml file that describes the tree of topics.
*/
public void writeContentXml(String outDir) throws Exception
{
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder parser = fact.newDocumentBuilder();
org.w3c.dom.Document doc = parser.newDocument();
Element root = doc.createElement("content");
root.setAttribute("dir", outDir);
doc.appendChild(root);
Element currentElement = root;
for (int i = 0; i < mTopics.size(); i++)
{
TopicWord2Help topic = (TopicWord2Help)mTopics.get(i);
int nextTopicIdx = i + 1;
TopicWord2Help nextTopic = (nextTopicIdx < mTopics.size()) ? (TopicWord2Help)mTopics.get(i + 1) : null;
int nextHeadingLevel = (nextTopic != null) ? nextTopic.getHeadingLevel() : 0;
if (nextHeadingLevel > topic.getHeadingLevel())
{
// Next topic is nested, therefore we have to start a book.
// We only allow increase level at a time.
if (nextHeadingLevel != topic.getHeadingLevel() + 1)
throw new Exception("Topic is nested for more than one level at a time. Title: " + topic.getTitle());
currentElement = writeBookStart(currentElement, topic);
}
else if (nextHeadingLevel < topic.getHeadingLevel())
{
// Next topic is one or more levels higher in the outline.
// Write out the current topic.
writeItem(currentElement, topic.getTitle(), topic.getFileName());
// End one or more nested topics could have ended at this point.
int levelsToClose = topic.getHeadingLevel() - nextHeadingLevel;
while (levelsToClose > 0)
{
currentElement = (Element)currentElement.getParentNode();
levelsToClose--;
}
}
else
{
// A topic at the current level and it has no children.
writeItem(currentElement, topic.getTitle(), topic.getFileName());
}
}
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = new File(outDir, "content.xml");
FileOutputStream outputStream = new FileOutputStream(file.getAbsolutePath());
StreamResult result = new StreamResult(new OutputStreamWriter(outputStream,"UTF-8")); // UTF-8 encoding must be specified in order for the output to have proper indentation.
// Write the DOM document to disk.
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", 2); // Set the indentation for child elements.
// Export as XML.
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
}
/**
* Inserts section breaks that delimit the topics.
*
* @param doc The document where to insert the section breaks.
*/
private static void insertTopicSections(Document doc) throws Exception
{
DocumentBuilder builder = new DocumentBuilder(doc);
NodeCollection paras = doc.getChildNodes(NodeType.PARAGRAPH, true);
ArrayList topicStartParas = new ArrayList();
for (Paragraph para : (Iterable<Paragraph>) paras)
{
int style = para.getParagraphFormat().getStyleIdentifier();
if ((style >= StyleIdentifier.HEADING_1) && (style <= MAX_TOPIC_HEADING) &&
(para.hasChildNodes()))
{
// Select heading paragraphs that must become topic starts.
// We can't modify them in this loop, we have to remember them in an array first.
topicStartParas.add(para);
}
else if ((style > MAX_TOPIC_HEADING) && (style <= StyleIdentifier.HEADING_9))
{
// Pull up headings. For example: if Heading 1-4 become topics, then I want Headings 5+
// to become Headings 4+. Maybe I want to pull up even higher?
para.getParagraphFormat().setStyleIdentifier(style - 1);
}
}
for (Paragraph para : (Iterable<Paragraph>) topicStartParas)
{
Section section = para.getParentSection();
// Insert section break if the paragraph is not at the beginning of a section already.
if (para != section.getBody().getFirstParagraph())
{
builder.moveTo(para.getFirstChild());
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
// This is the paragraph that was inserted at the end of the now old section.
// We don't really need the extra paragraph, we just needed the section.
section.getBody().getLastParagraph().remove();
}
}
}
/**
* Goes through the sections in the document and adds them as topics to the collection.
*/
private void addTopics(Document doc) throws Exception
{
for (Section section : doc.getSections())
{
try
{
TopicWord2Help topic = new TopicWord2Help(section, mFixUrl);
mTopics.add(topic);
}
catch (Exception e)
{
// If one topic fails, we continue with others.
System.out.println(e.getMessage());
}
}
}
private static Element writeBookStart(Element root, TopicWord2Help topic) throws Exception
{
Element book = root.getOwnerDocument().createElement("book");
root.appendChild(book);
book.setAttribute("name", topic.getTitle());
if (!topic.isHeadingOnly())
book.setAttribute("href", topic.getFileName());
return book;
}
private static void writeItem(Element root, String name, String href) throws Exception
{
Element item = root.getOwnerDocument().createElement("item");
root.appendChild(item);
item.setAttribute("name", name);
item.setAttribute("href", href);
}
private static String readFile(String fileName) throws Exception
{
FileInputStream reader = null;
try
{
reader = new FileInputStream(fileName);
byte[] fileBytes = new byte[reader.available()];
reader.read(fileBytes);
return new String(fileBytes);
}
finally {
if (reader != null)
reader.close();
}
}
private final ArrayList mTopics;
private final String mFixUrl;
private final String mHtmlHeader;
private final String mHtmlBanner;
private final String mHtmlFooter;
/**
* Specifies the maximum Heading X number.
* All of the headings above or equal to this will be put into their own topics.
*/
private static final int MAX_TOPIC_HEADING = StyleIdentifier.HEADING_4;
}
/**
* Represents a single topic that will be written as an HTML file.
*/
class TopicWord2Help
{
/**
* Creates a topic.
*/
public TopicWord2Help(Section section, String fixUrl) throws Exception
{
mTopicDoc = new Document();
mTopicDoc.appendChild(mTopicDoc.importNode(section, true, ImportFormatMode.KEEP_SOURCE_FORMATTING));
mTopicDoc.getFirstSection().remove();
Paragraph headingPara = (Paragraph)mTopicDoc.getFirstSection().getBody().getFirstChild();
if (headingPara == null)
throwTopicException("The section does not start with a paragraph.", section);
mHeadingLevel = headingPara.getParagraphFormat().getStyleIdentifier() - StyleIdentifier.HEADING_1;
if ((mHeadingLevel < 0) || (mHeadingLevel > 8))
throwTopicException("This topic does not start with a heading style paragraph.", section);
mTitle = headingPara.getText().trim();
if ("".equals(mTitle))
throwTopicException("This topic heading does not have text.", section);
// We actually remove the heading paragraph because <h1> will be output in the banner.
headingPara.remove();
mTopicDoc.getBuiltInDocumentProperties().setTitle(mTitle);
fixHyperlinks(section.getDocument(), fixUrl);
}
private static void throwTopicException(String message, Section section) throws Exception
{
throw new Exception(message + " Section text: " + section.getBody().toString(SaveFormat.TEXT).substring(0, 50));
}
private void fixHyperlinks(DocumentBase originalDoc, String fixUrl) throws Exception
{
if (fixUrl.endsWith("/"))
fixUrl = fixUrl.substring(0, fixUrl.length() - 1);
NodeCollection fieldStarts = mTopicDoc.getChildNodes(NodeType.FIELD_START, true);
for (FieldStart fieldStart : (Iterable<FieldStart>) fieldStarts)
{
if (fieldStart.getFieldType() != FieldType.FIELD_HYPERLINK)
continue;
Hyperlink hyperlink = new Hyperlink(fieldStart);
if (hyperlink.isLocal())
{
// We use "Hyperlink to a place in this document" feature of Microsoft Word
// to create local hyperlinks between topics within the same doc file.
// It causes MS Word to auto generate the bookmark name.
String bmkName = hyperlink.getTarget();
// But we have to follow the bookmark to get the text of the topic heading paragraph
// in order to be able to build the proper filename of the topic file.
Bookmark bmk = originalDoc.getRange().getBookmarks().get(bmkName);
// String test1 = MessageFormat.format("Found a link to a bookmark, but cannot locate the bookmark. Name:{0}.", bmkName);
if (bmk == null)
throw new Exception(MessageFormat.format("Found a link to a bookmark, but cannot locate the bookmark. Name:{0}.", bmkName));
Paragraph para = (Paragraph)bmk.getBookmarkStart().getParentNode();
String topicName = para.getText().trim();
hyperlink.setTarget(headingToFileName(topicName) + ".html");
hyperlink.setLocal(false);
}
else
{
// We "fix" URL like this:
// http://www.aspose.com/Products/Aspose.Words/Api/Aspose.Words.Body.html
// by changing them into this:
// Aspose.Words.Body.html
if (hyperlink.getTarget().startsWith(fixUrl) &&
(hyperlink.getTarget().length() > (fixUrl.length() + 1)))
{
hyperlink.setTarget(hyperlink.getTarget().substring(fixUrl.length() + 1));
}
}
}
}
public void writeHtml(String htmlHeader, String htmlBanner, String htmlFooter, String outDir) throws Exception
{
String fileName = new File(outDir, getFileName()).getAbsolutePath();
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.setPrettyFormat(true);
// This is to allow headings to appear to the left of main text.
saveOptions.setAllowNegativeIndent(true);
// Disable headers and footers.
saveOptions.setExportHeadersFootersMode(ExportHeadersFootersMode.NONE);
// Export the document to HTML.
mTopicDoc.save(fileName, saveOptions);
// We need to modify the HTML string, read HTML back.
String html;
FileInputStream reader = null;
try{
reader = new FileInputStream(fileName);
byte[] fileBytes = new byte[reader.available()];
reader.read(fileBytes);
html = new String(fileBytes);
}
finally { if (reader != null) reader.close(); }
// Builds the HTML <head> element.
String header = htmlHeader.replaceFirst(RegularExpressions.getHtmlTitle().pattern(), mTitle);
// Applies the new <head> element instead of the original one.
html = html.replaceFirst(RegularExpressions.getHtmlHead().pattern(), header);
html = html.replaceFirst(RegularExpressions.getHtmlBodyDivStart().pattern(), " id=\"nstext\"");
String banner = htmlBanner.replace("###TOPIC_NAME###", mTitle);
// Add the standard banner.
html = html.replace("<body>", "<body>" + banner);
// Add the standard footer.
html = html.replace("</body>", htmlFooter + "</body>");
FileOutputStream writer = null;
try{
writer = new FileOutputStream(fileName);
writer.write(html.getBytes());
}
finally { if (writer != null) writer.close(); }
}
/**
* Removes various characters from the header to form a file name that does not require escaping.
*/
private static String headingToFileName(String heading) throws Exception
{
StringBuilder b = new StringBuilder();
for (int i = 0; i < heading.length(); i++)
{
char c = heading.charAt(i);
if (Character.isLetterOrDigit(c))
b.append(c);
}
return b.toString();
}
public Document getDocument() throws Exception { return mTopicDoc; }
/**
* Gets the name of the topic html file without path.
*/
public String getFileName() throws Exception { return headingToFileName(mTitle) + ".html"; }
public String getTitle() throws Exception { return mTitle; }
public int getHeadingLevel() throws Exception { return mHeadingLevel; }
/**
* Returns true if the topic has no text (the heading paragraph has already been removed from the topic).
*/
public boolean isHeadingOnly() throws Exception
{
Body body = mTopicDoc.getFirstSection().getBody();
return (body.getFirstParagraph() == null);
}
private final Document mTopicDoc;
private final String mTitle;
private final int mHeadingLevel;
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(Word2Help.class);
// Specifies the destination directory where the HTML files are output.
File outPath = new File(dataDir, "Out");
// Remove any existing output and recreate the Out folder.
if(outPath.exists())
{
for(File file : outPath.listFiles())
{
file.delete();
}
}
outPath.mkdirs();
String outDir = outPath.getAbsolutePath();
// Specifies the part of the URLs to remove. If there are any hyperlinks that start
// with the above URL, this URL is removed. This allows the document designer to include
// links to the HTML API and they will be "corrected" so they work both in the online
// HTML and also in the compiled CHM.
String fixUrl = "";
// *** LICENSING ***
// An Aspose.Words license is required to use this project fully.
// Without a license Aspose.Words will work in evaluation mode and truncate documents
// and output watermarks.
//
// You can download a free 30-day trial license from the Aspose site. The easiest way is to set the license is to
// include the license in the executing directory and uncomment the following code.
//
// Aspose.Words.License license = new Aspose.Words.License();
// license.setLicense("Aspose.Words.lic");
System.out.println(MessageFormat.format("Extracting topics from {0}.", dataDir));
TopicCollection topics = new TopicCollection(dataDir, fixUrl);
topics.addFromDir(dataDir);
topics.writeHtml(outDir);
topics.writeContentXml(outDir);
Document doc = new Document(dataDir + "Document.doc");
DocSaveOptions saveOptions = new DocSaveOptions();
saveOptions.setAlwaysCompressMetafiles(false);
doc.save("SmallMetafilesUncompressed.doc", saveOptions);
Document doc = new Document(dataDir + "Document.doc");
DocSaveOptions docSaveOptions = new DocSaveOptions();
docSaveOptions.setPassword("password");
dataDir = dataDir + "Document.Password_out.doc";
doc.save(dataDir, docSaveOptions);
Document doc = new Document(dataDir + "in.doc");
DocSaveOptions saveOptions = (DocSaveOptions)SaveOptions.createSaveOptions(SaveFormat.DOC);
saveOptions.setSavePictureBullet(false);
doc.save(dataDir + "out.doc", saveOptions);
LoadOptions lo = new LoadOptions();
lo.setConvertShapeToOfficeMath(true);
// Specify load option to use previous default behaviour i.e. convert math shapes to office math ojects on loading stage.
Document doc = new Document(dataDir + "OfficeMath.docx", lo);
//Save the document into DOCX
doc.save(dataDir + "ConvertShapeToOfficeMath_out.docx", SaveFormat.DOCX);
Document doc = new Document(dataDir + "encrypted.odt", new com.aspose.words.LoadOptions("password"));
doc.save(dataDir + "out.odt", new OdtSaveOptions("newpassword"));
LoadOptions lo = new LoadOptions();
//Update the fields with the dirty attribute
lo.setUpdateDirtyFields(true);
//Load the Word document
Document doc = new Document(dataDir + "input.docx", lo);
//Save the document into DOCX
dataDir = dataDir + "output.docx";
doc.save(dataDir, SaveFormat.DOCX);
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.setPassword("password");
dataDir = dataDir + "Document.Password_out.docx";
doc.save(dataDir, ooxmlSaveOptions);
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions(SaveFormat.FLAT_OPC);
ooxmlSaveOptions.setKeepLegacyControlChars(true);
dataDir = dataDir + "Document_out.docx";
doc.save(dataDir, ooxmlSaveOptions);
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions so = new OoxmlSaveOptions(SaveFormat.DOCX);
so.setCompressionLevel(CompressionLevel.SUPER_FAST);
// Save the document to disk.
doc.save(dataDir + "SetCompressionLevel_out.docx", so);
Document doc = new Document(dataDir + "Document.doc");
// Set Word2016 version for document
doc.getCompatibilityOptions().optimizeFor(MsWordVersion.WORD_2016);
//Set the Strict compliance level.
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.setCompliance(OoxmlCompliance.ISO_29500_2008_STRICT);
ooxmlSaveOptions.setSaveFormat(SaveFormat.DOCX);
dataDir = dataDir + "Document.Iso29500_2008_Strict_out.docx";
doc.save(dataDir, ooxmlSaveOptions);
Document doc = new Document(dataDir + "Document.doc");
OoxmlSaveOptions ooxmlSaveOptions = new OoxmlSaveOptions();
ooxmlSaveOptions.setUpdateLastSavedTimeProperty(true);
dataDir = dataDir + "UpdateLastSavedTimeProperty_out.docx";
doc.save(dataDir, ooxmlSaveOptions);
RtfLoadOptions loadOptions = new RtfLoadOptions();
loadOptions.setRecognizeUtf8Text(true);
Document doc = new Document(dataDir + "Utf8Text.rtf", loadOptions);
dataDir = dataDir + "RecognizeUtf8Text_out.rtf";
doc.save(dataDir);
Document doc = new Document(dataDir + "Input.docx");
TxtSaveOptions saveOptions = new TxtSaveOptions();
//The default value is false.
saveOptions.setAddBidiMarks(true);
dataDir = dataDir + "Document.AddBidiMarks_out.txt";
doc.save(dataDir, saveOptions);
Document doc = new Document(dataDir + "Input.docx");
doc.save(dataDir + "output1.txt");
Document doc2 = new Document("Input.docx");
TxtSaveOptions options = new TxtSaveOptions();
doc2.save(dataDir + "output2.txt", options);
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.setDetectNumberingWithWhitespaces(false);
Document doc = new Document(dataDir + "LoadTxt.txt", loadOptions);
dataDir = dataDir + "DetectNumberingWithWhitespaces_out.docx";
doc.save(dataDir);
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.setDocumentDirection(DocumentDirection.AUTO);
Document doc = new Document(dataDir + "arabic.txt", loadOptions);
Paragraph paragraph = doc.getFirstSection().getBody().getFirstParagraph();
System.out.println(paragraph.getParagraphFormat().getBidi());
dataDir = dataDir + "DocumentDirection_out.docx";
doc.save(dataDir);
Document doc = new Document(dataDir + "TxtExportHeadersFootersMode.docx");
TxtSaveOptions options = new TxtSaveOptions();
options.setSaveFormat(SaveFormat.TEXT);
// All headers and footers are placed at the very end of the output document.
options.setExportHeadersFootersMode(TxtExportHeadersFootersMode.ALL_AT_END);
doc.save(dataDir + "outputFileNameA.txt", options);
// Only primary headers and footers are exported at the beginning and end of each section.
options.setExportHeadersFootersMode(TxtExportHeadersFootersMode.PRIMARY_ONLY);
doc.save(dataDir + "outputFileNameB.txt", options);
// No headers and footers are exported.
options.setExportHeadersFootersMode(TxtExportHeadersFootersMode.NONE);
doc.save(dataDir + "outputFileNameC.txt", options);
TxtLoadOptions loadOptions = new TxtLoadOptions();
loadOptions.setLeadingSpacesOptions(TxtLeadingSpacesOptions.TRIM);
loadOptions.setTrailingSpacesOptions(TxtTrailingSpacesOptions.TRIM);
Document doc = new Document(dataDir + "LoadTxt.txt", loadOptions);
dataDir = dataDir + "HandleSpacesOptions_out.docx";
doc.save(dataDir);
Document doc = new Document(dataDir + "Document.doc");
dataDir = dataDir + "Document.ConvertToTxt_out.txt";
doc.save(dataDir);
Document doc = new Document(dataDir + "Input.docx");
TxtSaveOptions options = new TxtSaveOptions();
options.getListIndentation().setCount(3);
options.getListIndentation().setCharacter(' ');
doc.save(dataDir + "output.txt", options);
Document doc = new Document(dataDir + "Input.docx");
TxtSaveOptions options = new TxtSaveOptions();
options.getListIndentation().setCount(1);
options.getListIndentation().setCharacter('\t');
doc.save(dataDir + "output.txt", options);
Document doc = new Document(dataDir + "test.docm");
VbaProject project = doc.getVbaProject();
Document destDoc = new Document();
destDoc.setVbaProject(new VbaProject());
// Clone a single module.
VbaModule copyModule = doc.getVbaProject().getModules().get("Module1").deepClone();
destDoc.getVbaProject().getModules().add(copyModule);
destDoc.save(dataDir + "output.docm");
Document doc = new Document(dataDir + "test.docm");
VbaProject project = doc.getVbaProject();
Document destDoc = new Document();
// Clone the whole project.
destDoc.setVbaProject(doc.getVbaProject().deepClone());
destDoc.save(dataDir + "output.docm");
Document doc = new Document();
// Create a new VBA project.
VbaProject project = new VbaProject();
project.setName("AsposeProject");
doc.setVbaProject(project);
// Create a new module and specify a macro source code.
VbaModule module = new VbaModule();
module.setName("AsposeModule");
module.setType(VbaModuleType.PROCEDURAL_MODULE);
module.setSourceCode("New source code");
// Add module to the VBA project.
doc.getVbaProject().getModules().add(module);
doc.save(dataDir + "VbaProject_out.docm");
Document doc = new Document(dataDir + "test.docm");
VbaProject project = doc.getVbaProject();
String newSourceCode = "Test change source code";
// Choose a module, and set a new source code.
project.getModules().get(0).setSourceCode(newSourceCode);
// The path to the documents directory.
String dataDir = Utils.getDataDir(WorkingWithVbaMacros.class);
Document doc = new Document(dataDir + "Document.dot");
for (VbaModule module : doc.getVbaProject().getModules()) {
System.out.println(module.getSourceCode());
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String[] fieldNames = doc.getMailMerge().getFieldNames();
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
doc.getMailMerge().getMappedDataFields().add("MyFieldName_InDocument", "MyFieldName_InDataSource");
public class ApplyCustomFormattingDuringMailMerge {
private static final String dataDir = Utils.getSharedDataDir(ApplyCustomFormattingDuringMailMerge.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
Document doc = new Document(dataDir + "MailMerge.AlternatingRows.doc");
// Add a handler for the MergeField event.
doc.getMailMerge().setFieldMergingCallback(new HandleMergeFieldAlternatingRows());
// Execute mail merge with regions.
DataTable dataTable = getSuppliersDataTable();
doc.getMailMerge().executeWithRegions(dataTable);
doc.save(dataDir + "MailMerge.AlternatingRows Out.doc");
}
/**
* Returns true if the value is odd; false if the value is even.
*/
public static boolean isOdd(int value) throws Exception {
return (value % 2 != 0);
}
/**
* Create DataTable and fill it with data. In real life this DataTable
* should be filled from a database.
*/
private static DataTable getSuppliersDataTable() throws Exception {
java.sql.ResultSet resultSet = createCachedRowSet(new String[] { "CompanyName", "ContactName" });
for (int i = 0; i < 10; i++)
addRow(resultSet, new String[] { "Company " + Integer.toString(i), "Contact " + Integer.toString(i) });
return new DataTable(resultSet, "Suppliers");
}
/**
* A helper method that creates an empty Java disconnected ResultSet with
* the specified columns.
*/
private static ResultSet createCachedRowSet(String[] columnNames) throws Exception {
RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
metaData.setColumnCount(columnNames.length);
for (int i = 0; i < columnNames.length; i++) {
metaData.setColumnName(i + 1, columnNames[i]);
metaData.setColumnType(i + 1, java.sql.Types.VARCHAR);
}
CachedRowSetImpl rowSet = new CachedRowSetImpl();
rowSet.setMetaData(metaData);
return rowSet;
}
/**
* A helper method that adds a new row with the specified values to a
* disconnected ResultSet.
*/
private static void addRow(ResultSet resultSet, String[] values) throws Exception {
resultSet.moveToInsertRow();
for (int i = 0; i < values.length; i++)
resultSet.updateString(i + 1, values[i]);
resultSet.insertRow();
// This "dance" is needed to add rows to the end of the result set properly.
// If I do something else then rows are either added at the front or the result
// set throws an exception about a deleted row during mail merge.
resultSet.moveToCurrentRow();
resultSet.last();
}
}
class HandleMergeFieldAlternatingRows implements IFieldMergingCallback {
/**
* Called for every merge field encountered in the document. We can either
* return some data to the mail merge engine or do something else with the
* document. In this case we modify cell formatting.
*/
public void fieldMerging(FieldMergingArgs e) throws Exception {
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.getDocument());
// This way we catch the beginning of a new row.
if (e.getFieldName().equals("CompanyName")) {
// Select the color depending on whether the row number is even or odd.
Color rowColor;
if (ApplyCustomFormattingDuringMailMerge.isOdd(mRowIdx))
rowColor = new Color(213, 227, 235);
else
rowColor = new Color(242, 242, 242);
// There is no way to set cell properties for the whole row at the moment,
// so we have to iterate over all cells in the row.
for (int colIdx = 0; colIdx < 4; colIdx++) {
mBuilder.moveToCell(0, mRowIdx, colIdx, 0);
mBuilder.getCellFormat().getShading().setBackgroundPatternColor(rowColor);
}
mRowIdx++;
}
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
// Do nothing.
}
private DocumentBuilder mBuilder;
private int mRowIdx;
}
public static class EmptyRegionsHandler implements IFieldMergingCallback {
/**
* Called for each field belonging to an unmerged region in the
* document.
*/
public void fieldMerging(FieldMergingArgs args) throws Exception {
// Change the text of each field of the ContactDetails region individually.
if ("ContactDetails".equals(args.getTableName())) {
// Set the text of the field based off the field name.
if ("Name".equals(args.getFieldName()))
args.setText("(No details found)");
else if ("Number".equals(args.getFieldName()))
args.setText("(N/A)");
}
// Remove the entire table of the Suppliers region. Also check if the previous paragraph
// before the table is a heading paragraph and if so remove that too.
if ("Suppliers".equals(args.getTableName())) {
Table table = (Table) args.getField().getStart().getAncestor(NodeType.TABLE);
// Check if the table has been removed from the document already.
if (table.getParentNode() != null) {
// Try to find the paragraph which precedes the table before the table is removed from the document.
if (table.getPreviousSibling() != null && table.getPreviousSibling().getNodeType() == NodeType.PARAGRAPH) {
Paragraph previousPara = (Paragraph) table.getPreviousSibling();
if (isHeadingParagraph(previousPara))
previousPara.remove();
}
table.remove();
}
}
}
/**
* Returns true if the paragraph uses any Heading style e.g Heading 1 to
* Heading 9
*/
private boolean isHeadingParagraph(Paragraph para) throws Exception {
return (para.getParagraphFormat().getStyleIdentifier() >= StyleIdentifier.HEADING_1 && para.getParagraphFormat().getStyleIdentifier() <= StyleIdentifier.HEADING_9);
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
// Do Nothing
}
}
/**
* Applies logic defined in the passed handler class to all unused regions
* in the document. This allows to manually control how unused regions are
* handled in the document.
*
* @param doc
* The document containing unused regions.
* @param handler
* The handler which implements the IFieldMergingCallback
* interface and defines the logic to be applied to each unmerged
* region.
*/
public static void executeCustomLogicOnEmptyRegions(Document doc, IFieldMergingCallback handler) throws Exception {
executeCustomLogicOnEmptyRegions(doc, handler, null); // Pass null to handle all regions found in the document.
}
/**
* Applies logic defined in the passed handler class to specific unused
* regions in the document as defined in regionsList. This allows to
* manually control how unused regions are handled in the document.
*
* @param doc
* The document containing unused regions.
* @param handler
* The handler which implements the IFieldMergingCallback
* interface and defines the logic to be applied to each unmerged
* region.
* @param regionsList
* A list of strings corresponding to the region names that are
* to be handled by the supplied handler class. Other regions
* encountered will not be handled and are removed automatically.
*/
public static void executeCustomLogicOnEmptyRegions(Document doc, IFieldMergingCallback handler, ArrayList regionsList) throws Exception {
// Certain regions can be skipped from applying logic to by not adding the table name inside the CreateEmptyDataSource method.
// Enable this cleanup option so any regions which are not handled by the user's logic are removed automatically.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
// Set the user's handler which is called for each unmerged region.
doc.getMailMerge().setFieldMergingCallback(handler);
// Execute mail merge using the dummy dataset. The dummy data source contains the table names of
// each unmerged region in the document (excluding ones that the user may have specified to be skipped). This will allow the handler
// to be called for each field in the unmerged regions.
doc.getMailMerge().executeWithRegions(createDataSourceFromDocumentRegions(doc, regionsList));
}
/**
* A helper method that creates an empty Java disconnected ResultSet with
* the specified columns.
*/
private static ResultSet createCachedRowSet(String[] columnNames) throws Exception {
RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
metaData.setColumnCount(columnNames.length);
for (int i = 0; i < columnNames.length; i++) {
metaData.setColumnName(i + 1, columnNames[i]);
metaData.setColumnType(i + 1, java.sql.Types.VARCHAR);
}
CachedRowSetImpl rowSet = new CachedRowSetImpl();
rowSet.setMetaData(metaData);
return rowSet;
}
/**
* A helper method that adds a new row with the specified values to a
* disconnected ResultSet.
*/
private static void addRow(ResultSet resultSet, String[] values) throws Exception {
resultSet.moveToInsertRow();
for (int i = 0; i < values.length; i++)
resultSet.updateString(i + 1, values[i]);
resultSet.insertRow();
// This "dance" is needed to add rows to the end of the result set properly.
// If I do something else then rows are either added at the front or the result
// set throws an exception about a deleted row during mail merge.
resultSet.moveToCurrentRow();
resultSet.last();
}
ArrayList<String> regions = new ArrayList<String>();
regions.add("ContactDetails");
executeCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler(), regions);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Create a data source which has some data missing.
// This will result in some regions that are merged and some that remain after executing mail merge.
DataSet data = getDataSource();
// Make sure that we have not set the removal of any unused regions as we will handle them manually.
// We achieve this by removing the RemoveUnusedRegions flag from the cleanup options by using the AND and NOT bitwise operators.
doc.getMailMerge().setCleanupOptions(doc.getMailMerge().getCleanupOptions() & ~MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
// Execute mail merge. Some regions will be merged with data, others left unmerged.
doc.getMailMerge().executeWithRegions(data);
// The regions which contained data now would of been merged. Any regions which had no data and were
// not merged will still remain in the document.
Document mergedDoc = doc.deepClone(); //ExSkip
// Apply logic to each unused region left in the document using the logic set out in the handler.
// The handler class must implement the IFieldMergingCallback interface.
executeCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler());
// Save the output document to disk.
doc.save(dataDir + "TestFile.CustomLogicEmptyRegions1 Out.doc");
/**
* Returns a DataSet object containing a DataTable for the unmerged regions
* in the specified document. If regionsList is null all regions found
* within the document are included. If an ArrayList instance is present the
* only the regions specified in the list that are found in the document are
* added.
*/
private static DataSet createDataSourceFromDocumentRegions(Document doc, ArrayList regionsList) throws Exception {
final String TABLE_START_MARKER = "TableStart:";
DataSet dataSet = new DataSet();
String tableName = null;
for (String fieldName : doc.getMailMerge().getFieldNames()) {
if (fieldName.contains(TABLE_START_MARKER)) {
tableName = fieldName.substring(TABLE_START_MARKER.length());
} else if (tableName != null) {
// Only add the table as a new DataTable if it doesn't already exists in the DataSet.
if (dataSet.getTables().get(tableName) == null) {
ResultSet resultSet = createCachedRowSet(new String[] { fieldName });
// We only need to add the first field for the handler to be called for the fields in the region.
if (regionsList == null || regionsList.contains(tableName)) {
addRow(resultSet, new String[] { "FirstField" });
}
dataSet.getTables().add(new DataTable(resultSet, tableName));
}
tableName = null;
}
}
return dataSet;
}
// Replace the unused region in the table with a "no records" message and merge all cells into one.
if ("Suppliers".equals(args.getTableName())) {
if ("FirstField".equals(args.getFieldValue())) {
// We will use the first paragraph to display our message. Make it centered within the table. The other fields in other cells
// within the table will be merged and won't be displayed so we don't need to do anything else with them.
parentParagraph.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
args.setText("No records to display");
}
// Merge the cells of the table together.
Cell cell = (Cell) parentParagraph.getAncestor(NodeType.CELL);
if (cell != null) {
if (cell.isFirstCell())
cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST); // If this cell is the first cell in the table then the merge is started using "CellMerge.First".
else
cell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS); // Otherwise the merge is continued using "CellMerge.Previous".
}
}
// Store the parent paragraph of the current field for easy access.
Paragraph parentParagraph = args.getField().getStart().getParentParagraph();
// Define the logic to be used when the ContactDetails region is encountered.
// The region is removed and replaced with a single line of text stating that there are no records.
if ("ContactDetails".equals(args.getTableName())) {
// Called for the first field encountered in a region. This can be used to execute logic on the first field
// in the region without needing to hard code the field name. Often the base logic is applied to the first field and
// different logic for other fields. The rest of the fields in the region will have a null FieldValue.
if ("FirstField".equals(args.getFieldValue())) {
FindReplaceOptions opts = new FindReplaceOptions();
opts.setMatchCase(false);
opts.setFindWholeWordsOnly(false);
// Remove the "Name:" tag from the start of the paragraph
parentParagraph.getRange().replace("Name:", "", opts);
// Set the text of the first field to display a message stating that there are no records.
args.setText("No records to display");
} else {
// We have already inserted our message in the paragraph belonging to the first field. The other paragraphs in the region
// will still remain so we want to remove these. A check is added to ensure that the paragraph has not already been removed.
// which may happen if more than one field is included in a paragraph.
if (parentParagraph.getParentNode() != null)
parentParagraph.remove();
}
}
private static final String dataDir = Utils.getSharedDataDir(ExecuteMailMergeWithRegions.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
Document doc = new Document(dataDir + "MailMerge.ExecuteWithRegions.doc");
int orderId = 10444;
// Perform several mail merge operations populating only part of the document each time.
// Use DataTable as a data source.
// The table name property should be set to match the name of the region defined in the document.
DataTable orderTable = getTestOrder(orderId);
doc.getMailMerge().executeWithRegions(orderTable);
DataTable orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC");
doc.getMailMerge().executeWithRegions(orderDetailsTable);
doc.save(dataDir + "MailMerge.ExecuteWithRegionsDataTable Out.doc");
}
private static DataTable getTestOrder(int orderId) throws Exception {
java.sql.ResultSet resultSet = executeDataTable(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", Integer.toString(orderId)));
return new DataTable(resultSet, "Orders");
}
private static DataTable getTestOrderDetails(int orderId, String orderBy) throws Exception {
StringBuilder builder = new StringBuilder();
builder.append(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0}", Integer.toString(orderId)));
if ((orderBy != null) && (orderBy.length() > 0)) {
builder.append(" ORDER BY ");
builder.append(orderBy);
}
java.sql.ResultSet resultSet = executeDataTable(builder.toString());
return new DataTable(resultSet, "OrderDetails");
}
/**
* Utility function that creates a connection, command, executes the command
* and return the result in a DataTable.
*/
private static java.sql.ResultSet executeDataTable(String commandText) throws Exception {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connString = "jdbc:ucanaccess://" + dataDir + "Northwind.mdb";
// From Wikipedia: The Sun driver has a known issue with character encoding and Microsoft Access databases.
// Microsoft Access may use an encoding that is not correctly translated by the driver, leading to the replacement
// in strings of, for example, accented characters by question marks.
//
// In this case I have to set CP1252 for the European characters to come through in the data values.
java.util.Properties props = new java.util.Properties();
props.put("charSet", "Cp1252");
// DSN-less DB connection.
java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, props);
// Create and execute a command.
java.sql.Statement statement = conn.createStatement();
return statement.executeQuery(commandText);
}
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
// Trim trailing and leading whitespaces mail merge values
doc.getMailMerge().setTrimWhitespaces(false);
// Fill the fields in the document with user data.
doc.getMailMerge().execute(new String[] { "FullName", "Company", "Address", "Address2", "City" },
new Object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });
doc.save(dataDir + "MailMerge.ExecuteArray_Out.doc");
static class MailMergeSwitches implements IFieldMergingCallback {
public void fieldMerging(FieldMergingArgs e) throws Exception {
if (e.getFieldName().startsWith("HTML")) {
if (e.getField().getFieldCode().contains("\\b")) {
FieldMergeField field = e.getField();
DocumentBuilder builder = new DocumentBuilder(e.getDocument());
builder.moveToMergeField(e.getDocumentFieldName(), true, false);
builder.write(field.getTextBefore());
builder.insertHtml(e.getFieldValue().toString());
e.setText("");
}
}
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
// Do Nothing
}
}
/**
* This sample shows how to insert check boxes and text input form fields during
* mail merge into a document.
*/
public class InsertCheckBoxesOrHTMLDuringMailMerge {
private static final String dataDir = Utils.getSharedDataDir(InsertCheckBoxesOrHTMLDuringMailMerge.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
execute();
}
private static void execute() throws Exception {
// Load the template document.
Document doc = new Document(dataDir + "Template.doc");
// Setup mail merge event handler to do the custom work.
doc.getMailMerge().setFieldMergingCallback(new HandleMergeField());
// This is the data for mail merge.
String[] fieldNames = new String[] { "RecipientName", "SenderName", "FaxNumber", "PhoneNumber", "Subject", "Body", "Urgent", "ForReview", "PleaseComment" };
Object[] fieldValues = new Object[] { "Josh", "Jenny", "123456789", "", "Hello", "<b>HTML Body Test message 1</b>", true, false, true };
// Execute the mail merge.
doc.getMailMerge().execute(fieldNames, fieldValues);
// Save the finished document.
doc.save(dataDir + "Template Out.doc");
}
}
class HandleMergeField implements IFieldMergingCallback {
/**
* This handler is called for every mail merge field found in the document,
* for every record found in the data source.
*/
public void fieldMerging(FieldMergingArgs e) throws Exception {
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.getDocument());
// We decided that we want all boolean values to be output as check box form fields.
if (e.getFieldValue() instanceof Boolean) {
// Move the "cursor" to the current merge field.
mBuilder.moveToMergeField(e.getFieldName());
// It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
String checkBoxName = java.text.MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());
// Insert a check box.
mBuilder.insertCheckBox(checkBoxName, (Boolean) e.getFieldValue(), 0);
// Nothing else to do for this field.
return;
}
// We want to insert html during mail merge.
if ("Body".equals(e.getFieldName())) {
mBuilder.moveToMergeField(e.getFieldName());
mBuilder.insertHtml((String) e.getFieldValue());
}
// Another example, we want the Subject field to come out as text input form field.
if ("Subject".equals(e.getFieldName())) {
mBuilder.moveToMergeField(e.getFieldName());
String textInputName = java.text.MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());
mBuilder.insertTextInput(textInputName, TextFormFieldType.REGULAR, "", (String) e.getFieldValue(), 0);
}
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
// Do nothing.
}
private DocumentBuilder mBuilder;
}
public class InsertImagesFromADatabase {
private static final String dataDir = Utils.getSharedDataDir(InsertImagesFromADatabase.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
Document doc = new Document(dataDir + "MailMerge.MergeImage.doc");
// Set up the event handler for image fields.
doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connString = "jdbc:ucanaccess://" + dataDir + "Northwind.mdb";
// DSN-less DB connection.
java.sql.Connection conn = java.sql.DriverManager.getConnection(connString);
// Create and execute a command.
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");
DataTable table = new DataTable(resultSet, "Employees");
// Perform mail merge.
doc.getMailMerge().executeWithRegions(table);
// Close the database.
conn.close();
doc.save(dataDir + "MailMerge.MergeImage Out.doc");
}
}
class HandleMergeImageFieldFromBlob implements IFieldMergingCallback {
public void fieldMerging(FieldMergingArgs args) throws Exception {
// Do nothing.
}
/**
* This is called when mail merge engine encounters Image:XXX merge
* field in the document. You have a chance to return an Image object,
* file name or a stream that contains the image.
*/
public void imageFieldMerging(ImageFieldMergingArgs e) throws Exception {
// The field value is a byte array, just cast it and create a stream on it.
ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
// Now the mail merge engine will retrieve the image from the stream.
e.setImageStream(imageStream);
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(MailMergeAndConditionalField.class);
// Open an existing document.
Document doc = new Document(dataDir + "UnconditionalMergeFieldsAndRegions.docx");
//Merge fields and merge regions are merged regardless of the parent IF field's condition.
doc.getMailMerge().setUnconditionalMergeFieldsAndRegions(true);
// Fill the fields in the document with user data.
doc.getMailMerge().execute(
new String[]{"FullName"},
new Object[]{"James Bond"});
doc.save(dataDir + "UnconditionalMergeFieldsAndRegions_out.docx", SaveFormat.DOCX);
// 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(MailMergeAndConditionalField.class);
// Open an existing document.
Document doc = new Document(dataDir + "UnconditionalMergeFieldsAndRegions.docx");
//Merge fields and merge regions are merged regardless of the parent IF field's condition.
doc.getMailMerge().setUnconditionalMergeFieldsAndRegions(true);
// Fill the fields in the document with user data.
doc.getMailMerge().execute(
new String[]{"FullName"},
new Object[]{"James Bond"});
doc.save(dataDir + "UnconditionalMergeFieldsAndRegions_out.docx", SaveFormat.DOCX);
// Open the document
Document doc = new Document(dataDir + "MailMerge.CleanupPunctuationMarks.docx");
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS);
doc.getMailMerge().setCleanupParagraphsWithPunctuationMarks(false);
doc.getMailMerge().execute(new String[]{"field1", "field2"}, new Object[]{"", ""});
dataDir = dataDir + "MailMerge.CleanupPunctuationMarks_out.docx";
// Save the output document to disk.
doc.save(dataDir);
/**
* This sample shows how to insert check boxes and text input form fields during mail merge into a document.
*/
public class MailMergeFormFields
{
/**
* The main entry point for the application.
*/
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = Utils.getDataDir(MailMergeFormFields.class);
// Load the template document.
Document doc = new Document(dataDir + "Template.doc");
// Setup mail merge event handler to do the custom work.
doc.getMailMerge().setFieldMergingCallback(new HandleMergeField());
// This is the data for mail merge.
String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
"Subject", "Body", "Urgent", "ForReview", "PleaseComment"};
Object[] fieldValues = new Object[] {"Josh", "Jenny", "123456789", "", "Hello",
"Test message 1", true, false, true};
// Execute the mail merge.
doc.getMailMerge().execute(fieldNames, fieldValues);
// Save the finished document.
doc.save(dataDir + "Template Out.doc");
System.out.println("Mail merge performed successfully.");
}
private static class HandleMergeField implements IFieldMergingCallback
{
/**
* This handler is called for every mail merge field found in the document,
* for every record found in the data source.
*/
public void fieldMerging(FieldMergingArgs e) throws Exception
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.getDocument());
// We decided that we want all boolean values to be output as check box form fields.
if (e.getFieldValue() instanceof Boolean)
{
// Move the "cursor" to the current merge field.
mBuilder.moveToMergeField(e.getFieldName());
// It is nice to give names to check boxes. Lets generate a name such as MyField21 or so.
String checkBoxName = java.text.MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());
// Insert a check box.
mBuilder.insertCheckBox(checkBoxName, (Boolean)e.getFieldValue(), 0);
// Nothing else to do for this field.
return;
}
// Another example, we want the Subject field to come out as text input form field.
if ("Subject".equals(e.getFieldName()))
{
mBuilder.moveToMergeField(e.getFieldName());
String textInputName = java.text.MessageFormat.format("{0}{1}", e.getFieldName(), e.getRecordIndex());
mBuilder.insertTextInput(textInputName, TextFormFieldType.REGULAR, "", (String)e.getFieldValue(), 0);
}
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception
{
// Do nothing.
}
private DocumentBuilder mBuilder;
}
}
/**
* This sample demonstrates how to execute mail merge with data from an XML
* data source. The XML file is read into memory, stored in a DOM and passed
* to a custom data source implementing IMailMergeDataSource. This returns
* each value from XML when called by the mail merge engine.
*/
private static final String dataDir = Utils.getSharedDataDir(MailMergeFromXMLUsingIMailMergeDataSource.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
// Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
// the XML data file and store it in memory.
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Parse the XML data.
org.w3c.dom.Document xmlData = db.parse(dataDir + "Customers.xml");
// Open a template document.
Document doc = new Document(dataDir + "TestFile.doc");
// Note that this class also works with a single repeatable region (and any nested regions).
// To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
// e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
doc.getMailMerge().execute(new XmlMailMergeDataTable(xmlData, "customer"));
// Save the output document.
doc.save(dataDir + "TestFile Out.doc");
}
class ShapeSetFieldMergingCallback implements IFieldMergingCallback{
public void fieldMerging(FieldMergingArgs args) throws Exception {
// Implementation is not required.
}
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
Shape shape = new Shape(args.getDocument(), ShapeType.IMAGE);
shape.setWidth(100);
shape.setHeight(200);
shape.setWrapSide(WrapType.SQUARE);
String imageFileName = Utils.getDataDir(MailMergeImageField.class) + "image.png";
shape.getImageData().setImage(imageFileName);
args.setShape(shape);
}
}
Document doc = new Document(new FileInputStream(dataDir + "template.docx"));
MailMerge mailMerge = doc.getMailMerge();
mailMerge.setUseNonMergeFields(true);
mailMerge.setTrimWhitespaces(true);
mailMerge.setUseWholeParagraphAsRegion(false);
mailMerge.setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_TABLE_ROWS
| MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS | MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS
| MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);
mailMerge.setFieldMergingCallback(new ShapeSetFieldMergingCallback());
mailMerge.executeWithRegions(new DataSourceRoot());
doc.save(dataDir + "result.docx");
// 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(MailMergeUsingMustacheSyntax.class);
// Open the document.
DataSet ds = new DataSet();
ds.readXml(dataDir + "Vendors.xml");
// Open a template document.
Document doc = new Document(dataDir + "VendorTemplate.doc");
doc.getMailMerge().setUseNonMergeFields(true);
// Execute mail merge to fill the template with data from XML using DataSet.
doc.getMailMerge().executeWithRegions(ds);
// Save the output document to disk.
doc.save(dataDir + "Output.doc");
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
doc.getMailMerge().setUseNonMergeFields(true);
// Fill the fields in the document with user data.
doc.getMailMerge().execute(new String[]{"FullName", "Company", "Address", "Address2", "City"}, new Object[]{"James Bond", "MI5 Headquarters", "Milbank", "", "London"});
doc.save(dataDir + "MailMerge.ExecuteArray_Out.doc");
// Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
// the XML data file and store it in memory.
javax.xml.parsers.DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Parse the XML data.
org.w3c.dom.Document xmlData = db.parse(dataDir + "Vendors.xml");
// Open a template document.
Document doc = new Document(dataDir + "VendorTemplate.doc");
doc.getMailMerge().setUseNonMergeFields(true);
// Note that this class also works with a single repeatable region (and any nested regions).
// To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
// e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
// Save the output document.
doc.save(dataDir + "MailMergeUsingMustacheSyntax_Out.docx");
// Open a template document.
Document doc = new Document(dataDir + "UseOfifelseMustacheSyntax.docx");
doc.getMailMerge().setUseNonMergeFields(true);
doc.getMailMerge().execute(new String[]{"GENDER"}, new Object[]{"MALE"});
// Save the output document.
doc.save(dataDir + "MailMergeUsingMustacheSyntaxifelse_out.docx");
/**
* This is called when mail merge engine encounters plain text (non image) merge
*/
static class HandleMergeFields implements IFieldMergingCallback {
public void fieldMerging(FieldMergingArgs args) throws Exception {
System.out.println("Mail merge for field : " +args.getFieldName() + " & Value : " +args.getFieldValue());
}
/**
* This is called when mail merge engine encounters Image:XXX merge
* field in the document. You have a chance to return an Image object,
* file name or a stream that contains the image.
*/
public void imageFieldMerging(ImageFieldMergingArgs e) throws Exception {
System.out.println("Mail merge for field : " +e.getFieldName() + " & Value : " +e.getFieldValue());
}
}
private static Document mailMergeTemplate(byte[] templateFile, String[] referenceFields, Object[] referenceValues) throws Exception {
Document doc = null;
try {
doc = new Document(new ByteArrayInputStream(templateFile));
FindReplaceOptions opts = new FindReplaceOptions();
opts.setFindWholeWordsOnly(false);
opts.setReplacingCallback( new ReplaceEvaluatorFindAndInsertMergefield());
doc.getRange().replace(Pattern.compile("�(.*?)�"), "", opts);
doc.getMailMerge().setFieldMergingCallback(new HandleMergeFields());
doc.getMailMerge().execute(referenceFields, referenceValues);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
String dataDir = Utils.getDataDir(BubbleChart.class);
String fileName = "Converted.pdf";
com.aspose.pdf.Document pdfDoc = new com.aspose.pdf.Document(dataDir + fileName);
ByteArrayOutputStream baOs = new ByteArrayOutputStream();
//Converting PDF document to word document
pdfDoc.save(baOs, com.aspose.pdf.SaveFormat.DocX);
String[] referenceFields = {"FIRSTNAME", "MEMFIRST"};
Object[] referenceValues = {"AAA", "BBB"};
Document document = mailMergeTemplate(baOs.toByteArray(), referenceFields, referenceValues);
document.save(dataDir + "Saved.pdf");
static class ReplaceEvaluatorFindAndInsertMergefield implements IReplacingCallback {
public int replacing(ReplacingArgs e) throws Exception {
// This is a Run node that contains either the beginning or the complete match.
Node currentNode = e.getMatchNode();
// The first (and may be the only) run can contain text before the match,
// in this case it is necessary to split the run.
if (e.getMatchOffset() > 0)
currentNode = splitRun((Run) currentNode, e.getMatchOffset());
ArrayList runs = new ArrayList();
// Find all runs that contain parts of the match string.
int remainingLength = e.getMatch().group().length();
while ((remainingLength > 0) && (currentNode != null) && (currentNode.getText().length() <= remainingLength)) {
runs.add(currentNode);
remainingLength = remainingLength - currentNode.getText().length();
// Select the next Run node.
// Have to loop because there could be other nodes such as BookmarkStart etc.
do {
currentNode = currentNode.getNextSibling();
} while ((currentNode != null) && (currentNode.getNodeType() != NodeType.RUN));
}
// Split the last run that contains the match if there is any text left.
if ((currentNode != null) && (remainingLength > 0)) {
splitRun((Run) currentNode, remainingLength);
runs.add(currentNode);
}
//Change static text to real merge fields.
DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
builder.moveTo((Run) runs.get(runs.size() - 1));
builder.insertField("MERGEFIELD \"" + e.getMatch().group(1) + "\"");
for (Run run : (Iterable<Run>) runs)
run.remove();
// Signal to the replace engine to do nothing because we have already done all what we wanted.
return ReplaceAction.SKIP;
}
/**
* Splits text of the specified run into two runs. Inserts the new run just
* after the specified run.
*/
private Run splitRun(Run run, int position) throws Exception {
Run afterRun = (Run) run.deepClone(true);
afterRun.setText(run.getText().substring(position));
run.setText(run.getText().substring((0), (0) + (position)));
run.getParentNode().insertAfter(afterRun, run);
return afterRun;
}
}
private static Connection mConnection;
private static final String dataDir = Utils.getSharedDataDir(NestedMailMergeRegions.class) + "MailMerge/";
public static void main(String[] args) throws Exception
{
produceMultipleDocuments(dataDir, "TestFile.Multiple Pages.doc");
}
public static void produceMultipleDocuments(String dataDir, String srcDoc) throws Exception
{
// Create a connection to the database
createConnection(dataDir);
// Open the database connection.
ResultSet rs = executeQuery("SELECT * FROM Customers");
// Open the template document.
Document doc = new Document(dataDir + srcDoc);
// A record of how many documents that have been generated so far.
int counter = 1;
// Loop though all records in the data source.
while(rs.next())
{
// Clone the template instead of loading it from disk (for speed).
Document dstDoc = (Document)doc.deepClone(true);
// Extract the data from the current row of the ResultSet into a Hashtable.
Hashtable dataMap = getRowData(rs);
// Execute mail merge.
dstDoc.getMailMerge().execute(keySetToArray(dataMap), dataMap.values().toArray());
// Save the document.
dstDoc.save(MessageFormat.format(dataDir + "TestFile Out {0}.doc", counter++));
}
}
/**
* Creates a Hashtable from the name and value of each column in the current row of the ResultSet.
*/
public static Hashtable getRowData(ResultSet rs) throws Exception
{
ResultSetMetaData metaData = rs.getMetaData();
Hashtable values = new Hashtable();
for(int i = 1; i <= metaData.getColumnCount(); i++)
{
values.put(metaData.getColumnName(i), rs.getObject(i));
}
return values;
}
/**
* Utility function that returns the keys of a Hashtable as an array of Strings.
*/
public static String[] keySetToArray(Hashtable table)
{
return (String[])table.keySet().toArray(new String[table.size()]);
}
/**
* Executes a query to the demo database using a new statement and returns
* the result in a ResultSet.
*/
protected static ResultSet executeQuery(String query) throws Exception {
return createStatement().executeQuery(query);
}
/**
* Utility function that creates a connection to the Database.
*/
public static void createConnection(String dataDir) throws Exception {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connectionString = "jdbc:ucanaccess://" + dataDir + "Customers.mdb";
// Create a connection to the database.
mConnection = DriverManager.getConnection(connectionString);
}
/**
* Utility function that creates a statement to the database.
*/
public static Statement createStatement() throws Exception {
return mConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(MustacheTemplateSyntax.class);
// Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
// the XML data file and store it in memory.
javax.xml.parsers.DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Parse the XML data.
org.w3c.dom.Document xmlData = db.parse(dataDir + "Orders.xml");
// Open a template document.
Document doc = new Document(dataDir + "ExecuteTemplate.doc");
doc.getMailMerge().setUseNonMergeFields(true);
// Note that this class also works with a single repeatable region (and any nested regions).
// To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
// e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
// Save the output document.
doc.save(dataDir + "Output.docx");
System.out.println("Mail merge performed successfully.");
private static final String dataDir = Utils.getSharedDataDir(NestedMailMergeRegions.class) + "MailMerge/";
private static Connection mConnection;
public static void main(String[] args) throws Exception {
// Create the dataset which will hold each DataTable used for mail merge.
DataSet pizzaDs = new DataSet();
// Create a connection to the database
createConnection(dataDir);
// Populate each DataTable from the database. Each query which returns a ResultSet object containing the data from the table.
// This ResultSet is wrapped into an Aspose.Words implementation of the DataTable class and added to a DataSet.
DataTable orders = new DataTable(executeQuery("SELECT * from Orders"), "Orders");
pizzaDs.getTables().add(orders);
DataTable itemDetails = new DataTable(executeQuery("SELECT * from Items"), "Items");
pizzaDs.getTables().add(itemDetails);
// In order for nested mail merge to work, the mail merge engine must know the relation between parent and child tables.
// Add a DataRelation to specify relations between these tables.
pizzaDs.getRelations().add(new DataRelation("OrderToItemDetails", orders, itemDetails, new String[] { "OrderID" }, new String[] { "OrderID" }));
// Open the template document.
Document doc = new Document(dataDir + "Invoice Template.doc");
// Trim trailing and leading whitespaces mail merge values
//doc.getMailMerge().setTrimWhitespaces(false);
// Execute nested mail merge with regions
doc.getMailMerge().executeWithRegions(pizzaDs);
// Save the output to disk
doc.save(dataDir + "Invoice Out.doc");
assert doc.getMailMerge().getFieldNames().length == 0 : "There was a problem with mail merge";
}
/**
* Executes a query to the demo database using a new statement and returns
* the result in a ResultSet.
*/
protected static ResultSet executeQuery(String query) throws Exception {
return createStatement().executeQuery(query);
}
/**
* Utility function that creates a connection to the Database.
*/
public static void createConnection(String dataDir) throws Exception {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connectionString = "jdbc:ucanaccess://" + dataDir + "InvoiceDB.mdb";
// Create a connection to the database.
mConnection = DriverManager.getConnection(connectionString);
}
/**
* Utility function that creates a statement to the database.
*/
public static Statement createStatement() throws Exception {
return mConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
public class ProduceMultipleDocumentsDuringMailMerge {
private static final String dataDir = Utils.getSharedDataDir(ProduceMultipleDocumentsDuringMailMerge.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
produceMultipleDocuments(dataDir, "TestFile.doc");
}
public static void produceMultipleDocuments(String dataDir, String srcDoc) throws Exception {
// Open the database connection.
ResultSet rs = getData(dataDir, "SELECT * FROM Customers");
// Open the template document.
Document doc = new Document(dataDir + srcDoc);
// A record of how many documents that have been generated so far.
int counter = 1;
// Loop though all records in the data source.
while (rs.next()) {
// Clone the template instead of loading it from disk (for speed).
Document dstDoc = (Document) doc.deepClone(true);
// Extract the data from the current row of the ResultSet into a Hashtable.
Hashtable dataMap = getRowData(rs);
// Execute mail merge.
dstDoc.getMailMerge().execute(keySetToArray(dataMap), dataMap.values().toArray());
// Save the document.
dstDoc.save(MessageFormat.format(dataDir + "TestFile Out {0}.doc", counter++));
}
}
/**
* Creates a Hashtable from the name and value of each column in the current
* row of the ResultSet.
*/
public static Hashtable getRowData(ResultSet rs) throws Exception {
ResultSetMetaData metaData = rs.getMetaData();
Hashtable values = new Hashtable();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
values.put(metaData.getColumnName(i), rs.getObject(i));
}
return values;
}
/**
* Utility function that returns the keys of a Hashtable as an array of
* Strings.
*/
public static String[] keySetToArray(Hashtable table) {
return (String[]) table.keySet().toArray(new String[table.size()]);
}
/**
* Utility function that creates a connection to the Database.
*/
public static ResultSet getData(String dataDir, String query) throws Exception {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connectionString = "jdbc:ucanaccess://" + dataDir + "Customers.mdb";
// DSN-less DB connection.
Connection connection = DriverManager.getConnection(connectionString);
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
return statement.executeQuery(query);
}
}
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Create a dummy data source containing no data.
DataSet data = new DataSet();
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
// Execute mail merge which will have no effect as there is no data. However the regions found in the document will be removed
// automatically as they are unused.
doc.getMailMerge().executeWithRegions(data);
// Save the output document to disk.
doc.save(dataDir + "TestFile.RemoveEmptyRegions Out.doc");
// 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(RemoveUnmergedRegions.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Create a dummy data source containing no data.
DataSet data = new DataSet();
// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);
// Execute mail merge which will have no effect as there is no data. However the regions found in the document will be removed
// automatically as they are unused.
doc.getMailMerge().executeWithRegions(data);
// Save the output document to disk.
doc.save(dataDir + "Output.doc");
// 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(SimpleMailMerge.class);
// Open the document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");
doc.getMailMerge().setUseNonMergeFields(true);
doc.getMailMerge().execute(
new String[]{"FullName", "Company", "Address", "Address2", "City"},
new Object[]{"James Bond", "MI5 Headquarters", "Milbank", "", "London"});
// Save the output document to disk.
doc.save(dataDir + "Output.doc");
/**
* This sample demonstrates how to execute mail merge with data from an XML data
* source. The XML file is read into memory, stored in a DOM and passed to a
* custom data source implementing IMailMergeDataSource. This returns each value
* from XML when called by the mail merge engine.
*/
public class XMLMailMerge {
private static final String dataDir = Utils.getSharedDataDir(XMLMailMerge.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
// Use DocumentBuilder from the javax.xml.parsers package and Document class from the org.w3c.dom package to read
// the XML data file and store it in memory.
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Parse the XML data.
org.w3c.dom.Document xmlData = db.parse(dataDir + "Customers.xml");
// Open a template document.
Document doc = new Document(dataDir + "TestFile.doc");
// Note that this class also works with a single repeatable region (and any nested regions).
// To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
// e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
doc.getMailMerge().execute(new XmlMailMergeDataTable(xmlData, "customer"));
// Save the output document.
doc.save(dataDir + "TestFile Out.doc");
System.out.println("Mail merge performed successfully.");
}
}
public class XmlMailMergeDataSet implements IMailMergeDataSourceRoot
{
/**
* Creates a new XmlMailMergeDataSet for the specified XML document. All regions in the document can be
* merged at once using this class.
*
* @param xmlDoc The DOM object which contains the parsed XML data.
*/
public XmlMailMergeDataSet(org.w3c.dom.Document xmlDoc)
{
mXmlDoc = xmlDoc;
}
public IMailMergeDataSource getDataSource(String tableName) throws Exception
{
return new XmlMailMergeDataTable(mXmlDoc, tableName);
}
private org.w3c.dom.Document mXmlDoc;
}
/**
* A custom mail merge data source that allows you to merge data from an XML
* document into Word templates. This class demonstrates how data can be read
* from a custom data source (XML parsed and loaded into a DOM) and merged into
* a document using the IMailMergeDataSource interface.
*
* An instance of this class represents a single table in the data source and in
* the template. Note: We are using the Document and Node class from the
* org.w3c.dom package here and not from Aspose.Words.
*/
public class XmlMailMergeDataTable implements IMailMergeDataSource {
/**
* Creates a new XmlMailMergeDataSource for the specified XML document and
* table name.
*
* @param xmlDoc
* The DOM object which contains the parsed XML data.
* @param tableName
* The name of the element in the data source where the data of
* the region is extracted from.
*/
public XmlMailMergeDataTable(org.w3c.dom.Document xmlDoc, String tableName) throws Exception {
this(xmlDoc.getDocumentElement(), tableName);
}
/**
* Private constructor that is also called by GetChildDataSource.
*/
private XmlMailMergeDataTable(Node rootNode, String tableName) throws Exception {
mTableName = tableName;
// Get the first element on this level matching the table name.
mCurrentNode = (Node) retrieveExpression("./" + tableName).evaluate(rootNode, XPathConstants.NODE);
}
/**
* The name of the data source. Used by Aspose.Words only when executing
* mail merge with repeatable regions.
*/
public String getTableName() {
return mTableName;
}
/**
* Aspose.Words calls this method to get a value for every data field.
*/
public boolean getValue(String fieldName, Ref<Object> fieldValue) throws Exception{
// Attempt to retrieve the child node matching the field name by using XPath.
Node value = (Node) retrieveExpression(fieldName).evaluate(mCurrentNode, XPathConstants.NODE);
// We also look for the field name in attributes of the element node.
Element nodeAsElement = (Element) mCurrentNode;
if (value != null) {
// Field exists in the data source as a child node, pass the value and return true.
// This merges the data into the document.
fieldValue.set(value.getTextContent());
return true;
} else if (nodeAsElement.hasAttribute(fieldName)) {
// Field exists in the data source as an attribute of the current node, pass the value and return true.
// This merges the data into the document.
fieldValue.set(nodeAsElement.getAttribute(fieldName));
return true;
} else {
// Field does not exist in the data source, return false.
// No value will be merged for this field and it is left over in the document.
return false;
}
}
/**
* Moves to the next record in a collection. This method is a little
* different then the regular implementation as we are walking over an XML
* document stored in a DOM.
*/
public boolean moveNext() {
if (!isEof()) {
// Don't move to the next node if this the first record to be merged.
if (!mIsFirstRecord) {
// Find the next node which is an element and matches the table name represented by this class.
// This skips any text nodes and any elements which belong to a different table.
do {
mCurrentNode = mCurrentNode.getNextSibling();
} while ((mCurrentNode != null) && !(mCurrentNode.getNodeName().equals(mTableName) && (mCurrentNode.getNodeType() == Node.ELEMENT_NODE)));
} else {
mIsFirstRecord = false;
}
}
return (!isEof());
}
/**
* If the data source contains nested data this method will be called to
* retrieve the data for the child table. In the XML data source nested data
* this should look like this:
*
* <Tables>
* <ParentTable>
* <Name>ParentName</Name>
* <ChildTable>
* <Text>Content</Text>
* </ChildTable>
* </ParentTable>
* </Tables>
*/
public IMailMergeDataSource getChildDataSource(String tableName) throws Exception {
return new XmlMailMergeDataTable(mCurrentNode, tableName);
}
private boolean isEof() {
return (mCurrentNode == null);
}
/**
* Returns a cached version of a compiled XPathExpression if available,
* otherwise creates a new expression.
*/
private XPathExpression retrieveExpression(String path) throws Exception {
XPathExpression expression;
if (mExpressionSet.containsKey(path)) {
expression = (XPathExpression) mExpressionSet.get(path);
} else {
expression = mXPath.compile(path);
mExpressionSet.put(path, expression);
}
return expression;
}
/**
* Instance variables.
*/
private Node mCurrentNode;
private boolean mIsFirstRecord = true;
private final String mTableName;
private final HashMap mExpressionSet = new HashMap();
private final XPath mXPath = XPathFactory.newInstance().newXPath();
}
// 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(AccessBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
Bookmark bookmark1 = doc.getRange().getBookmarks().get(0);
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
doc.save(dataDir + "output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(AccessBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
Bookmark bookmark1 = doc.getRange().getBookmarks().get(0);
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
doc.save(dataDir + "output.doc");
System.out.println("\nTable bookmarked successfully.\nFile saved at " + dataDir);
// 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(BookmarkNameAndText.class);
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
// Get the name and text of the bookmark.
String name = bookmark.getName();
String text = bookmark.getText();
// Set the name and text of the bookmark.
bookmark.setName("RenamedBookmark");
bookmark.setText("This is a new bookmarked text.");
// The path to the documents directory.
String dataDir = Utils.getDataDir(BookmarkNameAndText.class);
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
// Get the name and text of the bookmark.
String name = bookmark.getName();
String text = bookmark.getText();
// Set the name and text of the bookmark.
bookmark.setName("RenamedBookmark");
bookmark.setText("This is a new bookmarked text.");
System.out.println("\nBookmark name and text set successfully.");
// The path to the documents directory.
String dataDir = Utils.getDataDir(BookmarkTable.class);
//Create empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// We call this method to start building the table.
builder.startTable();
builder.insertCell();
// Start bookmark here after calling InsertCell
builder.startBookmark("MyBookmark");
builder.write("Row 1, Cell 1 Content.");
// Build the second cell
builder.insertCell();
builder.write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.endRow();
// Build the first cell of the second row.
builder.insertCell();
builder.write("Row 2, Cell 1 Content");
// Build the second cell.
builder.insertCell();
builder.write("Row 2, Cell 2 Content.");
builder.endRow();
// Signal that we have finished building the table.
builder.endTable();
//End of bookmark
builder.endBookmark("MyBookmark");
doc.save(dataDir+ "output.doc");
System.out.println("\nTable bookmarked successfully.\nFile saved at " + dataDir);
// Create empty document
Document doc = new Document(dataDir + "Bookmark.Table_out.doc");
for (Bookmark bookmark : doc.getRange().getBookmarks())
{
System.out.printf("Bookmark: {0}{1}", bookmark.getName(), bookmark.isColumn() ? " (Column)" : "");
if (bookmark.isColumn())
{
Row row = (Row) bookmark.getBookmarkStart().getAncestor(NodeType.ROW);
if (row != null && bookmark.getFirstColumn() < row.getCells().getCount())
System.out.print(row.getCells().get(bookmark.getFirstColumn()).getText());
}
}
// This is the paragraph that contains the beginning of the bookmark.
Paragraph startPara = (Paragraph)srcBookmark.getBookmarkStart().getParentNode();
// This is the paragraph that contains the end of the bookmark.
Paragraph endPara = (Paragraph)srcBookmark.getBookmarkEnd().getParentNode();
if ((startPara == null) || (endPara == null))
throw new IllegalStateException("Parent of the bookmark start or end is not a paragraph, cannot handle this scenario yet.");
// Limit ourselves to a reasonably simple scenario.
if (startPara.getParentNode() != endPara.getParentNode())
throw new IllegalStateException("Start and end paragraphs have different parents, cannot handle this scenario yet.");
// We want to copy all paragraphs from the start paragraph up to (and including) the end paragraph,
// therefore the node at which we stop is one after the end paragraph.
Node endNode = endPara.getNextSibling();
// This is the loop to go through all paragraph-level nodes in the bookmark.
for (Node curNode = startPara; curNode != endNode; curNode = curNode.getNextSibling())
{
// This creates a copy of the current node and imports it (makes it valid) in the context
// of the destination document. Importing means adjusting styles and list identifiers correctly.
Node newNode = importer.importNode(curNode, true);
// Now we simply append the new node to the destination.
dstNode.appendChild(newNode);
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyBookmarkedText.class);
// Load the source document.
Document srcDoc = new Document(dataDir + "Template.doc");
// This is the bookmark whose content we want to copy.
Bookmark srcBookmark = srcDoc.getRange().getBookmarks().get("ntf010145060");
// We will be adding to this document.
Document dstDoc = new Document();
// Let's say we will be appending to the end of the body of the last section.
CompositeNode dstNode = dstDoc.getLastSection().getBody();
// It is a good idea to use this import context object because multiple nodes are being imported.
// If you import multiple times without a single context, it will result in many styles created.
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
// Do it once.
appendBookmarkedText(importer, srcBookmark, dstNode);
// Do it one more time for fun.
appendBookmarkedText(importer, srcBookmark, dstNode);
// Save the finished document.
dstDoc.save(dataDir + "Template Out.doc");
System.out.println("Bookmarked text copied successfully.");
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateBookmark.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("MyBookmark");
builder.writeln("Text inside a bookmark.");
builder.endBookmark("MyBookmark");
builder.startBookmark("Nested Bookmark");
builder.writeln("Text inside a NestedBookmark.");
builder.endBookmark("Nested Bookmark");
builder.writeln("Text after Nested Bookmark.");
builder.endBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.getOutlineOptions().setDefaultBookmarksOutlineLevel(1);
options.getOutlineOptions().setDefaultBookmarksOutlineLevel(2);
doc.save(dataDir + "output.pdf", options);
System.out.println("\nBookmark created successfully.");
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetAndSetBookmarkNameAndText.class);
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
// Get the name and text of the bookmark.
String name = bookmark.getName();
String text = bookmark.getText();
// Set the name and text of the bookmark.
bookmark.setName("RenamedBookmark");
bookmark.setText("This is a new bookmarked text.");
System.out.println("\nBookmark name and text set successfully.");
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertBookmarksWithWhiteSpaces.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("My Bookmark");
builder.writeln("Text inside a bookmark.");
builder.startBookmark("Nested Bookmark");
builder.writeln("Text inside a NestedBookmark.");
builder.endBookmark("Nested Bookmark");
builder.writeln("Text after Nested Bookmark.");
builder.endBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.getOutlineOptions().getBookmarksOutlineLevels().add("My Bookmark", 1);
options.getOutlineOptions().getBookmarksOutlineLevels().add("Nested Bookmark", 2);
dataDir = dataDir + "Insert.Bookmarks_out_.pdf";
doc.save(dataDir, options);
System.out.println("\nBookmarks with white spaces inserted successfully.\nFile saved at " + dataDir);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ObtainBookmarkByIndexAndName.class);
Document doc = new Document(dataDir + "Bookmarks.doc");
// By index.
Bookmark bookmark1 = doc.getRange().getBookmarks().get(0);
System.out.println("\nBookmark by index is " + bookmark1.getText());
// By name.
Bookmark bookmark2 = doc.getRange().getBookmarks().get("Bookmark2");
System.out.println("\nBookmark by name is " + bookmark2.getText());
public static void showHideBookmarkedContent(Document doc, String bookmarkName, boolean showHide) throws Exception {
DocumentBuilder builder = new DocumentBuilder(doc);
Bookmark bm = doc.getRange().getBookmarks().get(bookmarkName);
builder.moveToDocumentEnd();
// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
Field field = builder.insertField("IF \"", null);
builder.moveTo(field.getStart().getNextSibling().getNextSibling());
builder.insertField("MERGEFIELD " + bookmarkName + "", null);
builder.write("\" = \"true\" ");
builder.write("\"");
builder.write("\"");
builder.write(" \"\"");
Node currentNode = field.getStart();
boolean flag = true;
while (currentNode != null && flag) {
if (currentNode.getNodeType() == NodeType.RUN)
if (currentNode.toString(SaveFormat.TEXT).trim().equals("\""))
flag = false;
Node nextNode = currentNode.getNextSibling();
bm.getBookmarkStart().getParentNode().insertBefore(currentNode, bm.getBookmarkStart());
currentNode = nextNode;
}
Node endNode = bm.getBookmarkEnd();
flag = true;
while (currentNode != null && flag) {
if (currentNode.getNodeType() == NodeType.FIELD_END)
flag = false;
Node nextNode = currentNode.getNextSibling();
bm.getBookmarkEnd().getParentNode().insertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
}
doc.getMailMerge().execute(new String[]{bookmarkName}, new Object[]{showHide});
//In case, you do not want to use MailMerge then you may use the following lines of code.
//builder.moveToMergeField(bookmarkName);
//builder.write(showHide ? "true" : "false");
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(ShowHideBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
showHideBookmarkedContent(doc,"MyBookmark",false);
doc.save(dataDir + "Updated_Document.docx");
// The path to the documents directory.
String dataDir = Utils.getDataDir(UntangleRowBookmarks.class);
// Load a document.
Document doc = new Document(dataDir + "TestDefect1352.doc");
// This perform the custom task of putting the row bookmark ends into the same row with the bookmark starts.
untangleRowBookmarks(doc);
// Now we can easily delete rows by a bookmark without damaging any other row's bookmarks.
deleteRowByBookmark(doc, "ROW2");
// This is just to check that the other bookmark was not damaged.
if (doc.getRange().getBookmarks().get("ROW1").getBookmarkEnd() == null)
throw new Exception("Wrong, the end of the bookmark was deleted.");
// Save the finished document.
doc.save(dataDir + "TestDefect1352 Out.doc");
System.out.println("Untangled row bookmarks successfully.");
// Find the bookmark in the document. Exit if cannot find it.
Bookmark bookmark = doc.getRange().getBookmarks().get(bookmarkName);
if (bookmark == null)
return;
// Get the parent row of the bookmark. Exit if the bookmark is not in a row.
Row row = (Row)bookmark.getBookmarkStart().getAncestor(Row.class);
if (row == null)
return;
// Remove the row.
row.remove();
for (Bookmark bookmark : doc.getRange().getBookmarks())
{
// Get the parent row of both the bookmark and bookmark end node.
Row row1 = (Row)bookmark.getBookmarkStart().getAncestor(Row.class);
Row row2 = (Row)bookmark.getBookmarkEnd().getAncestor(Row.class);
// If both rows are found okay and the bookmark start and end are contained
// in adjacent rows, then just move the bookmark end node to the end
// of the last paragraph in the last cell of the top row.
if ((row1 != null) && (row2 != null) && (row1.getNextSibling() == row2))
row1.getLastCell().getLastParagraph().appendChild(bookmark.getBookmarkEnd());
}
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
Chart chart = shape.getChart();
// Determines whether the title shall be shown for this chart. Default is true.
chart.getTitle().setShow(true);
// Setting chart Title.
chart.getTitle().setText("Sample Line Chart Title");
// Determines whether other chart elements shall be allowed to overlap title.
chart.getTitle().setOverlay(false);
// Please note if null or empty value is specified as title text, auto generated title will be shown.
// Determines how legend shall be shown for this chart.
chart.getLegend().setPosition(LegendPosition.LEFT);
chart.getLegend().setOverlay(true);
doc.save(dataDir + "ChartAppearance_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
// Get first series.
ChartSeries series0 = shape.getChart().getSeries().get(0);
// Get second series.
ChartSeries series1 = shape.getChart().getSeries().get(1);
// Specifies whether by default the parent element shall inverts its colors if the value is negative.
series0.setInvertIfNegative(true);
// Set default marker symbol and size.
series0.getMarker().setSymbol(MarkerSymbol.CIRCLE);
series0.getMarker().setSize(15);
series1.getMarker().setSymbol(MarkerSymbol.STAR);
series1.getMarker().setSize(10);
doc.save(dataDir + "ChartDataPoints_out.docx");//
// Working with Charts through Shape.Chart Object
changeChartAppearanceUsingShapeChartObject();
// Working with Single ChartSeries Class
workingWithSingleChartSeries();
//All single ChartSeries have default ChartDataPoint options, lets change them
changeDefaultChartDataPointOptions();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
// Get first series.
ChartSeries series0 = shape.getChart().getSeries().get(0);
// Get second series.
ChartSeries series1 = shape.getChart().getSeries().get(1);
// Change first series name.
series0.setName("My Name1");
// Change second series name.
series1.setName("My Name2");
// You can also specify whether the line connecting the points on the chart shall be smoothed using Catmull-Rom splines.
series0.setSmooth(true);
series1.setSmooth(true);
doc.save(dataDir + "SingleChartSeries_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add chart with default data.
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
Chart chart = shape.getChart();
chart.getTitle().setText("Data Labels With Different Number Format");
// Delete default generated series.
chart.getSeries().clear();
// Add new series
ChartSeries series0 = chart.getSeries().add("AW Series 0", new String[]{"AW0", "AW1", "AW2"}, new double[]{2.5, 1.5, 3.5});
series0.hasDataLabels(true);
// Set currency format code.
series0.getDataLabels().get(0).getNumberFormat().setFormatCode("\"$\"#,##0.00");
// Set date format code.
series0.getDataLabels().get(1).getNumberFormat().setFormatCode("d/mm/yyyy");
// Set percentage format code.
series0.getDataLabels().get(2).getNumberFormat().setFormatCode("0.00%");
// Or you can set format code to be linked to a source cell,
// in this case NumberFormat will be reset to general and inherited from a source cell.
series0.getDataLabels().get(2).getNumberFormat().isLinkedToSource(true);
doc.save(dataDir + "NumberFormat_DataLabel_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.PIE, 432, 252);
Chart chart = shape.getChart();
chart.getSeries().clear();
ChartSeries series = chart.getSeries().add("Series 1",
new String[] { "Category1", "Category2", "Category3" },
new double[] { 2.7, 3.2, 0.8 });
ChartDataLabelCollection labels = series.getDataLabels();
labels.setShowPercentage(true);
labels.setShowValue(true);
labels.setShowLeaderLines(false);
labels.setSeparator(" - ");
doc.save(dataDir + "Demo.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Area chart.
Shape shape = builder.insertChart(ChartType.AREA, 432, 252);
Chart chart = shape.getChart();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("01/01/2016");
Date date2 = sdf.parse("02/02/2016");
Date date3 = sdf.parse("03/03/2016");
Date date4 = sdf.parse("04/04/2016");
Date date5 = sdf.parse("05/05/2016");
// Use this overload to add series to any type of Area, Radar and Stock charts.
chart.getSeries().add ("AW Series 1", new Date[] {date1, date2, date3, date4, date5}, new double[] {32, 32, 28, 12, 15});
doc.save(dataDir + "TestInsertAreaChart_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Bubble chart.
Shape shape = builder.insertChart(ChartType.BUBBLE, 432, 252);
Chart chart = shape.getChart();
// Use this overload to add series to any type of Bubble charts.
chart.getSeries().add("AW Series 1", new double[] { 0.7, 1.8, 2.6 }, new double[] { 2.7, 3.2, 0.8 }, new double[] { 10, 4, 8 });
doc.save(dataDir + "TestInsertBubbleChart_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add chart with default data. You can specify different chart types and sizes.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
// Chart property of Shape contains all chart related options.
Chart chart = shape.getChart();
// Get chart series collection.
ChartSeriesCollection seriesColl = chart.getSeries();
// Delete default generated series.
seriesColl.clear();
// Create category names array, in this example we have two categories.
String[] categories = new String[] { "AW Category 1", "AW Category 2" };
// Adding new series. Please note, data arrays must not be empty and arrays must be the same size.
seriesColl.add("AW Series 1", categories, new double[] { 1, 2 });
seriesColl.add("AW Series 2", categories, new double[] { 3, 4 });
seriesColl.add("AW Series 3", categories, new double[] { 5, 6 });
seriesColl.add("AW Series 4", categories, new double[] { 7, 8 });
seriesColl.add("AW Series 5", categories, new double[] { 9, 10 });
doc.save(dataDir + "TestInsertChartColumn1_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Column chart.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
// Use this overload to add series to any type of Bar, Column, Line and Surface charts.
chart.getSeries().add("AW Series 1", new String[] { "AW Category 1", "AW Category 2" }, new double[] { 1, 2 });
doc.save(dataDir + "TestInsertColumnChart2_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert Scatter chart.
Shape shape = builder.insertChart(ChartType.SCATTER, 432, 252);
Chart chart = shape.getChart();
// Use this overload to add series to any type of Scatter charts.
chart.getSeries().add("AW Series 1", new double[] { 0.7, 1.8, 2.6 }, new double[] { 2.7, 3.2, 0.8 });
doc.save(dataDir + "TestInsertScatterChart_out.docx");
// Insert Column chart
insertColumnChart1();
insertColumnChart2();
// Insert Scatter chart
insertScatterChart();
// Insert Area chart
insertAreaChart();
// Insert Bubble chart
insertBubbleChart();
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.insertChart(ChartType.AREA, 432, 252);
Chart chart = shape.getChart();
// Clear demo data.
chart.getSeries().clear();
// Fill data.
chart.getSeries().add("AW Series 1",
new Date[]{new Date(2002, 1, 1), new Date(2002, 6, 1), new Date(2015, 7, 1), new Date(2015, 8, 1), new Date(2015, 9, 1)},
new double[]{640, 320, 280, 120, 150});
ChartAxis xAxis = chart.getAxisX();
ChartAxis yAxis = chart.getAxisY();
// Change the X axis to be category instead of date, so all the points will be put with equal interval on the X axis.
xAxis.setCategoryType(AxisCategoryType.CATEGORY);
// Define X axis properties.
xAxis.setCrosses(AxisCrosses.CUSTOM);
xAxis.setCrossesAt(3); // measured in display units of the Y axis (hundreds)
xAxis.setReverseOrder(true);
xAxis.setMajorTickMark(AxisTickMark.CROSS);
xAxis.setMinorTickMark(AxisTickMark.OUTSIDE);
xAxis.setTickLabelOffset(200);
// Define Y axis properties.
yAxis.setTickLabelPosition(AxisTickLabelPosition.HIGH);
yAxis.setMajorUnit(100);
yAxis.setMinorUnit(50);
yAxis.getDisplayUnit().setUnit(AxisBuiltInUnit.HUNDREDS);
yAxis.getScaling().setMinimum(new AxisBound(100));
yAxis.getScaling().setMaximum(new AxisBound(700));
dataDir = dataDir + "SetAxisProperties_out.docx";
doc.save(dataDir);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
// Clear demo data.
chart.getSeries().clear();
// Fill data.
chart.getSeries().add("AW Series 1",
new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
new double[] { 1.2, 0.3, 2.1, 2.9, 4.2 });
// Hide the Y axis.
chart.getAxisY().setHidden(true);
dataDir = dataDir + "HideChartAxis_out.docx";
doc.save(dataDir);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
// Clear demo data.
chart.getSeries().clear();
// Fill data.
chart.getSeries().add("AW Series 1",
new String[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"},
new double[]{1.2, 0.3, 2.1, 2.9, 4.2});
chart.getAxisY().getScaling().setMinimum(new AxisBound(0));
chart.getAxisY().getScaling().setMaximum(new AxisBound(6));
dataDir = dataDir + "SetboundsOfAxis_out.docx";
doc.save(dataDir);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
// Clear demo data.
chart.getSeries().clear();
// Fill data.
chart.getSeries().add("AW Series 1",
new Date[]{new Date(2017, 11, 06), new Date(2017, 11, 9), new Date(2017, 11, 15),
new Date(2017, 11, 21), new Date(2017, 11, 25), new Date(2017, 11, 29)},
new double[]{1.2, 0.3, 2.1, 2.9, 4.2, 5.3}
);
// Set X axis bounds.
ChartAxis xAxis = chart.getAxisX();
xAxis.getScaling().setMinimum(new AxisBound(new Date(2017, 11, 5).getTime()));
xAxis.getScaling().setMaximum(new AxisBound(new Date(2017, 12, 3).getTime()));
// Set major units to a week and minor units to a day.
xAxis.setMajorUnit(7);
xAxis.setMinorUnit(1);
xAxis.setMajorTickMark(AxisTickMark.CROSS);
xAxis.setMinorTickMark(AxisTickMark.OUTSIDE);
dataDir = dataDir + "SetDateTimeValuesToAxis_out.docx";
doc.save(dataDir);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
// Clear demo data.
chart.getSeries().clear();
// Fill data.
chart.getSeries().add("AW Series 1",
new String[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"},
new double[]{1.2, 0.3, 2.1, 2.9, 4.2});
chart.getAxisX().setTickLabelSpacing(2);
dataDir = dataDir + "SetIntervalUnitBetweenLabelsOnAxis_out.docx";
doc.save(dataDir);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
// Clear demo data.
chart.getSeries().clear();
// Fill data.
chart.getSeries().add("AW Series 1",
new String[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"},
new double[]{1900000, 850000, 2100000, 600000, 1500000});
// Set number format.
chart.getAxisY().getNumberFormat().setFormatCode("#,##0");
dataDir = dataDir + "FormatAxisNumber_out.docx";
doc.save(dataDir);
Document doc = new Document(dataDir + "Document.docx");
Shape shape = (Shape)doc.getChild(NodeType.SHAPE, 0, true);
ChartAxis axis = shape.getChart().getAxisX();
//This property has effect only for multi-line labels.
axis.setTickLabelAlignment(ParagraphAlignment.RIGHT);
doc.save(dataDir + "Document_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.BAR, 432, 252);
// Get first series.
ChartSeries series0 = shape.getChart().getSeries().get(0);
series0.hasDataLabels(true);
// Set properties.
series0.getDataLabels().setShowLegendKey(true);
// By default, when you add data labels to the data points in a pie chart, leader lines are displayed for data labels that are
// positioned far outside the end of data points. Leader lines create a visual connection between a data label and its
// corresponding data point.
series0.getDataLabels().setShowLeaderLines(true);
series0.getDataLabels().setShowCategoryName(false);
series0.getDataLabels().setShowPercentage(false);
series0.getDataLabels().setShowSeriesName(true);
series0.getDataLabels().setShowValue(true);
series0.getDataLabels().setSeparator("/");
series0.getDataLabels().setShowValue(true);
doc.save(dataDir + "ChartDataLabelOfASingleChartSeries_out.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
// Chart property of Shape contains all chart related options.
Chart chart = shape.getChart();
// Get chart series collection.
ChartSeriesCollection seriesCollection = chart.getSeries();
// Check series count.
System.out.println(seriesCollection.getCount());
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
// Chart property of Shape contains all chart related options.
Chart chart = shape.getChart();
// Get chart series collection.
ChartSeriesCollection seriesCollection = chart.getSeries();
// Check series count.
System.out.println(seriesCollection.getCount());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
// Get first series.
ChartSeries series0 = shape.getChart().getSeries().get(0);
// Get second series.
ChartSeries series1 = shape.getChart().getSeries().get(1);
ChartDataPointCollection dataPointCollection = series0.getDataPoints();
// Add data point to the first and second point of the first series.
ChartDataPoint dataPoint00 = dataPointCollection.add(0);
ChartDataPoint dataPoint01 = dataPointCollection.add(1);
// Set explosion.
dataPoint00.setExplosion(50);
// Set marker symbol and size.
dataPoint00.getMarker().setSymbol(MarkerSymbol.CIRCLE);
dataPoint00.getMarker().setSize(15);
dataPoint01.getMarker().setSymbol(MarkerSymbol.DIAMOND);
dataPoint01.getMarker().setSize(20);
// Add data point to the third point of the second series.
ChartDataPoint dataPoint12 = series1.getDataPoints().add(2);
dataPoint12.setInvertIfNegative(true);
dataPoint12.getMarker().setSymbol(MarkerSymbol.STAR);
dataPoint12.getMarker().setSize(20);
doc.save(dataDir + "SingleChartDataPointOfAChartSeries_out.docx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.LINE, 432, 252);
// Get first series.
ChartSeries series0 = shape.getChart().getSeries().get(0);
// Get second series.
ChartSeries series1 = shape.getChart().getSeries().get(1);
ChartDataPointCollection dataPointCollection = series0.getDataPoints();
// Add data point to the first and second point of the first series.
ChartDataPoint dataPoint00 = dataPointCollection.add(0);
ChartDataPoint dataPoint01 = dataPointCollection.add(1);
// Set explosion.
dataPoint00.setExplosion(50);
// Set marker symbol and size.
dataPoint00.getMarker().setSymbol(MarkerSymbol.CIRCLE);
dataPoint00.getMarker().setSize(15);
dataPoint01.getMarker().setSymbol(MarkerSymbol.DIAMOND);
dataPoint01.getMarker().setSize(20);
// Add data point to the third point of the second series.
ChartDataPoint dataPoint12 = series1.getDataPoints().add(2);
dataPoint12.setInvertIfNegative(true);
dataPoint12.getMarker().setSymbol(MarkerSymbol.STAR);
dataPoint12.getMarker().setSize(20);
doc.save(dataDir + "SingleChartDataPointOfAChartSeries_out.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(AddComments.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Some text is added.");
Comment comment = new Comment(doc, "Awais Hafeez", "AH", new Date());
builder.getCurrentParagraph().appendChild(comment);
comment.getParagraphs().add(new Paragraph(doc));
comment.getFirstParagraph().getRuns().add(new Run(doc, "Comment text."));
doc.save(dataDir + "output.doc");
String dataDir = Utils.getDataDir(AddComments.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Some text is added.");
Comment comment = new Comment(doc, "Awais Hafeez", "AH", new Date());
builder.getCurrentParagraph().appendChild(comment);
comment.getParagraphs().add(new Paragraph(doc));
comment.getFirstParagraph().getRuns().add(new Run(doc, "Comment text."));
doc.save(dataDir + "output.doc");
Document doc = new Document(dataDir + "TestFile.doc");
Comment comment = (Comment)doc.getChild(NodeType.COMMENT, 0, true);
//Remove the reply
comment.removeReply(comment.getReplies().get(0));
//Add a reply to comment
comment.addReply("John Doe", "JD", new Date(), "New reply");
dataDir = dataDir + "TestFile_Out.doc";
// Save the document to disk.
doc.save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(AnchorComment.class);
Document doc = new Document();
Paragraph para1 = new Paragraph(doc);
Run run1 = new Run(doc, "Some ");
Run run2 = new Run(doc, "text ");
para1.appendChild(run1);
para1.appendChild(run2);
doc.getFirstSection().getBody().appendChild(para1);
Paragraph para2 = new Paragraph(doc);
Run run3 = new Run(doc, "is ");
Run run4 = new Run(doc, "added ");
para2.appendChild(run3);
para2.appendChild(run4);
doc.getFirstSection().getBody().appendChild(para2);
Comment comment = new Comment(doc, "Awais Hafeez", "AH", new Date());
comment.getParagraphs().add(new Paragraph(doc));
comment.getFirstParagraph().getRuns().add(new Run(doc, "Comment text."));
CommentRangeStart commentRangeStart = new CommentRangeStart(doc, comment.getId());
CommentRangeEnd commentRangeEnd = new CommentRangeEnd(doc, comment.getId());
run1.getParentNode().insertAfter(commentRangeStart, run1);
run3.getParentNode().insertAfter(commentRangeEnd, run3);
commentRangeEnd.getParentNode().insertAfter(comment, commentRangeEnd);
doc.save(dataDir + "output.doc");
String dataDir = Utils.getDataDir(AnchorComment.class);
Document doc = new Document();
Paragraph para1 = new Paragraph(doc);
Run run1 = new Run(doc, "Some ");
Run run2 = new Run(doc, "text ");
para1.appendChild(run1);
para1.appendChild(run2);
doc.getFirstSection().getBody().appendChild(para1);
Paragraph para2 = new Paragraph(doc);
Run run3 = new Run(doc, "is ");
Run run4 = new Run(doc, "added ");
para2.appendChild(run3);
para2.appendChild(run4);
doc.getFirstSection().getBody().appendChild(para2);
Comment comment = new Comment(doc, "Awais Hafeez", "AH", new Date());
comment.getParagraphs().add(new Paragraph(doc));
comment.getFirstParagraph().getRuns().add(new Run(doc, "Comment text."));
CommentRangeStart commentRangeStart = new CommentRangeStart(doc, comment.getId());
CommentRangeEnd commentRangeEnd = new CommentRangeEnd(doc, comment.getId());
run1.getParentNode().insertAfter(commentRangeStart, run1);
run3.getParentNode().insertAfter(commentRangeEnd, run3);
commentRangeEnd.getParentNode().insertAfter(comment, commentRangeEnd);
doc.save(dataDir + "output.doc");
// 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(ExtractComments.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about them.
for (Comment comment : (Iterable<Comment>) comments) {
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
System.out.print(collectedComments);
// 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(ExtractCommentsByAuthor.class);
String authorName = "ks";
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about those written by the authorName author.
for (Comment comment : (Iterable<Comment>) comments) {
if (comment.getAuthor().equals(authorName))
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
System.out.print(collectedComments);
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractCommentsByAuthor.class);
String authorName = "ks";
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about those written by the authorName author.
for (Comment comment : (Iterable<Comment>) comments) {
if (comment.getAuthor().equals(authorName))
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
System.out.print(collectedComments);
// 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(ProcessComments.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
for (String comment : (Iterable<String>) extractComments(doc))
System.out.print(comment);
// Remove comments by the "pm" author.
removeComments(doc, "pm");
System.out.println("Comments from \"pm\" are removed!");
// Extract the information about the comments of the "ks" author.
for (String comment : (Iterable<String>) extractComments(doc, "ks"))
System.out.print(comment);
// Remove all comments.
removeComments(doc);
System.out.println("All comments are removed!");
// Save the document.
doc.save(dataDir + "output.doc");
}
//ExStart
//ExFor:Comment.Author
//ExFor:Comment.DateTime
//ExId:ProcessComments_Extract_All
//ExSummary:Extracts the author name, date&time and text of all comments in the document.
static ArrayList extractComments(Document doc) throws Exception {
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about them.
for (Comment comment : (Iterable<Comment>) comments) {
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
return collectedComments;
}
//ExEnd
//ExStart
//ExId:ProcessComments_Extract_Author
//ExSummary:Extracts the author name, date&time and text of the comments by the specified author.
static ArrayList extractComments(Document doc, String authorName) throws Exception {
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about those written by the authorName author.
for (Comment comment : (Iterable<Comment>) comments) {
if (comment.getAuthor().equals(authorName))
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
return collectedComments;
}
//ExEnd
//ExStart
//ExId:ProcessComments_Remove_All
//ExSummary:Removes all comments in the document.
static void removeComments(Document doc) throws Exception {
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Remove all comments.
comments.clear();
}
//ExEnd
//ExStart
//ExId:ProcessComments_Remove_Author
//ExSummary:Removes comments by the specified author.
static void removeComments(Document doc, String authorName) throws Exception {
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and remove those written by the authorName author.
for (int i = comments.getCount() - 1; i >= 0; i--) {
Comment comment = (Comment) comments.get(i);
if (comment.getAuthor().equals(authorName))
comment.remove();
}
static void CommentResolvedandReplies(Document doc) {
NodeCollection<Comment> comments = doc.getChildNodes(NodeType.COMMENT, true);
Comment parentComment = (Comment) comments.get(0);
for (Comment childComment : parentComment.getReplies()) {
// Get comment parent and status.
System.out.println(childComment.getAncestor().getId());
System.out.println(childComment.getDone());
// And update comment Done mark.
childComment.setDone(true);
}
}
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about them.
for (Comment comment : (Iterable<Comment>) comments) {
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
return collectedComments;
ArrayList collectedComments = new ArrayList();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and gather information about those written by the authorName author.
for (Comment comment : (Iterable<Comment>) comments) {
if (comment.getAuthor().equals(authorName))
collectedComments.add(comment.getAuthor() + " " + comment.getDateTime() + " " + comment.toString(SaveFormat.TEXT));
}
return collectedComments;
// The path to the documents directory.
String dataDir = Utils.getDataDir(ProcessComments.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
for (String comment : (Iterable<String>) extractComments(doc))
System.out.print(comment);
// Remove comments by the "pm" author.
removeComments(doc, "pm");
System.out.println("Comments from \"pm\" are removed!");
// Extract the information about the comments of the "ks" author.
for (String comment : (Iterable<String>) extractComments(doc, "ks"))
System.out.print(comment);
//Read the comment's reply and resolve them.
System.out.println("Read the comment's reply and resolve them.");
CommentResolvedandReplies(doc);
// Remove all comments.
removeComments(doc);
System.out.println("All comments are removed!");
// Save the document.
doc.save(dataDir + "output.doc");
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Remove all comments.
comments.clear();
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and remove those written by the authorName author.
for (int i = comments.getCount() - 1; i >= 0; i--) {
Comment comment = (Comment) comments.get(i);
if (comment.getAuthor().equals(authorName))
comment.remove();
}
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(RemoveCommentRegionText.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
CommentRangeStart commentStart = (CommentRangeStart)doc.getChild(NodeType.COMMENT_RANGE_START, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd)doc.getChild(NodeType.COMMENT_RANGE_END, 0, true);
Node currentNode = commentStart;
Boolean isRemoving = true;
while (currentNode != null && isRemoving)
{
if (currentNode.getNodeType() == NodeType.COMMENT_RANGE_END)
isRemoving = false;
Node nextNode = currentNode.nextPreOrder(doc);
currentNode.remove();
currentNode = nextNode;
}
doc.save(dataDir + "output.doc");
// 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(RemoveCommentRegionText.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
CommentRangeStart commentStart = (CommentRangeStart)doc.getChild(NodeType.COMMENT_RANGE_START, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd)doc.getChild(NodeType.COMMENT_RANGE_END, 0, true);
Node currentNode = commentStart;
Boolean isRemoving = true;
while (currentNode != null && isRemoving)
{
if (currentNode.getNodeType() == NodeType.COMMENT_RANGE_END)
isRemoving = false;
Node nextNode = currentNode.nextPreOrder(doc);
currentNode.remove();
currentNode = nextNode;
}
doc.save(dataDir + "output.doc");
// 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(RemoveComments.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Remove all comments.
comments.clear();
doc.save(dataDir + "output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(RemoveComments.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Remove all comments.
comments.clear();
doc.save(dataDir + "output.doc");
// 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(RemoveCommentsByAuthor.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
String authorName = "pm";
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and remove those written by the authorName author.
for (int i = comments.getCount() - 1; i >= 0; i--) {
Comment comment = (Comment) comments.get(i);
if (comment.getAuthor().equals(authorName))
comment.remove();
}
doc.save(dataDir + "output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(RemoveCommentsByAuthor.class);
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
String authorName = "pm";
// Collect all comments in the document
NodeCollection comments = doc.getChildNodes(NodeType.COMMENT, true);
// Look through all comments and remove those written by the authorName author.
for (int i = comments.getCount() - 1; i >= 0; i--) {
Comment comment = (Comment) comments.get(i);
if (comment.getAuthor().equals(authorName))
comment.remove();
}
doc.save(dataDir + "output.doc");
Document doc = new Document();
StyleCollection styles = doc.getStyles();
for (Style style : styles)
System.out.println(style.getName());
Document doc = new Document();
for(int i =0; i < doc.getStyles().getCount(); i++)
System.out.println(doc.getStyles().get(i).getName());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
doc.ensureMinimum();
GroupShape gs = new GroupShape(doc);
Shape shape = new Shape(doc, ShapeType.ACCENT_BORDER_CALLOUT_1);
shape.setWidth(100);
shape.setHeight(100);
gs.appendChild(shape);
Shape shape1 = new Shape(doc, ShapeType.ACTION_BUTTON_BEGINNING);
shape1.setLeft(100);
shape1.setWidth(100);
shape1.setHeight(200);
gs.appendChild(shape1);
gs.setWidth(200);
gs.setHeight(200);
gs.setCoordSize(new Dimension(200, 200));
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertNode(gs);
doc.save(dataDir + "AddGroupShape_out.docx");
Document doc = new Document();
doc.ensureMinimum();
GroupShape gs = new GroupShape(doc);
Shape shape = new Shape(doc, ShapeType.ACCENT_BORDER_CALLOUT_1);
shape.setWidth(100);
shape.setHeight(100);
gs.appendChild(shape);
Shape shape1 = new Shape(doc, ShapeType.ACTION_BUTTON_BEGINNING);
shape1.setLeft(100);
shape1.setWidth(100);
shape1.setHeight(200);
gs.appendChild(shape1);
gs.setWidth(200);
gs.setHeight(200);
gs.setCoordSize(new Dimension(200, 200));
DocumentBuilder builder = new DocumentBuilder(doc);
builder.insertNode(gs);
doc.save(dataDir + "AddGroupShape_out.docx");
// The path to the documents directory.
String dataDir = Utils.getDataDir(BindingContentControlwithXML.class);
Document doc = new Document();
CustomXmlPart xmlPart = doc.getCustomXmlParts().add(UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d").toString(), "<root><text>Hello, World!</text></root>");
StructuredDocumentTag sdt = new StructuredDocumentTag(doc, SdtType.PLAIN_TEXT, MarkupLevel.BLOCK);
doc.getFirstSection().getBody().appendChild(sdt);
sdt.getXmlMapping().setMapping(xmlPart, "/root[1]/text[1]", "");
dataDir = dataDir + "BindSDTtoCustomXmlPart_out.doc";
// Save the document to disk.
doc.save(dataDir);
// 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(CheckBoxTypeContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag stdCheckBox =new StructuredDocumentTag(doc, SdtType.CHECKBOX, MarkupLevel.INLINE);
builder.insertNode(stdCheckBox);
doc.save(dataDir + "output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(CheckBoxTypeContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag stdCheckBox =new StructuredDocumentTag(doc, SdtType.CHECKBOX, MarkupLevel.INLINE);
builder.insertNode(stdCheckBox);
doc.save(dataDir + "output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(CheckDMLTextEffect.class);
// Initialize document.
Document doc = new Document(dataDir + "Document.doc");
RunCollection runs = doc.getFirstSection().getBody().getFirstParagraph().getRuns();
Font runFont = runs.get(0).getFont();
// One run might have several Dml text effects applied.
System.out.println(runFont.hasDmlEffect(TextDmlEffect.SHADOW));
System.out.println(runFont.hasDmlEffect(TextDmlEffect.EFFECT_3_D));
System.out.println(runFont.hasDmlEffect(TextDmlEffect.REFLECTION));
System.out.println(runFont.hasDmlEffect(TextDmlEffect.OUTLINE));
System.out.println(runFont.hasDmlEffect(TextDmlEffect.FILL));
// The path to the documents directory.
String dataDir = Utils.getDataDir(ClearContentsControl.class);
Document doc = new Document(dataDir + "input.docx");
StructuredDocumentTag sdt = (StructuredDocumentTag) doc.getChild(NodeType.STRUCTURED_DOCUMENT_TAG, 0, true);
sdt.clear();
dataDir = dataDir + "ClearContentsControl_out.doc";
// Save the document to disk.
doc.save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document(dataDir + "Document.doc");
Document clone = doc.deepClone();
// Load the document from disk.
Document doc = new Document(dataDir + "Document.doc");
Document clone = doc.deepClone();
// Save the document to disk.
clone.save(dataDir + "TestFile_clone_out.doc");
// 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(ComboBoxContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag sdt =new StructuredDocumentTag(doc, SdtType.COMBO_BOX, MarkupLevel.BLOCK);
sdt.getListItems().add(new SdtListItem("Choose an item", "3"));
sdt.getListItems().add(new SdtListItem("Item 1", "1"));
sdt.getListItems().add(new SdtListItem("Item 2", "2"));
doc.getFirstSection().getBody().appendChild(sdt);
doc.save(dataDir + "output.doc");
// The path to the documents directory.
String dataDir = Utils.getDataDir(ComboBoxContentControl.class);
// Open the document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
StructuredDocumentTag sdt =new StructuredDocumentTag(doc, SdtType.COMBO_BOX, MarkupLevel.BLOCK);
sdt.getListItems().add(new SdtListItem("Choose an item", "3"));
sdt.getListItems().add(new SdtListItem("Item 1", "1"));
sdt.getListItems().add(new SdtListItem("Item 2", "2"));
doc.getFirstSection().getBody().appendChild(sdt);
doc.save(dataDir + "output.doc");
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
CompareOptions options = new CompareOptions();
options.setIgnoreFormatting(true);
// Relates to Microsoft Word "Show changes in" option in "Compare Documents" dialog box.
options.setTarget(ComparisonTargetType.NEW);
docA.compare(docB, "user", new Date(), options);
Document docA = new Document(dataDir + "DocumentA.doc");
Document docB = new Document(dataDir + "DocumentB.doc");
docA.compare(docB, "user", new Date()); // exception is thrown.
// Example Shows Normal Comparison Case
normalComparisonCase();
// Case when Document has Revisions already so Comparison is not Possible
caseWhenDocumentHasRevisions();
// Shows how to test that Word Documents are "Equal"
wordDocumentsAreEqual();
Document docA = new Document(dataDir + "DocumentA.doc");
Document docB = new Document(dataDir + "DocumentB.doc");
docA.compare(docB, "user", new Date()); // docA now contains changes as revisions
DocumentBuilder builderA = new DocumentBuilder(new Document());
DocumentBuilder builderB = new DocumentBuilder(new Document());
builderA.writeln("This is A simple word");
builderB.writeln("This is B simple words");
CompareOptions co = new CompareOptions();
co.setGranularity(Granularity.CHAR_LEVEL);
builderA.getDocument().compare(builderB.getDocument(), "author", new Date(), co);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(CompareTwoWordDocumentswithCompareOptions.class);
com.aspose.words.Document docA = new com.aspose.words.Document(dataDir + "DocumentA.doc");
com.aspose.words.Document docB = new com.aspose.words.Document(dataDir + "DocumentB.doc");
com.aspose.words.CompareOptions options = new com.aspose.words.CompareOptions();
options.setIgnoreFormatting(true);
options.setIgnoreHeadersAndFooters(true);
options.setIgnoreCaseChanges(true);
options.setIgnoreTables(true);
options.setIgnoreFields(true);
options.setIgnoreComments(true);
options.setIgnoreTextboxes(true);
options.setIgnoreFootnotes(true);
// DocA now contains changes as revisions.
docA.compare(docB, "user", new Date(), options);
if (docA.getRevisions().getCount() == 0)
System.out.println("Documents are equal");
else
System.out.println("Documents are not equal");
Document docA = new Document(dataDir + "DocumentA.doc");
Document docB = new Document(dataDir + "DocumentB.doc");
docA.compare(docB, "user", new Date());
if(docA.getRevisions().getCount() == 0)
System.out.println("Documents are equal");
String dataDir = Utils.getDataDir(CompareTwoWordDocumentswithCompareOptions.class);
com.aspose.words.Document docA = new com.aspose.words.Document(dataDir + "DocumentA.doc");
com.aspose.words.Document docB = new com.aspose.words.Document(dataDir + "DocumentB.doc");
com.aspose.words.CompareOptions options = new com.aspose.words.CompareOptions();
options.setIgnoreFormatting(true);
options.setIgnoreHeadersAndFooters(true);
options.setIgnoreCaseChanges(true);
options.setIgnoreTables(true);
options.setIgnoreFields(true);
options.setIgnoreComments(true);
options.setIgnoreTextboxes(true);
options.setIgnoreFootnotes(true);
// DocA now contains changes as revisions.
docA.compare(docB, "user", new Date(), options);
if (docA.getRevisions().getCount() == 0)
System.out.println("Documents are equal");
else
System.out.println("Documents are not equal");
@ImperviousPanda
Copy link

ImperviousPanda commented Jul 29, 2020

This example does not work as intended for me:

Document docB = new Document(dataDir + "DocumentB.doc");
docA.compare(docB, "user", new Date());
if(docA.getRevisions().getCount() == 0)
    System.out.println("Documents are equal");

My difference is that I'm saving a docx, re loading it and then comparing the two documents. From my understanding this should work the same.

Here is a snippet of my code:
`final Document substitutedDocx = this.personalizationVariableSubstituterImpl.substituteDocx(document);

    substitutedDocx.save("src/test/test.docx");
    final Document expectedDocument = new Document("src/test/test.docx");

    // This adds revisions to the document to make it equal to the other document
    substitutedDocx.compare(expectedDocument, "user", new Date());
    assertEquals("Reservation substituted docx is incorrect", 0,
            substitutedDocx.getRevisions().getCount());`

The actual number of revisions is 6

@Muzammil-khan
Copy link

@ImperviousPanda Could you please attach the source document.

@ImperviousPanda
Copy link

I figured this out - it is because I am still playing around with the trial version and the watermark adds an extra 6 revisions on save.

For now I am saving the other document as a temporary file and then comparing. I can remove this code when we buy a license.

@Muzammil-khan
Copy link

@ImperviousPanda Thank you for your feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment