Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
// 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());
}
// The path to the documents directory.
String dataDir = Utils.getDataDir(CheckFormat.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 java.io.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;
}
}
}
// 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(CheckFormat.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 java.io.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 java.io.File(dataDir).listFiles();
// 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();
// 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/";
// 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());
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
// 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(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));