This Gist contains examples of Aspose.Words for Java
-
-
Save aspose-words/b37032675133885c4c91814fb3d51a25 to your computer and use it in GitHub Desktop.
This Gist contains code snippets of examples of Aspose.Words for Java.
This gist exceeds the recommended number of files (~10).
To access all files, please clone this gist.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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())); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
Paragraph para = new Paragraph(doc); | |
Section section = doc.getLastSection(); | |
section.getBody().appendChild(para); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
// Returns NodeType.Document | |
int type = doc.getNodeType(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(AccessAndVerifySignature.class); | |
// 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()); | |
System.out.println("Subject name: " + signature.getCertificate().getSubjectAlternativeNames()); | |
System.out.println("Issuer name: " + signature.getCertificate().getIssuerAlternativeNames()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
File[] fileList = new File(dataDir).listFiles(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ConvertDocumentToByte.class); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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())); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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())); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(Doc2PDF.class); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "encrypted.odt", new com.aspose.words.LoadOptions("password")); | |
doc.save(dataDir + "out.odt", new OdtSaveOptions("newpassword")); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "encrypted.odt"); | |
System.out.println(info.isEncrypted()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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"); | |
System.out.println("Document loaded and saved successfully."); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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."); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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")); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(OpenDocument.class); | |
String filename = "Test.docx"; | |
Document doc = new Document(dataDir + filename); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(OpenDocUsingStream.class); | |
String filename = "Test.docx"; | |
InputStream in = new FileInputStream(dataDir + filename); | |
Document doc = new Document(in); | |
System.out.println("Document opened. Total pages are " + doc.getPageCount()); | |
in.close(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Called from the web-app index page (because the POST method is chosen for the input form). | |
*/ | |
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()); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
RtfLoadOptions loadOptions = new RtfLoadOptions(); | |
loadOptions.setRecognizeUtf8Text(true); | |
Document doc = new Document(dataDir + "Utf8Text.rtf", loadOptions); | |
dataDir = dataDir + "RecognizeUtf8Text_out.rtf"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Input.docx"); | |
TxtSaveOptions saveOptions = new TxtSaveOptions(); | |
saveOptions.setAddBidiMarks(false); | |
dataDir = dataDir + "Document.AddBidiMarks_out.txt"; | |
doc.save(dataDir, saveOptions); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
TxtLoadOptions loadOptions = new TxtLoadOptions(); | |
loadOptions.setDetectNumberingWithWhitespaces(false); | |
Document doc = new Document(dataDir + "LoadTxt.txt", loadOptions); | |
dataDir = dataDir + "DetectNumberingWithWhitespaces_out.docx"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
dataDir = dataDir + "Document.ConvertToTxt_out.txt"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
doc.getMailMerge().deleteFields(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
String[] fieldNames = doc.getMailMerge().getFieldNames(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* 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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
ArrayList<String> regions = new ArrayList<String>(); | |
regions.add("ContactDetails"); | |
executeCustomLogicOnEmptyRegions(doc, new EmptyRegionsHandler(), regions); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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". | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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())) { | |
// Remove the "Name:" tag from the start of the paragraph | |
parentParagraph.getRange().replace("Name:", "", false, false); | |
// 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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* 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"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Set the appropriate mail merge clean up options to remove any unused regions from the document. | |
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
** | |
* 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, 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[0] = 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[0] = 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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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 }); | |
// Add DataLabel to the first point of the first series. | |
ChartDataLabel chartDataLabel0 = series0.getDataLabels().add(0); | |
chartDataLabel0.setShowValue(true); | |
// Set currency format code. | |
chartDataLabel0.getNumberFormat().setFormatCode("\"$\"#,##0.00"); | |
ChartDataLabel chartDataLabel1 = series0.getDataLabels().add(1); | |
chartDataLabel1.setShowValue(true); | |
// Set date format code. | |
chartDataLabel1.getNumberFormat().setFormatCode("d/mm/yyyy"); | |
ChartDataLabel chartDataLabel2 = series0.getDataLabels().add(2); | |
chartDataLabel2.setShowValue(true); | |
// Set percentage format code. | |
chartDataLabel2.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. | |
chartDataLabel2.getNumberFormat().isLinkedToSource(true); | |
doc.save(dataDir +"NumberFormat_DataLabel_out.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.BAR, 432, 252); | |
// Get first series. | |
ChartSeries series0 = shape.getChart().getSeries().get(0); | |
ChartDataLabelCollection dataLabelCollection = series0.getDataLabels(); | |
// Add data label to the first and second point of the first series. | |
ChartDataLabel chartDataLabel00 = dataLabelCollection.add(0); | |
ChartDataLabel chartDataLabel01 = dataLabelCollection.add(1); | |
// Set properties. | |
chartDataLabel00.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. | |
chartDataLabel00.setShowLeaderLines(true); | |
chartDataLabel00.setShowCategoryName(false); | |
chartDataLabel00.setShowPercentage(false); | |
chartDataLabel00.setShowSeriesName(true); | |
chartDataLabel00.setShowValue(true); | |
chartDataLabel00.setSeparator("/"); | |
chartDataLabel01.setShowValue(true); | |
doc.save(dataDir + "ChartDataLabelOfASingleChartSeries_out.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(CreateSimpleDocumentUsingDocumentBuilder.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("Aspose_Words_Java"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
StyleCollection styles = doc.getStyles(); | |
for (Style style : styles) | |
System.out.println(style.getName()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
for(int i =0; i < doc.getStyles().getCount(); i++) | |
System.out.println(doc.getStyles().get(i).getName()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document docA = new Document(dataDir + "DocumentA.doc"); | |
Document docB = new Document(dataDir + "DocumentB.doc"); | |
docA.compare(docB, "user", new Date()); // exception is thrown. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ConvertBetweenMeasurementUnits.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
PageSetup pageSetup = builder.getPageSetup(); | |
pageSetup.setTopMargin(ConvertUtil.inchToPoint(1.0)); | |
pageSetup.setBottomMargin(ConvertUtil.inchToPoint(1.0)); | |
pageSetup.setLeftMargin(ConvertUtil.inchToPoint(1.5)); | |
pageSetup.setRightMargin(ConvertUtil.inchToPoint(1.5)); | |
pageSetup.setHeaderDistance(ConvertUtil.inchToPoint(0.2)); | |
pageSetup.setFooterDistance(ConvertUtil.inchToPoint(0.2)); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderApplyBordersAndShadingToParagraph.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Set paragraph borders | |
BorderCollection borders = builder.getParagraphFormat().getBorders(); | |
borders.setDistanceFromText(20); | |
borders.getByBorderType(BorderType.LEFT).setLineStyle(LineStyle.DOUBLE); | |
borders.getByBorderType(BorderType.RIGHT).setLineStyle(LineStyle.DOUBLE); | |
borders.getByBorderType(BorderType.TOP).setLineStyle(LineStyle.DOUBLE); | |
borders.getByBorderType(BorderType.BOTTOM).setLineStyle(LineStyle.DOUBLE); | |
// Set paragraph shading | |
Shading shading = builder.getParagraphFormat().getShading(); | |
shading.setTexture(TextureIndex.TEXTURE_DIAGONAL_CROSS); | |
shading.setBackgroundPatternColor(Color.YELLOW); | |
shading.setForegroundPatternColor(Color.GREEN); | |
builder.write("I'm a formatted paragraph with double border and nice shading."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderApplyParagraphStyle.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.TITLE); | |
builder.write("Hello"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderBuildTable.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Table table = builder.startTable(); | |
builder.insertCell(); | |
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS); | |
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER); | |
builder.write("This is Row 1 Cell 1"); | |
builder.insertCell(); | |
builder.write("This is Row 1 Cell 2"); | |
builder.endRow(); | |
builder.getRowFormat().setHeight(100); | |
builder.getRowFormat().setHeightRule(HeightRule.EXACTLY); | |
builder.getCellFormat().setOrientation(TextOrientation.UPWARD); | |
builder.write("This is Row 2 Cell 1"); | |
builder.insertCell(); | |
builder.getCellFormat().setOrientation(TextOrientation.DOWNWARD); | |
builder.write("This is Row 2 Cell 2"); | |
builder.endRow(); | |
builder.endTable(); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderCursorPosition.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Node node = builder.getCurrentNode(); | |
Paragraph curParagraph = builder.getCurrentParagraph(); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertBookmark.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.startBookmark("FineBookMark"); | |
builder.write("This is just a fine bookmark."); | |
builder.endBookmark("FineBookmark"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertBreak.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("This is Page 1"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.write("This is Page 2"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.write("This is Page 3"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertCheckBoxFormField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertCheckBox("CheckBox", true, true, 0); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertComboBoxFormField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
String[] items = {"One", "Two", "Three"}; | |
builder.insertComboBox("DropDown", items, 0); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
Path path = Paths.get(dataDir, "input.zip"); | |
byte[] bs = Files.readAllBytes(path); | |
ByteArrayInputStream stream = new ByteArrayInputStream(bs); | |
Shape shape = builder.insertOleObject(stream, "Package", true, null); | |
OlePackage olePackage = shape.getOleFormat().getOlePackage(); | |
olePackage.setFileName("filename.zip"); | |
olePackage.setDisplayName("displayname.zip"); | |
dataDir = dataDir + "DocumentBuilderInsertOleObjectOlePackage_out.doc"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.getFont().setLocaleId(1031); | |
builder.insertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\""); | |
builder.write(" - "); | |
builder.insertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\""); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertFloatingImage.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertImage(dataDir + "test.jpg", | |
RelativeHorizontalPosition.MARGIN, | |
100, | |
RelativeVerticalPosition.MARGIN, | |
100, | |
200, | |
100, | |
WrapType.SQUARE); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Initialize document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.writeln("Insert a horizontal rule shape into the document."); | |
builder.insertHorizontalRule(); | |
dataDir = dataDir + "DocumentBuilder.InsertHorizontalRule_out.doc"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertHtml.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertHtml( | |
"<P align='right'>Paragraph right</P>" + | |
"<b>Implicit paragraph left</b>" + | |
"<div align='center'>Div center</div>" + | |
"<h1 align='left'>Heading 1 left.</h1>"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertHyperlink.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("Please make sure to visit "); | |
// Specify font formatting for the hyperlink. | |
builder.getFont().setColor(Color.MAGENTA); | |
// builder.getFont().setUnderline(); | |
//builder.Font.Underline = Underline.Single; | |
// Insert the link. | |
builder.insertHyperlink("Aspose Website", "http://www.aspose.com", false); | |
// Revert to default formatting. | |
builder.getFont().clearFormatting(); | |
builder.write(" for more information."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertInlineImage.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertImage(dataDir + "test.jpg"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertOleObject.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertOleObject("http://www.aspose.com", "htmlfile", true, true, null); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertParagraph.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Font font = builder.getFont(); | |
font.setSize(16); | |
font.setColor(Color.DARK_GRAY); | |
font.setBold(true); | |
font.setName("Algerian"); | |
font.setUnderline(2); | |
ParagraphFormat paragraphFormat = builder.getParagraphFormat(); | |
paragraphFormat.setFirstLineIndent(12); | |
paragraphFormat.setAlignment(1); | |
paragraphFormat.setKeepTogether(true); | |
builder.write("This is a sample Paragraph"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
String dataDir = Utils.getDataDir(DocumentBuilderInsertTableOfContents.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1); | |
builder.writeln("Heading 1"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2); | |
builder.writeln("Heading 1.1"); | |
builder.writeln("Heading 1.2"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1); | |
builder.writeln("Heading 2"); | |
builder.writeln("Heading 3"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2); | |
builder.writeln("Heading 3.1"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_3); | |
builder.writeln("Heading 3.1.1"); | |
builder.writeln("Heading 3.1.2"); | |
builder.writeln("Heading 3.1.3"); | |
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_2); | |
builder.writeln("Heading 3.2"); | |
builder.writeln("Heading 3.3"); | |
doc.updateFields(); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderInsertTextInputFormField.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Hello", 0); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToBookmark.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveToBookmark("CoolBookmark"); | |
builder.writeln("This is a very cool bookmark."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToBookmarkEnd.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveToBookmark("CoolBookmark", false, true); | |
builder.writeln("This is a very cool bookmark."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToDocumentStartEnd.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveToDocumentEnd(); | |
builder.write("\n\nThis is the end of the document."); | |
builder.insertParagraph(); | |
builder.moveToDocumentStart(); | |
builder.write("\nThis is the beginning of the document."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToMergeField.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveToMergeField("NiceMergeField"); | |
builder.writeln("This is a very nice merge field."); | |
// doc.save(dataDir + "output.doc"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToNode.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveTo(doc.getFirstSection().getBody().getLastParagraph()); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToParagraph.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveToParagraph(2, 0); | |
builder.writeln("This is the 3rd paragraph."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToSection.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.moveToSection(2); | |
builder.write("\nThis is third Section\n"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderMoveToTableCell.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "DocumentBuilder.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// All parameters are 0-index. Moves to the 2nd table, 3rd row, 5th cell. | |
builder.moveToCell(1, 2, 4, 0); | |
builder.writeln("Hello World!"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetFontFormatting.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Font font = builder.getFont(); | |
font.setSize(16); | |
font.setColor(Color.blue); | |
font.setBold(true); | |
font.setName("Arial"); | |
font.setUnderline(Underline.DOTTED); | |
builder.write("I'm a very nice formatted string."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(DocumentBuilderSetImageAspectRatioLocked.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Shape shape = builder.insertImage(dataDir + "Test.png"); | |
shape.setAspectRatioLocked(false); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetMultilevelListFormatting.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.getListFormat().applyNumberDefault(); | |
builder.writeln("Item 1"); | |
builder.writeln("Item 2"); | |
builder.getListFormat().listIndent(); | |
builder.writeln("Item 2.1"); | |
builder.writeln("Item 2.2"); | |
builder.getListFormat().listIndent(); | |
builder.writeln("Item 2.1.1"); | |
builder.writeln("Item 2.2.2"); | |
builder.getListFormat().listOutdent(); | |
builder.writeln("Item 3"); | |
builder.getListFormat().removeNumbers(); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetPageSetupAndSectionFormatting.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.getPageSetup().setOrientation(Orientation.LANDSCAPE); | |
builder.getPageSetup().setLeftMargin(50); | |
builder.getPageSetup().setPaperSize(PaperSize.PAPER_10_X_14); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetParagraphFormatting.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
ParagraphFormat paragraphFormat = builder.getParagraphFormat(); | |
paragraphFormat.setAlignment(ParagraphAlignment.CENTER); | |
paragraphFormat.setLeftIndent(50); | |
paragraphFormat.setRightIndent(50); | |
paragraphFormat.setSpaceAfter(25); | |
paragraphFormat.setKeepTogether(true); | |
builder.writeln("I'm a very nice formatted paragraph. I'm intended to demonstrate how the left and right indents affect word wrapping."); | |
builder.writeln("I'm another nice formatted paragraph. I'm intended to demonstrate how the space after paragraph looks like."); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetSpacebetweenAsianandLatintext.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Set paragraph formatting properties | |
ParagraphFormat paragraphFormat = builder.getParagraphFormat(); | |
paragraphFormat.setAddSpaceBetweenFarEastAndAlpha(true); | |
paragraphFormat.setAddSpaceBetweenFarEastAndDigit(true); | |
builder.writeln("Automatically adjust space between Asian and Latin text"); | |
builder.writeln("Automatically adjust space between Asian text and numbers"); | |
dataDir = dataDir + "DocumentBuilderSetSpacebetweenAsianandLatintext.doc"; | |
doc.save(dataDir); | |
System.out.println("Document Saved"); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetTableCellFormatting.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertCell(); | |
CellFormat cellFormat =builder.getCellFormat(); | |
cellFormat.setWidth(250); | |
cellFormat.setLeftPadding(30); | |
cellFormat.setRightPadding(30); | |
cellFormat.setBottomPadding(30); | |
cellFormat.setTopPadding(30); | |
builder.writeln("I'm a wonderful formatted cell."); | |
builder.endRow(); | |
builder.endTable(); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(DocumentBuilderSetTableRowFormatting.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Table table = builder.startTable(); | |
builder.insertCell(); | |
RowFormat rowFormat = builder.getRowFormat(); | |
rowFormat.setHeight(100); | |
rowFormat.setHeightRule(HeightRule.EXACTLY); | |
table.setBottomPadding(30); | |
table.setTopPadding(30); | |
table.setLeftPadding(30); | |
table.setRightPadding(30); | |
builder.writeln("I'm a wonderful formatted row."); | |
builder.endRow(); | |
builder.endTable(); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// The path to the documents directory. | |
Document doc = new Document(dataDir + "Document.doc"); | |
//Set the layout mode for a section allowing to define the document grid behavior | |
//Note that the Document Grid tab becomes visible in the Page Setup dialog of MS Word if any Asian language is defined as editing language. | |
doc.getFirstSection().getPageSetup().setLayoutMode(SectionLayoutMode.GRID); | |
//Set the number of characters per line in the document grid. | |
doc.getFirstSection().getPageSetup().setCharactersPerLine(30); | |
//Set the number of lines per page in the document grid. | |
doc.getFirstSection().getPageSetup().setLinesPerPage(10); | |
//Save the document | |
doc.save(dataDir + "Document.PageSetup_out.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentBetweenBlockLevelNodes.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
Paragraph startPara = (Paragraph) doc.getLastSection().getChild(NodeType.PARAGRAPH, 2, true); | |
Table endTable = (Table) doc.getLastSection().getChild(NodeType.TABLE, 0, true); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
ArrayList extractedNodes = extractContent(startPara, endTable, true); | |
// Lets reverse the array to make inserting the content back into the document easier. | |
Collections.reverse(extractedNodes); | |
while (extractedNodes.size() > 0) { | |
// Insert the last node from the reversed list | |
endTable.getParentNode().insertAfter((Node) extractedNodes.get(0), endTable); | |
// Remove this node from the list after insertion. | |
extractedNodes.remove(0); | |
} | |
// Save the generated document to disk. | |
doc.save(dataDir + "output.doc"); | |
System.out.println("Content extracted between the block level nodes successfully."); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentBetweenBookmarks.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Retrieve the bookmark from the document. | |
Bookmark bookmark = doc.getRange().getBookmarks().get("Bookmark1"); | |
// We use the BookmarkStart and BookmarkEnd nodes as markers. | |
BookmarkStart bookmarkStart = bookmark.getBookmarkStart(); | |
BookmarkEnd bookmarkEnd = bookmark.getBookmarkEnd(); | |
// Firstly extract the content between these nodes including the bookmark. | |
ArrayList extractedNodesInclusive = extractContent(bookmarkStart, bookmarkEnd, true); | |
Document dstDoc = generateDocument(doc, extractedNodesInclusive); | |
dstDoc.save(dataDir + "TestFile.BookmarkInclusive Out.doc"); | |
// Secondly extract the content between these nodes this time without including the bookmark. | |
ArrayList extractedNodesExclusive = extractContent(bookmarkStart, bookmarkEnd, false); | |
dstDoc = generateDocument(doc, extractedNodesExclusive); | |
dstDoc.save(dataDir + "output.doc"); | |
System.out.println("Content extracted between bookmarks successfully."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentBetweenCommentRange.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// This is a quick way of getting both comment nodes. | |
// Your code should have a proper method of retrieving each corresponding start and end node. | |
CommentRangeStart commentStart = (CommentRangeStart) doc.getChild(NodeType.COMMENT_RANGE_START, 0, true); | |
CommentRangeEnd commentEnd = (CommentRangeEnd) doc.getChild(NodeType.COMMENT_RANGE_END, 0, true); | |
// Firstly extract the content between these nodes including the comment as well. | |
ArrayList extractedNodesInclusive = extractContent(commentStart, commentEnd, true); | |
Document dstDoc = generateDocument(doc, extractedNodesInclusive); | |
dstDoc.save(dataDir + "TestFile.CommentInclusive Out.doc"); | |
// Secondly extract the content between these nodes without the comment. | |
ArrayList extractedNodesExclusive = extractContent(commentStart, commentEnd, false); | |
dstDoc = generateDocument(doc, extractedNodesExclusive); | |
dstDoc.save(dataDir + "output.doc"); | |
System.out.println("Content extracted between comment range successfully."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentBetweenParagraphs.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Gather the nodes. The GetChild method uses 0-based index | |
Paragraph startPara = (Paragraph) doc.getFirstSection().getChild(NodeType.PARAGRAPH, 6, true); | |
Paragraph endPara = (Paragraph) doc.getFirstSection().getChild(NodeType.PARAGRAPH, 10, true); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
ArrayList extractedNodes = extractContent(startPara, endPara, true); | |
// Insert the content into a new separate document and save it to disk. | |
Document dstDoc = generateDocument(doc, extractedNodes); | |
dstDoc.save(dataDir + "output.doc"); | |
System.out.println("Content extracted between the paragraphs successfully."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public static ArrayList extractContent(Node startNode, Node endNode, boolean isInclusive) throws Exception { | |
// First check that the nodes passed to this method are valid for use. | |
verifyParameterNodes(startNode, endNode); | |
// Create a list to store the extracted nodes. | |
ArrayList nodes = new ArrayList(); | |
// Keep a record of the original nodes passed to this method so we can split marker nodes if needed. | |
Node originalStartNode = startNode; | |
Node originalEndNode = endNode; | |
// Extract content based on block level nodes (paragraphs and tables). Traverse through parent nodes to find them. | |
// We will split the content of first and last nodes depending if the marker nodes are inline | |
while (startNode.getParentNode().getNodeType() != NodeType.BODY) | |
startNode = startNode.getParentNode(); | |
while (endNode.getParentNode().getNodeType() != NodeType.BODY) | |
endNode = endNode.getParentNode(); | |
boolean isExtracting = true; | |
boolean isStartingNode = true; | |
boolean isEndingNode; | |
// The current node we are extracting from the document. | |
Node currNode = startNode; | |
// Begin extracting content. Process all block level nodes and specifically split the first and last nodes when needed so paragraph formatting is retained. | |
// Method is little more complex than a regular extractor as we need to factor in extracting using inline nodes, fields, bookmarks etc as to make it really useful. | |
while (isExtracting) { | |
// Clone the current node and its children to obtain a copy. | |
CompositeNode cloneNode = (CompositeNode) currNode.deepClone(true); | |
isEndingNode = currNode.equals(endNode); | |
if (isStartingNode || isEndingNode) { | |
// We need to process each marker separately so pass it off to a separate method instead. | |
if (isStartingNode) { | |
processMarker(cloneNode, nodes, originalStartNode, isInclusive, isStartingNode, isEndingNode); | |
isStartingNode = false; | |
} | |
// Conditional needs to be separate as the block level start and end markers maybe the same node. | |
if (isEndingNode) { | |
processMarker(cloneNode, nodes, originalEndNode, isInclusive, isStartingNode, isEndingNode); | |
isExtracting = false; | |
} | |
} else | |
// Node is not a start or end marker, simply add the copy to the list. | |
nodes.add(cloneNode); | |
// Move to the next node and extract it. If next node is null that means the rest of the content is found in a different section. | |
if (currNode.getNextSibling() == null && isExtracting) { | |
// Move to the next section. | |
Section nextSection = (Section) currNode.getAncestor(NodeType.SECTION).getNextSibling(); | |
currNode = nextSection.getBody().getFirstChild(); | |
} else { | |
// Move to the next node in the body. | |
currNode = currNode.getNextSibling(); | |
} | |
} | |
// Return the nodes between the node markers. | |
return nodes; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public static Document generateDocument(Document srcDoc, ArrayList nodes) throws Exception { | |
// Create a blank document. | |
Document dstDoc = new Document(); | |
// Remove the first paragraph from the empty document. | |
dstDoc.getFirstSection().getBody().removeAllChildren(); | |
// Import each node from the list into the new document. Keep the original formatting of the node. | |
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
for (Node node : (Iterable<Node>) nodes) { | |
Node importNode = importer.importNode(node, true); | |
dstDoc.getFirstSection().getBody().appendChild(importNode); | |
} | |
// Return the generated document. | |
return dstDoc; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static void verifyParameterNodes(Node startNode, Node endNode) throws Exception { | |
// The order in which these checks are done is important. | |
if (startNode == null) | |
throw new IllegalArgumentException("Start node cannot be null"); | |
if (endNode == null) | |
throw new IllegalArgumentException("End node cannot be null"); | |
if (!startNode.getDocument().equals(endNode.getDocument())) | |
throw new IllegalArgumentException("Start node and end node must belong to the same document"); | |
if (startNode.getAncestor(NodeType.BODY) == null || endNode.getAncestor(NodeType.BODY) == null) | |
throw new IllegalArgumentException("Start node and end node must be a child or descendant of a body"); | |
// Check the end node is after the start node in the DOM tree | |
// First check if they are in different sections, then if they're not check their position in the body of the same section they are in. | |
Section startSection = (Section) startNode.getAncestor(NodeType.SECTION); | |
Section endSection = (Section) endNode.getAncestor(NodeType.SECTION); | |
int startIndex = startSection.getParentNode().indexOf(startSection); | |
int endIndex = endSection.getParentNode().indexOf(endSection); | |
if (startIndex == endIndex) { | |
if (startSection.getBody().indexOf(startNode) > endSection.getBody().indexOf(endNode)) | |
throw new IllegalArgumentException("The end node must be after the start node in the body"); | |
} else if (startIndex > endIndex) | |
throw new IllegalArgumentException("The section of end node must be after the section start node"); | |
} | |
/** | |
* Checks if a node passed is an inline node. | |
*/ | |
private static boolean isInline(Node node) throws Exception { | |
// Test if the node is desendant of a Paragraph or Table node and also is not a paragraph or a table a paragraph inside a comment class which is decesant of a pararaph is possible. | |
return ((node.getAncestor(NodeType.PARAGRAPH) != null || node.getAncestor(NodeType.TABLE) != null) && !(node.getNodeType() == NodeType.PARAGRAPH || node.getNodeType() == NodeType.TABLE)); | |
} | |
/** | |
* Removes the content before or after the marker in the cloned node depending on the type of marker. | |
*/ | |
private static void processMarker(CompositeNode cloneNode, ArrayList nodes, Node node, boolean isInclusive, boolean isStartMarker, boolean isEndMarker) throws Exception { | |
// If we are dealing with a block level node just see if it should be included and add it to the list. | |
if (!isInline(node)) { | |
// Don't add the node twice if the markers are the same node | |
if (!(isStartMarker && isEndMarker)) { | |
if (isInclusive) | |
nodes.add(cloneNode); | |
} | |
return; | |
} | |
// If a marker is a FieldStart node check if it's to be included or not. | |
// We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph. | |
if (node.getNodeType() == NodeType.FIELD_START) { | |
// If the marker is a start node and is not be included then skip to the end of the field. | |
// If the marker is an end node and it is to be included then move to the end field so the field will not be removed. | |
if ((isStartMarker && !isInclusive) || (!isStartMarker && isInclusive)) { | |
while (node.getNextSibling() != null && node.getNodeType() != NodeType.FIELD_END) | |
node = node.getNextSibling(); | |
} | |
} | |
// If either marker is part of a comment then to include the comment itself we need to move the pointer forward to the Comment | |
// node found after the CommentRangeEnd node. | |
if (node.getNodeType() == NodeType.COMMENT_RANGE_END) { | |
while (node.getNextSibling() != null && node.getNodeType() != NodeType.COMMENT) | |
node = node.getNextSibling(); | |
} | |
// Find the corresponding node in our cloned node by index and return it. | |
// If the start and end node are the same some child nodes might already have been removed. Subtract the | |
// difference to get the right index. | |
int indexDiff = node.getParentNode().getChildNodes().getCount() - cloneNode.getChildNodes().getCount(); | |
// Child node count identical. | |
if (indexDiff == 0) | |
node = cloneNode.getChildNodes().get(node.getParentNode().indexOf(node)); | |
else | |
node = cloneNode.getChildNodes().get(node.getParentNode().indexOf(node) - indexDiff); | |
// Remove the nodes up to/from the marker. | |
boolean isSkip; | |
boolean isProcessing = true; | |
boolean isRemoving = isStartMarker; | |
Node nextNode = cloneNode.getFirstChild(); | |
while (isProcessing && nextNode != null) { | |
Node currentNode = nextNode; | |
isSkip = false; | |
if (currentNode.equals(node)) { | |
if (isStartMarker) { | |
isProcessing = false; | |
if (isInclusive) | |
isRemoving = false; | |
} else { | |
isRemoving = true; | |
if (isInclusive) | |
isSkip = true; | |
} | |
} | |
nextNode = nextNode.getNextSibling(); | |
if (isRemoving && !isSkip) | |
currentNode.remove(); | |
} | |
// After processing the composite node may become empty. If it has don't include it. | |
if (!(isStartMarker && isEndMarker)) { | |
if (cloneNode.hasChildNodes()) | |
nodes.add(cloneNode); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentBetweenParagraphStyles.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Gather a list of the paragraphs using the respective heading styles. | |
ArrayList parasStyleHeading1 = paragraphsByStyleName(doc, "Heading 1"); | |
ArrayList parasStyleHeading3 = paragraphsByStyleName(doc, "Heading 3"); | |
// Use the first instance of the paragraphs with those styles. | |
Node startPara1 = (Node) parasStyleHeading1.get(0); | |
Node endPara1 = (Node) parasStyleHeading3.get(0); | |
// Extract the content between these nodes in the document. Don't include these markers in the extraction. | |
ArrayList extractedNodes = extractContent(startPara1, endPara1, false); | |
// Insert the content into a new separate document and save it to disk. | |
Document dstDoc = generateDocument(doc, extractedNodes); | |
dstDoc.save(dataDir + "output.doc"); | |
System.out.println("Content extracted between the paragraph styles successfully."); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentBetweenRuns.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Retrieve a paragraph from the first section. | |
Paragraph para = (Paragraph) doc.getChild(NodeType.PARAGRAPH, 7, true); | |
// Use some runs for extraction. | |
Run startRun = para.getRuns().get(1); | |
Run endRun = para.getRuns().get(4); | |
// Extract the content between these nodes in the document. Include these markers in the extraction. | |
ArrayList extractedNodes = extractContent(startRun, endRun, true); | |
// Get the node from the list. There should only be one paragraph returned in the list. | |
Node node = (Node) extractedNodes.get(0); | |
// Print the text of this node to the console. | |
System.out.println(node.toString(SaveFormat.TEXT)); | |
System.out.println("Content extracted between the runs successfully."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class ExtractContentUsingDocumentVisitor { | |
public static void main(String[] args) throws Exception { | |
String dataDir = Utils.getSharedDataDir(ExtractContentUsingDocumentVisitor.class) + "ExtractedSelectedContentBetweenNodes/"; | |
// Open the document we want to convert. | |
Document doc = new Document(dataDir + "Visitor.ToText.doc"); | |
// Create an object that inherits from the DocumentVisitor class. | |
MyDocToTxtWriter myConverter = new MyDocToTxtWriter(); | |
// This is the well known Visitor pattern. Get the model to accept a visitor. | |
// The model will iterate through itself by calling the corresponding methods | |
// on the visitor object (this is called visiting). | |
// | |
// Note that every node in the object model has the Accept method so the visiting | |
// can be executed not only for the whole document, but for any node in the document. | |
doc.accept(myConverter); | |
// Once the visiting is complete, we can retrieve the result of the operation, | |
// that in this example, has accumulated in the visitor. | |
System.out.println(myConverter.getText()); | |
} | |
} | |
/** | |
* Simple implementation of saving a document in the plain text format. | |
* Implemented as a Visitor. | |
*/ | |
class MyDocToTxtWriter extends DocumentVisitor { | |
private final StringBuilder mBuilder; | |
private boolean mIsSkipText; | |
public MyDocToTxtWriter() throws Exception { | |
mIsSkipText = false; | |
mBuilder = new StringBuilder(); | |
} | |
/** | |
* Gets the plain text of the document that was accumulated by the visitor. | |
*/ | |
public String getText() throws Exception { | |
return mBuilder.toString(); | |
} | |
/** | |
* Called when a Run node is encountered in the document. | |
*/ | |
public int visitRun(Run run) throws Exception { | |
appendText(run.getText()); | |
// Let the visitor continue visiting other nodes. | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Called when a FieldStart node is encountered in the document. | |
*/ | |
public int visitFieldStart(FieldStart fieldStart) throws Exception { | |
// In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows | |
// after a field start character. We want to skip field codes and output field | |
// result only, therefore we use a flag to suspend the output while inside a field code. | |
// | |
// Note this is a very simplistic implementation and will not work very well | |
// if you have nested fields in a document. | |
mIsSkipText = true; | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Called when a FieldSeparator node is encountered in the document. | |
*/ | |
public int visitFieldSeparator(FieldSeparator fieldSeparator) throws Exception { | |
// Once reached a field separator node, we enable the output because we are | |
// now entering the field result nodes. | |
mIsSkipText = false; | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Called when a FieldEnd node is encountered in the document. | |
*/ | |
public int visitFieldEnd(FieldEnd fieldEnd) throws Exception { | |
// Make sure we enable the output when reached a field end because some fields | |
// do not have field separator and do not have field result. | |
mIsSkipText = false; | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Called when visiting of a Paragraph node is ended in the document. | |
*/ | |
public int visitParagraphEnd(Paragraph paragraph) throws Exception { | |
// When outputting to plain text we output Cr+Lf characters. | |
appendText(ControlChar.CR_LF); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitBodyStart(Body body) throws Exception { | |
// We can detect beginning and end of all composite nodes such as Section, Body, | |
// Table, Paragraph etc and provide custom handling for them. | |
mBuilder.append("*** Body Started ***\r\n"); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitBodyEnd(Body body) throws Exception { | |
mBuilder.append("*** Body Ended ***\r\n"); | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Called when a HeaderFooter node is encountered in the document. | |
*/ | |
public int visitHeaderFooterStart(HeaderFooter headerFooter) throws Exception { | |
// Returning this value from a visitor method causes visiting of this | |
// node to stop and move on to visiting the next sibling node. | |
// The net effect in this example is that the text of headers and footers | |
// is not included in the resulting output. | |
return VisitorAction.SKIP_THIS_NODE; | |
} | |
/** | |
* Adds text to the current output. Honours the enabled/disabled output | |
* flag. | |
*/ | |
private void appendText(String text) throws Exception { | |
if (!mIsSkipText) | |
mBuilder.append(text); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractContentUsingField.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Use a document builder to retrieve the field start of a merge field. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field. | |
// We could also get FieldStarts of a field using GetChildNode method as in the other examples. | |
builder.moveToMergeField("Fullname", false, false); | |
// The builder cursor should be positioned at the start of the field. | |
FieldStart startField = (FieldStart) builder.getCurrentNode(); | |
Paragraph endPara = (Paragraph) doc.getFirstSection().getChild(NodeType.PARAGRAPH, 5, true); | |
// Extract the content between these nodes in the document. Don't include these markers in the extraction. | |
ArrayList extractedNodes = extractContent(startField, endPara, false); | |
// Insert the content into a new separate document and save it to disk. | |
Document dstDoc = generateDocument(doc, extractedNodes); | |
dstDoc.save(dataDir + "output.pdf"); | |
System.out.println("Content extracted using fields successfully."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractTextOnly.class); | |
Document doc = new Document(); | |
// Use a document builder to retrieve the field start of a merge field. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertField("MERGEFIELD Field"); | |
// GetText will retrieve all field codes and special characters | |
System.out.println("GetText() Result: " + doc.getText()); | |
// ToString will export the node to the specified format. When converted to text it will not retrieve fields code | |
// or special characters, but will still contain some natural formatting characters such as paragraph markers etc. | |
// This is the same as "viewing" the document as if it was opened in a text editor. | |
System.out.println("ToString() Result: " + doc.toString(SaveFormat.TEXT)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class GenerateACustomBarCodeImage { | |
private static final String dataDir = Utils.getSharedDataDir(GenerateACustomBarCodeImage.class) + "Barcode/"; | |
public static void main(String[] args) throws Exception { | |
Document doc = new Document(dataDir + "GenerateACustomBarCodeImage.docx"); | |
// Set custom barcode generator | |
doc.getFieldOptions().setBarcodeGenerator(new CustomBarcodeGenerator()); | |
doc.save(dataDir + "GenerateACustomBarCodeImage_out.pdf"); | |
} | |
/** | |
* Sample of custom barcode generator implementation (with underlying | |
* Aspose.BarCode module) | |
*/ | |
static class CustomBarcodeGenerator implements IBarcodeGenerator { | |
/** | |
* Converts barcode image height from Word units to Aspose.BarCode units. | |
* | |
* @param heightInTwipsString | |
* @return | |
*/ | |
private float convertSymbolHeight(String heightInTwipsString) { | |
// Input value is in 1/1440 inches (twips) | |
int heightInTwips = Integer.MIN_VALUE; | |
try { | |
heightInTwips = Integer.parseInt(heightInTwipsString); | |
} catch (NumberFormatException e) { | |
heightInTwips = Integer.MIN_VALUE; | |
} | |
if (heightInTwips == Integer.MIN_VALUE) { | |
throw new RuntimeException("Error! Incorrect height - " + heightInTwipsString + "."); | |
} | |
// Convert to mm | |
return (float) (heightInTwips * 25.4 / 1440); | |
} | |
/** | |
* Converts barcode image color from Word to Aspose.BarCode. | |
* | |
* @param inputColor | |
* @return | |
*/ | |
private Color convertColor(String inputColor) { | |
// Input should be from "0x000000" to "0xFFFFFF" | |
/* | |
* Integer color = Integer.MIN_VALUE; try { color = | |
* Integer.parseInt(inputColor.replace("0x", "")); } catch | |
* (NumberFormatException e) { color = Integer.MIN_VALUE; } | |
* | |
* if (color == Integer.MIN_VALUE) { throw new RuntimeException( | |
* "Error! Incorrect color - " + inputColor + "."); } | |
*/ | |
return Color.BLACK; | |
// Backword conversion - | |
//return string.Format("0x{0,6:X6}", mControl.ForeColor.ToArgb() & 0xFFFFFF); | |
} | |
/** | |
* Converts bar code scaling factor from percents to float. | |
* | |
* @param scalingFactor | |
* @return | |
*/ | |
private float convertScalingFactor(String scalingFactor) { | |
boolean isParsed = false; | |
int percents = Integer.MIN_VALUE; | |
try { | |
percents = Integer.parseInt(scalingFactor); | |
} catch (NumberFormatException e) { | |
percents = Integer.MIN_VALUE; | |
} | |
if (percents != Integer.MIN_VALUE) { | |
if (percents >= 10 && percents <= 10000) { | |
isParsed = true; | |
} | |
} | |
if (!isParsed) { | |
throw new RuntimeException("Error! Incorrect scaling factor - " + scalingFactor + "."); | |
} | |
return percents / 100.0f; | |
} | |
/** | |
* Implementation of the GetBarCodeImage() method for IBarCodeGenerator | |
* interface. | |
* | |
* @param parameters | |
* @return | |
*/ | |
public BufferedImage getBarcodeImage(BarcodeParameters parameters) { | |
if (parameters.getBarcodeType() == null || parameters.getBarcodeValue() == null) { | |
return null; | |
} | |
BarCodeBuilder builder = new BarCodeBuilder(); | |
String type = parameters.getBarcodeType().toUpperCase(); | |
if (type.equals("QR")) | |
builder.setEncodeType(EncodeTypes.QR); | |
if (type.equals("CODE128")) | |
builder.setEncodeType(EncodeTypes.CODE_128); | |
if (type.equals("CODE39")) | |
builder.setEncodeType(EncodeTypes.CODE_39_STANDARD); | |
if (type.equals("EAN8")) | |
builder.setEncodeType(EncodeTypes.EAN_8); | |
if (type.equals("UPCA")) | |
builder.setEncodeType(EncodeTypes.UPCA); | |
if (type.equals("UPCE")) | |
builder.setEncodeType(EncodeTypes.UPCE); | |
if (type.equals("ITF14")) | |
builder.setEncodeType(EncodeTypes.ITF_14); | |
if (type.equals("CASE")) | |
builder.setEncodeType(EncodeTypes.NONE); | |
if (builder.getEncodeType() == EncodeTypes.NONE) | |
return null; | |
builder.setCodeText(parameters.getBarcodeValue()); | |
if (builder.getEncodeType() == EncodeTypes.QR) { | |
builder.setDisplay2DText(parameters.getBarcodeValue()); | |
} | |
if (parameters.getForegroundColor() != null) { | |
builder.setForeColor(convertColor(parameters.getForegroundColor())); | |
} | |
if (parameters.getBackgroundColor() != null) { | |
builder.setBackColor(convertColor(parameters.getBackgroundColor())); | |
} | |
if (parameters.getSymbolHeight() != null) { | |
builder.setImageHeight(convertSymbolHeight(parameters.getSymbolHeight())); | |
builder.setAutoSize(false); | |
} | |
builder.setCodeLocation(CodeLocation.None); | |
if (parameters.getDisplayText()) { | |
builder.setCodeLocation(CodeLocation.Below); | |
} | |
builder.getCaptionAbove().setText(""); | |
final float scale = 0.4f; // Empiric scaling factor for converting Word barcode to Aspose.BarCode | |
float xdim = 1.0f; | |
if (builder.getEncodeType() == EncodeTypes.QR) { | |
builder.setAutoSize(false); | |
builder.setImageWidth(builder.getImageWidth() * scale); | |
builder.setImageHeight(builder.getImageWidth()); | |
xdim = builder.getImageHeight() / 25; | |
builder.setyDimension(xdim); | |
builder.setxDimension(xdim); | |
} | |
if (parameters.getScalingFactor() != null) { | |
float scalingFactor = convertScalingFactor(parameters.getScalingFactor()); | |
builder.setImageHeight(builder.getImageHeight() * scalingFactor); | |
if (builder.getEncodeType() == EncodeTypes.QR) { | |
builder.setImageWidth(builder.getImageHeight()); | |
builder.setxDimension(xdim * scalingFactor); | |
builder.setyDimension(xdim * scalingFactor); | |
} | |
builder.setAutoSize(false); | |
} | |
return builder.getBarCodeImage(); | |
} | |
/* (non-Javadoc) | |
* @see com.aspose.words.IBarcodeGenerator#getOldBarcodeImage(com.aspose.words.BarcodeParameters) | |
*/ | |
@Override | |
public BufferedImage getOldBarcodeImage(BarcodeParameters arg0) throws Exception { | |
// TODO Auto-generated method stub | |
return null; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
for (java.util.Map.Entry entry : doc.getVariables()) { | |
String name = entry.getKey().toString(); | |
String value = entry.getValue().toString(); | |
// Do something useful. | |
System.out.println("Name: " + name + ", Value: " + value); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public static void insertADocumentAtABookmark() throws Exception { | |
Document mainDoc = new Document(dataDir + "InsertDocument1.doc"); | |
Document subDoc = new Document(dataDir + "InsertDocument2.doc"); | |
Bookmark bookmark = mainDoc.getRange().getBookmarks().get("insertionPlace"); | |
insertDocument(bookmark.getBookmarkStart().getParentNode(), subDoc); | |
mainDoc.save(dataDir + "InsertDocumentAtBookmark_out.doc"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* Inserts content of the external document after the specified node. | |
* Section breaks and section formatting of the inserted document are | |
* ignored. | |
* | |
* @param insertAfterNode | |
* Node in the destination document after which the content | |
* should be inserted. This node should be a block level node | |
* (paragraph or table). | |
* @param srcDoc | |
* The document to insert. | |
*/ | |
public static void insertDocument(Node insertAfterNode, Document srcDoc) throws Exception { | |
// Make sure that the node is either a paragraph or table. | |
if ((insertAfterNode.getNodeType() != NodeType.PARAGRAPH) & (insertAfterNode.getNodeType() != NodeType.TABLE)) | |
throw new IllegalArgumentException("The destination node should be either a paragraph or table."); | |
// We will be inserting into the parent of the destination paragraph. | |
CompositeNode dstStory = insertAfterNode.getParentNode(); | |
// This object will be translating styles and lists during the import. | |
NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
// Loop through all sections in the source document. | |
for (Section srcSection : srcDoc.getSections()) { | |
// Loop through all block level nodes (paragraphs and tables) in the body of the section. | |
for (Node srcNode : (Iterable<Node>) srcSection.getBody()) { | |
// Let's skip the node if it is a last empty paragraph in a section. | |
if (srcNode.getNodeType() == (NodeType.PARAGRAPH)) { | |
Paragraph para = (Paragraph) srcNode; | |
if (para.isEndOfSection() && !para.hasChildNodes()) | |
continue; | |
} | |
// This creates a clone of the node, suitable for insertion into the destination document. | |
Node newNode = importer.importNode(srcNode, true); | |
// Insert new node after the reference node. | |
dstStory.insertAfter(newNode, insertAfterNode); | |
insertAfterNode = newNode; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public static void insertDocumentAtMailMerge() throws Exception { | |
// Open the main document. | |
Document mainDoc = new Document(dataDir + "InsertDocument1.doc"); | |
// Add a handler to MergeField event | |
mainDoc.getMailMerge().setFieldMergingCallback(new InsertDocumentAtMailMergeHandler()); | |
// The main document has a merge field in it called "Document_1". | |
// The corresponding data for this field contains fully qualified path to the document | |
// that should be inserted to this field. | |
mainDoc.getMailMerge().execute(new String[] { "Document_1" }, new String[] { dataDir + "InsertDocument2.doc" }); | |
mainDoc.save(dataDir + "InsertDocumentAtMailMerge_out.doc"); | |
} | |
private static class InsertDocumentAtMailMergeHandler implements IFieldMergingCallback { | |
/** | |
* This handler makes special processing for the "Document_1" field. The | |
* field value contains the path to load the document. We load the | |
* document and insert it into the current merge field. | |
*/ | |
public void fieldMerging(FieldMergingArgs e) throws Exception { | |
if ("Document_1".equals(e.getDocumentFieldName())) { | |
// Use document builder to navigate to the merge field with the specified name. | |
DocumentBuilder builder = new DocumentBuilder(e.getDocument()); | |
builder.moveToMergeField(e.getDocumentFieldName()); | |
// The name of the document to load and insert is stored in the field value. | |
Document subDoc = new Document((String) e.getFieldValue()); | |
// Insert the document. | |
insertDocument(builder.getCurrentParagraph(), subDoc); | |
// The paragraph that contained the merge field might be empty now and you probably want to delete it. | |
if (!builder.getCurrentParagraph().hasChildNodes()) | |
builder.getCurrentParagraph().remove(); | |
// Indicate to the mail merge engine that we have inserted what we wanted. | |
e.setText(null); | |
} | |
} | |
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception { | |
// Do nothing. | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
//Load a document from a BLOB database field | |
private class InsertDocumentAtMailMergeBlobHandler implements IFieldMergingCallback { | |
/** | |
* This handler makes special processing for the "Document_1" field. The | |
* field value contains the path to load the document. We load the | |
* document and insert it into the current merge field. | |
*/ | |
public void fieldMerging(FieldMergingArgs e) throws Exception { | |
if ("Document_1".equals(e.getDocumentFieldName())) { | |
// Use document builder to navigate to the merge field with the specified name. | |
DocumentBuilder builder = new DocumentBuilder(e.getDocument()); | |
builder.moveToMergeField(e.getDocumentFieldName()); | |
// Load the document from the blob field. | |
ByteArrayInputStream inStream = new ByteArrayInputStream((byte[]) e.getFieldValue()); | |
Document subDoc = new Document(inStream); | |
inStream.close(); | |
// Insert the document. | |
insertDocument(builder.getCurrentParagraph(), subDoc); | |
// The paragraph that contained the merge field might be empty now and you probably want to delete it. | |
if (!builder.getCurrentParagraph().hasChildNodes()) | |
builder.getCurrentParagraph().remove(); | |
// Indicate to the mail merge engine that we have inserted what we wanted. | |
e.setText(null); | |
} | |
} | |
public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception { | |
// Do nothing. | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public static void insertDocumentAtReplace() throws Exception { | |
Document mainDoc = new Document(dataDir + "InsertDocument1.doc"); | |
mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), new InsertDocumentAtReplaceHandler(), false); | |
mainDoc.save(dataDir + "InsertDocumentAtReplace_out.doc"); | |
} | |
private static class InsertDocumentAtReplaceHandler implements IReplacingCallback { | |
public int replacing(ReplacingArgs e) throws Exception { | |
Document subDoc = new Document(dataDir + "InsertDocument2.doc"); | |
// Insert a document after the paragraph, containing the match text. | |
Paragraph para = (Paragraph) e.getMatchNode().getParentNode(); | |
insertDocument(para, subDoc); | |
// Remove the paragraph with the match text. | |
para.remove(); | |
return ReplaceAction.SKIP; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* Inserts content of the external document after the specified node. | |
* | |
* @param insertAfterNode | |
* Node in the destination document after which the content | |
* should be inserted. This node should be a block level node | |
* (paragraph or table). | |
* @param srcDoc | |
* The document to insert. | |
*/ | |
public static void insertDocumentWithSectionFormatting(Node insertAfterNode, Document srcDoc) throws Exception { | |
// Make sure that the node is either a pargraph or table. | |
if ((insertAfterNode.getNodeType() != NodeType.PARAGRAPH) & (insertAfterNode.getNodeType() != NodeType.TABLE)) | |
throw new Exception("The destination node should be either a paragraph or table."); | |
// Document to insert srcDoc into. | |
Document dstDoc = (Document) insertAfterNode.getDocument(); | |
// To retain section formatting, split the current section into two at the marker node and then import the content from srcDoc as whole sections. | |
// The section of the node which the insert marker node belongs to | |
Section currentSection = (Section) insertAfterNode.getAncestor(NodeType.SECTION); | |
// Don't clone the content inside the section, we just want the properties of the section retained. | |
Section cloneSection = (Section) currentSection.deepClone(false); | |
// However make sure the clone section has a body, but no empty first paragraph. | |
cloneSection.ensureMinimum(); | |
cloneSection.getBody().getFirstParagraph().remove(); | |
// Insert the cloned section into the document after the original section. | |
insertAfterNode.getDocument().insertAfter(cloneSection, currentSection); | |
// Append all nodes after the marker node to the new section. This will split the content at the section level at | |
// the marker so the sections from the other document can be inserted directly. | |
Node currentNode = insertAfterNode.getNextSibling(); | |
while (currentNode != null) { | |
Node nextNode = currentNode.getNextSibling(); | |
cloneSection.getBody().appendChild(currentNode); | |
currentNode = nextNode; | |
} | |
// This object will be translating styles and lists during the import. | |
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.USE_DESTINATION_STYLES); | |
// Loop through all sections in the source document. | |
for (Section srcSection : srcDoc.getSections()) { | |
Node newNode = importer.importNode(srcSection, true); | |
// Append each section to the destination document. Start by inserting it after the split section. | |
dstDoc.insertAfter(newNode, currentSection); | |
currentSection = (Section) newNode; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ModifyContentControls.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx"); | |
for (Object t : doc.getChildNodes(NodeType.STRUCTURED_DOCUMENT_TAG, true)) { | |
StructuredDocumentTag std = (StructuredDocumentTag) t; | |
if (std.getSdtType() == SdtType.PLAIN_TEXT) { | |
std.removeAllChildren(); | |
Paragraph para = (Paragraph) std.appendChild(new Paragraph(doc)); | |
Run run = new Run(doc, "new text goes here"); | |
para.appendChild(run); | |
} | |
if (std.getSdtType() == SdtType.DROP_DOWN_LIST) { | |
SdtListItem secondItem = std.getListItems().get(2); | |
std.getListItems().setSelectedValue(secondItem); | |
} | |
if (std.getSdtType() == SdtType.PICTURE) { | |
Shape shape = (Shape) std.getChild(NodeType.SHAPE, 0, true); | |
if (shape.hasImage()) { | |
shape.getImageData().setImage(dataDir + "Watermark.png"); | |
} | |
} | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
String fileName = dataDir + "Properties.doc"; | |
Document doc = new Document(fileName); | |
System.out.println("1. Document name: " + fileName); | |
System.out.println("2. Built-in Properties"); | |
for (DocumentProperty prop : doc.getBuiltInDocumentProperties()) | |
System.out.println(prop.getName() + " : " + prop.getValue()); | |
System.out.println("3. Custom Properties"); | |
for (DocumentProperty prop : doc.getCustomDocumentProperties()) | |
System.out.println(prop.getName() + " : " + prop.getValue()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Properties.doc"); | |
CustomDocumentProperties props = doc.getCustomDocumentProperties(); | |
if (props.get("Authorized") == null) { | |
props.add("Authorized", true); | |
props.add("Authorized By", "John Smith"); | |
props.add("Authorized Date", new Date()); | |
props.add("Authorized Revision", doc.getBuiltInDocumentProperties().getRevisionNumber()); | |
props.add("Authorized Amount", 123.45); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Properties.doc"); | |
doc.getCustomDocumentProperties().remove("Authorized Date"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Properties.doc"); | |
doc.setRemovePersonalInformation(true); | |
dataDir = dataDir + "RemovePersonalInformation_out.docx"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
int protectionType = doc.getProtectionType(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
doc.protect(ProtectionType.ALLOW_ONLY_FORM_FIELDS, "password"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(); | |
doc.unprotect(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(RemoveBreaks.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Remove the page and section breaks from the document. | |
// In Aspose.Words section breaks are represented as separate Section nodes in the document. | |
// To remove these separate sections the sections are combined. | |
removePageBreaks(doc); | |
removeSectionBreaks(doc); | |
// Save the document. | |
doc.save(dataDir + "TestFile Out.doc"); | |
System.out.println("Removed breaks from the document successfully."); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static void removePageBreaks(Document doc) throws Exception { | |
// Retrieve all paragraphs in the document. | |
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true); | |
// Iterate through all paragraphs | |
for (Paragraph para : (Iterable<Paragraph>) paragraphs) { | |
// If the paragraph has a page break before set then clear it. | |
if (para.getParagraphFormat().getPageBreakBefore()) | |
para.getParagraphFormat().setPageBreakBefore(false); | |
// Check all runs in the paragraph for page breaks and remove them. | |
for (Run run : (Iterable<Run>) para.getRuns()) { | |
if (run.getText().contains(ControlChar.PAGE_BREAK)) | |
run.setText(run.getText().replace(ControlChar.PAGE_BREAK, "")); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static void removeSectionBreaks(Document doc) throws Exception { | |
// Loop through all sections starting from the section that precedes the last one | |
// and moving to the first section. | |
for (int i = doc.getSections().getCount() - 2; i >= 0; i--) { | |
// Copy the content of the current section to the beginning of the last section. | |
doc.getLastSection().prependContent(doc.getSections().get(i)); | |
// Remove the copied section. | |
doc.getSections().get(i).remove(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public static void main(String[] args) throws Exception { | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(ReplaceWithEvaluator.class); | |
Document doc = new Document(dataDir + "Document.doc"); | |
doc.getRange().replace(Pattern.compile("[s|m]ad"), new ReplaceCallback(), true); | |
doc.save(dataDir + "output.doc"); | |
} | |
class ReplaceCallback implements IReplacingCallback { | |
private int count = 0; | |
@Override | |
public int replacing(ReplacingArgs args) throws Exception { | |
count++; | |
args.setReplacement("HAPPY-" + count); | |
return ReplaceAction.REPLACE; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ReplaceWithRegex.class); | |
Document doc = new Document(dataDir + "Document.doc"); | |
doc.getRange().replace(Pattern.compile("[s|m]ad"), "happy"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ReplaceWithString.class); | |
Document doc = new Document(dataDir + "Document.doc"); | |
doc.getRange().replace("sad", "bad", false, true); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(RichTextBoxContentControl.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
StructuredDocumentTag sdtRichText =new StructuredDocumentTag(doc, SdtType.RICH_TEXT, MarkupLevel.BLOCK); | |
Paragraph para = new Paragraph(doc); | |
Run run = new Run(doc); | |
run.setText("Hello World"); | |
run.getFont().setColor(Color.MAGENTA); | |
para.getRuns().add(run); | |
sdtRichText.getChildNodes().add(para); | |
doc.getFirstSection().getBody().appendChild(sdtRichText); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(fileName); | |
doc.getCompatibilityOptions().optimizeFor(MsWordVersion.WORD_2016); | |
dataDir = dataDir + "TestFile_out.doc"; | |
// Save the document to disk. | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(SetCurrentStateOfCheckBox.class); | |
// Open the document. | |
Document doc = new Document(dataDir + "CheckBoxTypeContentControl.docx"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
StructuredDocumentTag SdtCheckBox = (StructuredDocumentTag)doc.getChild(NodeType.STRUCTURED_DOCUMENT_TAG, 0, true); | |
//StructuredDocumentTag.Checked property gets/sets current state of the Checkbox SDT | |
if (SdtCheckBox.getSdtType() == SdtType.CHECKBOX) | |
SdtCheckBox.setChecked(true); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
LoadOptions loadOptions = new LoadOptions(); | |
loadOptions.getLanguagePreferences().setAsDefault(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."); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
doc.getViewOptions().setViewType(ViewType.PAGE_LAYOUT); | |
doc.getViewOptions().setZoomPercent(50); | |
doc.save(dataDir + "Document.SetZoom_out.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
// Start tracking and make some revisions. | |
doc.startTrackRevisions("Author"); | |
doc.getFirstSection().getBody().appendParagraph("Hello world!"); | |
// Revisions will now show up as normal text in the output document. | |
doc.acceptAllRevisions(); | |
doc.save(dataDir + "Document.AcceptedRevisions_out_.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Revisions.docx"); | |
for (RevisionGroup group : (Iterable<RevisionGroup>) doc.getRevisions().getGroups()) { | |
System.out.println(group.getAuthor() + ", " + RevisionType.getName(group.getRevisionType()) + ": "); | |
System.out.println(group.getText()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Revisions.docx"); | |
ParagraphCollection paragraphs = doc.getFirstSection().getBody().getParagraphs(); | |
for (int i = 0; i < paragraphs.getCount(); i++) { | |
if (paragraphs.get(i).isMoveFromRevision()) | |
System.out.println("The paragraph " + i + " has been moved (deleted)."); | |
if (paragraphs.get(i).isMoveToRevision()) | |
System.out.println("The paragraph " + i + " has been moved (inserted)."); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Revisions.docx"); | |
//Do not render the comments in PDF | |
doc.getLayoutOptions().setShowComments(false); | |
doc.save(dataDir + "RemoveCommentsinPDF_out.pdf"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Revisions.docx"); | |
// Renders insert and delete revisions inline, format revisions in balloons. | |
doc.getLayoutOptions().getRevisionOptions().setShowInBalloons(ShowInBalloons.FORMAT); | |
// Renders insert revisions inline, delete and format revisions in balloons. | |
//doc.LayoutOptions.RevisionOptions.ShowInBalloons = ShowInBalloons.FormatAndDelete; | |
doc.save(dataDir + "SetShowInBalloons_out.pdf"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(UseControlCharacters.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("This is First Line"); | |
builder.write(ControlChar.CR); | |
builder.write("This is Second Line"); | |
builder.write(ControlChar.CR_LF); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "TestFile.docx"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("Some text"); | |
builder.insertFootnote(FootnoteType.ENDNOTE, "Endnote text."); | |
EndnoteOptions option = doc.getEndnoteOptions(); | |
option.setRestartRule(FootnoteNumberingRule.RESTART_PAGE); | |
option.setPosition(EndnotePosition.END_OF_SECTION); | |
dataDir = dataDir + "TestFile_Out.doc"; | |
// Save the document to disk. | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "TestFile.docx"); | |
//Set footnote and endnode position. | |
doc.getFootnoteOptions().setPosition(FootnotePosition.BENEATH_TEXT); | |
doc.getEndnoteOptions().setPosition(EndnotePosition.END_OF_SECTION); | |
dataDir = dataDir + "TestFile_Out.doc"; | |
// Save the document to disk. | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "TestFile.docx"); | |
//Specify the number of columns with which the footnotes area is formatted. | |
doc.getFootnoteOptions().setColumns(3); | |
dataDir = dataDir + "TestFile_Out.doc"; | |
// Save the document to disk. | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
//Load the Word document | |
Document doc = new Document(dataDir + "Document.doc"); | |
//Open Office uses centimeters when specifying lengths, widths and other measurable formatting | |
//and content properties in documents whereas MS Office uses inches. | |
OdtSaveOptions saveOptions = new OdtSaveOptions(); | |
saveOptions.setMeasureUnit(OdtSaveMeasureUnit.INCHES); | |
//Save the document into ODT | |
doc.save(dataDir + "MeasureUnit_out.odt", saveOptions); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
OoxmlSaveOptions options = new OoxmlSaveOptions(); | |
options.setUpdateLastSavedTimeProperty(true); | |
dataDir = dataDir + "UpdateLastSavedTimeProperty_out.docx"; | |
// Save the document to disk. | |
doc.save(dataDir, options); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(WriteAndFont.class); | |
// Open the document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Font font = builder.getFont(); | |
font.setSize(16); | |
font.setColor(Color.blue); | |
font.setBold(true); | |
font.setName("Algerian"); | |
font.setUnderline(Underline.DOUBLE); | |
builder.write("aspose......... aspose_words_java"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "Input.docx"); | |
ParagraphFormat format = doc.getFirstSection().getBody().getParagraphs().get(0).getParagraphFormat(); | |
format.setFarEastLineBreakControl(false); | |
format.setWordWrap(true); | |
format.setHangingPunctuation(false); | |
dataDir = dataDir + "SetAsianTypographyLinebreakGroupProp_out.doc"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ChangeFieldUpdateCultureSource.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.getFont().setLocaleId(1031); | |
builder.insertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\""); | |
builder.write(" - "); | |
builder.insertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\""); | |
// Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from. | |
// Set the culture used during field update to the culture used by the field. | |
doc.getFieldOptions().setFieldUpdateCultureSource(FieldUpdateCultureSource.FIELD_CODE); | |
//DateTime object issue | |
// doc.getMailMerge().ex | |
// doc.getMailMerge().execute(new String[] { "Date2" }, new Object[] { new (2011, 1, 01) }); | |
// doc.MailMerge.Execute(new string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) }); | |
doc.save(dataDir + "InsertNestedFields Out.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ConvertFieldsInBody.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Pass the appropriate parameters to convert PAGE fields encountered to static text only in the body of the first section. | |
FieldsHelper.convertFieldsToStaticText(doc.getFirstSection().getBody(), FieldType.FIELD_PAGE); | |
// Save the document with fields transformed to disk. | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static class FieldsHelper extends DocumentVisitor { | |
private int mFieldDepth = 0; | |
private ArrayList mNodesToSkip = new ArrayList(); | |
private int mTargetFieldType; | |
private FieldsHelper(int targetFieldType) { | |
mTargetFieldType = targetFieldType; | |
} | |
public static void convertFieldsToStaticText(CompositeNode compositeNode, int targetFieldType) throws Exception { | |
String originalNodeText = compositeNode.toString(SaveFormat.TEXT); //ExSkip | |
FieldsHelper helper = new FieldsHelper(targetFieldType); | |
compositeNode.accept(helper); | |
assert (originalNodeText.equals(compositeNode.toString(SaveFormat.TEXT))) : "Error: Text of the node converted differs from the original"; //ExSkip | |
for (Node node : (Iterable<Node>) compositeNode.getChildNodes(NodeType.ANY, true)) //ExSkip | |
assert (!(node instanceof FieldChar && ((FieldChar) node).getFieldType() == targetFieldType)) : "Error: A field node that should be removed still remains."; //ExSkip | |
} | |
public int visitFieldStart(FieldStart fieldStart) { | |
// We must keep track of the starts and ends of fields incase of any nested fields. | |
if (fieldStart.getFieldType() == mTargetFieldType) { | |
mFieldDepth++; | |
fieldStart.remove(); | |
} else { | |
// This removes the field start if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldStart); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldSeparator(FieldSeparator fieldSeparator) { | |
// When visiting a field separator we should decrease the depth level. | |
if (fieldSeparator.getFieldType() == mTargetFieldType) { | |
mFieldDepth--; | |
fieldSeparator.remove(); | |
} else { | |
// This removes the field separator if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldSeparator); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldEnd(FieldEnd fieldEnd) { | |
if (fieldEnd.getFieldType() == mTargetFieldType) | |
fieldEnd.remove(); | |
else | |
CheckDepthAndRemoveNode(fieldEnd); // This removes the field end if it's inside a field that is being converted. | |
return VisitorAction.CONTINUE; | |
} | |
public int visitRun(Run run) { | |
// Remove the run if it is between the FieldStart and FieldSeparator of the field being converted. | |
CheckDepthAndRemoveNode(run); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitParagraphEnd(Paragraph paragraph) { | |
if (mFieldDepth > 0) { | |
// The field code that is being converted continues onto another paragraph. We | |
// need to copy the remaining content from this paragraph onto the next paragraph. | |
Node nextParagraph = paragraph.getNextSibling(); | |
// Skip ahead to the next available paragraph. | |
while (nextParagraph != null && nextParagraph.getNodeType() != NodeType.PARAGRAPH) | |
nextParagraph = nextParagraph.getNextSibling(); | |
// Copy all of the nodes over. Keep a list of these nodes so we know not to remove them. | |
while (paragraph.hasChildNodes()) { | |
mNodesToSkip.add(paragraph.getLastChild()); | |
((Paragraph) nextParagraph).prependChild(paragraph.getLastChild()); | |
} | |
paragraph.remove(); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitTableStart(Table table) { | |
CheckDepthAndRemoveNode(table); | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Checks whether the node is inside a field or should be skipped and then removes it if necessary. | |
*/ | |
private void CheckDepthAndRemoveNode(Node node) { | |
if (mFieldDepth > 0 && !mNodesToSkip.contains(node)) | |
node.remove(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ConvertFieldsInDocument.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Pass the appropriate parameters to convert all IF fields encountered in the document (including headers and footers) to static text. | |
FieldsHelper.convertFieldsToStaticText(doc, FieldType.FIELD_IF); | |
// Save the document with fields transformed to disk. | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static class FieldsHelper extends DocumentVisitor { | |
private int mFieldDepth = 0; | |
private ArrayList mNodesToSkip = new ArrayList(); | |
private int mTargetFieldType; | |
private FieldsHelper(int targetFieldType) { | |
mTargetFieldType = targetFieldType; | |
} | |
/** | |
* Converts any fields of the specified type found in the descendants of the node into static text. | |
* | |
* @param compositeNode The node in which all descendants of the specified FieldType will be converted to static text. | |
* @param targetFieldType The FieldType of the field to convert to static text. | |
*/ | |
public static void convertFieldsToStaticText(CompositeNode compositeNode, int targetFieldType) throws Exception { | |
String originalNodeText = compositeNode.toString(SaveFormat.TEXT); //ExSkip | |
FieldsHelper helper = new FieldsHelper(targetFieldType); | |
compositeNode.accept(helper); | |
assert (originalNodeText.equals(compositeNode.toString(SaveFormat.TEXT))) : "Error: Text of the node converted differs from the original"; //ExSkip | |
for (Node node : (Iterable<Node>) compositeNode.getChildNodes(NodeType.ANY, true)) //ExSkip | |
assert (!(node instanceof FieldChar && ((FieldChar) node).getFieldType() == targetFieldType)) : "Error: A field node that should be removed still remains."; //ExSkip | |
} | |
public int visitFieldStart(FieldStart fieldStart) { | |
// We must keep track of the starts and ends of fields incase of any nested fields. | |
if (fieldStart.getFieldType() == mTargetFieldType) { | |
mFieldDepth++; | |
fieldStart.remove(); | |
} else { | |
// This removes the field start if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldStart); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldSeparator(FieldSeparator fieldSeparator) { | |
// When visiting a field separator we should decrease the depth level. | |
if (fieldSeparator.getFieldType() == mTargetFieldType) { | |
mFieldDepth--; | |
fieldSeparator.remove(); | |
} else { | |
// This removes the field separator if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldSeparator); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldEnd(FieldEnd fieldEnd) { | |
if (fieldEnd.getFieldType() == mTargetFieldType) | |
fieldEnd.remove(); | |
else | |
CheckDepthAndRemoveNode(fieldEnd); // This removes the field end if it's inside a field that is being converted. | |
return VisitorAction.CONTINUE; | |
} | |
public int visitRun(Run run) { | |
// Remove the run if it is between the FieldStart and FieldSeparator of the field being converted. | |
CheckDepthAndRemoveNode(run); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitParagraphEnd(Paragraph paragraph) { | |
if (mFieldDepth > 0) { | |
// The field code that is being converted continues onto another paragraph. We | |
// need to copy the remaining content from this paragraph onto the next paragraph. | |
Node nextParagraph = paragraph.getNextSibling(); | |
// Skip ahead to the next available paragraph. | |
while (nextParagraph != null && nextParagraph.getNodeType() != NodeType.PARAGRAPH) | |
nextParagraph = nextParagraph.getNextSibling(); | |
// Copy all of the nodes over. Keep a list of these nodes so we know not to remove them. | |
while (paragraph.hasChildNodes()) { | |
mNodesToSkip.add(paragraph.getLastChild()); | |
((Paragraph) nextParagraph).prependChild(paragraph.getLastChild()); | |
} | |
paragraph.remove(); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitTableStart(Table table) { | |
CheckDepthAndRemoveNode(table); | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Checks whether the node is inside a field or should be skipped and then removes it if necessary. | |
*/ | |
private void CheckDepthAndRemoveNode(Node node) { | |
if (mFieldDepth > 0 && !mNodesToSkip.contains(node)) | |
node.remove(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ConvertFieldsInParagraph.class); | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
// Pass the appropriate parameters to convert all IF fields to static text that are encountered only in the last | |
// paragraph of the document. | |
FieldsHelper.convertFieldsToStaticText(doc.getFirstSection().getBody().getLastParagraph(), FieldType.FIELD_IF); | |
// Save the document with fields transformed to disk. | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static class FieldsHelper extends DocumentVisitor { | |
private int mFieldDepth = 0; | |
private ArrayList mNodesToSkip = new ArrayList(); | |
private int mTargetFieldType; | |
private FieldsHelper(int targetFieldType) { | |
mTargetFieldType = targetFieldType; | |
} | |
public static void convertFieldsToStaticText(CompositeNode compositeNode, int targetFieldType) throws Exception { | |
String originalNodeText = compositeNode.toString(SaveFormat.TEXT); //ExSkip | |
FieldsHelper helper = new FieldsHelper(targetFieldType); | |
compositeNode.accept(helper); | |
assert (originalNodeText.equals(compositeNode.toString(SaveFormat.TEXT))) : "Error: Text of the node converted differs from the original"; //ExSkip | |
for (Node node : (Iterable<Node>) compositeNode.getChildNodes(NodeType.ANY, true)) //ExSkip | |
assert (!(node instanceof FieldChar && ((FieldChar) node).getFieldType() == targetFieldType)) : "Error: A field node that should be removed still remains."; //ExSkip | |
} | |
public int visitFieldStart(FieldStart fieldStart) { | |
// We must keep track of the starts and ends of fields incase of any nested fields. | |
if (fieldStart.getFieldType() == mTargetFieldType) { | |
mFieldDepth++; | |
fieldStart.remove(); | |
} else { | |
// This removes the field start if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldStart); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldSeparator(FieldSeparator fieldSeparator) { | |
// When visiting a field separator we should decrease the depth level. | |
if (fieldSeparator.getFieldType() == mTargetFieldType) { | |
mFieldDepth--; | |
fieldSeparator.remove(); | |
} else { | |
// This removes the field separator if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldSeparator); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldEnd(FieldEnd fieldEnd) { | |
if (fieldEnd.getFieldType() == mTargetFieldType) | |
fieldEnd.remove(); | |
else | |
CheckDepthAndRemoveNode(fieldEnd); // This removes the field end if it's inside a field that is being converted. | |
return VisitorAction.CONTINUE; | |
} | |
public int visitRun(Run run) { | |
// Remove the run if it is between the FieldStart and FieldSeparator of the field being converted. | |
CheckDepthAndRemoveNode(run); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitParagraphEnd(Paragraph paragraph) { | |
if (mFieldDepth > 0) { | |
// The field code that is being converted continues onto another paragraph. We | |
// need to copy the remaining content from this paragraph onto the next paragraph. | |
Node nextParagraph = paragraph.getNextSibling(); | |
// Skip ahead to the next available paragraph. | |
while (nextParagraph != null && nextParagraph.getNodeType() != NodeType.PARAGRAPH) | |
nextParagraph = nextParagraph.getNextSibling(); | |
// Copy all of the nodes over. Keep a list of these nodes so we know not to remove them. | |
while (paragraph.hasChildNodes()) { | |
mNodesToSkip.add(paragraph.getLastChild()); | |
((Paragraph) nextParagraph).prependChild(paragraph.getLastChild()); | |
} | |
paragraph.remove(); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitTableStart(Table table) { | |
CheckDepthAndRemoveNode(table); | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Checks whether the node is inside a field or should be skipped and then removes it if necessary. | |
*/ | |
private void CheckDepthAndRemoveNode(Node node) { | |
if (mFieldDepth > 0 && !mNodesToSkip.contains(node)) | |
node.remove(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
DocumentBuilder builder = new DocumentBuilder(); | |
FieldIf field = (FieldIf)builder.insertField("IF 1 = 1", null); | |
int actualResult = field.evaluateCondition(); | |
switch (actualResult) { | |
case 0: | |
System.out.println("ERROR"); | |
break; | |
case 1: | |
System.out.println("TRUE"); | |
break; | |
case 2: | |
System.out.println("FALSE"); | |
break; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static class FieldsHelper extends DocumentVisitor { | |
private int mFieldDepth = 0; | |
private ArrayList mNodesToSkip = new ArrayList(); | |
private int mTargetFieldType; | |
/** | |
* Converts any fields of the specified type found in the descendants of the node into static text. | |
* | |
* @param compositeNode The node in which all descendants of the specified FieldType will be converted to static text. | |
* @param targetFieldType The FieldType of the field to convert to static text. | |
*/ | |
public static void convertFieldsToStaticText(CompositeNode compositeNode, int targetFieldType) throws Exception { | |
String originalNodeText = compositeNode.toString(SaveFormat.TEXT); //ExSkip | |
FieldsHelper helper = new FieldsHelper(targetFieldType); | |
compositeNode.accept(helper); | |
assert (originalNodeText.equals(compositeNode.toString(SaveFormat.TEXT))) : "Error: Text of the node converted differs from the original"; //ExSkip | |
for (Node node : (Iterable<Node>)compositeNode.getChildNodes(NodeType.ANY, true)) //ExSkip | |
assert (!(node instanceof FieldChar && ((FieldChar)node).getFieldType() == targetFieldType)) : "Error: A field node that should be removed still remains."; //ExSkip | |
} | |
private FieldsHelper(int targetFieldType) { | |
mTargetFieldType = targetFieldType; | |
} | |
public int visitFieldStart(FieldStart fieldStart) { | |
// We must keep track of the starts and ends of fields incase of any nested fields. | |
if (fieldStart.getFieldType() == mTargetFieldType) | |
{ | |
mFieldDepth++; | |
fieldStart.remove(); | |
} | |
else | |
{ | |
// This removes the field start if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldStart); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldSeparator(FieldSeparator fieldSeparator) { | |
// When visiting a field separator we should decrease the depth level. | |
if (fieldSeparator.getFieldType() == mTargetFieldType) | |
{ | |
mFieldDepth--; | |
fieldSeparator.remove(); | |
} | |
else | |
{ | |
// This removes the field separator if it's inside a field that is being converted. | |
CheckDepthAndRemoveNode(fieldSeparator); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitFieldEnd(FieldEnd fieldEnd) { | |
if (fieldEnd.getFieldType() == mTargetFieldType) | |
fieldEnd.remove(); | |
else | |
CheckDepthAndRemoveNode(fieldEnd); // This removes the field end if it's inside a field that is being converted. | |
return VisitorAction.CONTINUE; | |
} | |
public int visitRun(Run run) { | |
// Remove the run if it is between the FieldStart and FieldSeparator of the field being converted. | |
CheckDepthAndRemoveNode(run); | |
return VisitorAction.CONTINUE; | |
} | |
public int visitParagraphEnd(Paragraph paragraph) { | |
if (mFieldDepth > 0) | |
{ | |
// The field code that is being converted continues onto another paragraph. We | |
// need to copy the remaining content from this paragraph onto the next paragraph. | |
Node nextParagraph = paragraph.getNextSibling(); | |
// Skip ahead to the next available paragraph. | |
while (nextParagraph != null && nextParagraph.getNodeType() != NodeType.PARAGRAPH) | |
nextParagraph = nextParagraph.getNextSibling(); | |
// Copy all of the nodes over. Keep a list of these nodes so we know not to remove them. | |
while (paragraph.hasChildNodes()) | |
{ | |
mNodesToSkip.add(paragraph.getLastChild()); | |
((Paragraph)nextParagraph).prependChild(paragraph.getLastChild()); | |
} | |
paragraph.remove(); | |
} | |
return VisitorAction.CONTINUE; | |
} | |
public int visitTableStart(Table table) { | |
CheckDepthAndRemoveNode(table); | |
return VisitorAction.CONTINUE; | |
} | |
/** | |
* Checks whether the node is inside a field or should be skipped and then removes it if necessary. | |
*/ | |
private void CheckDepthAndRemoveNode(Node node) { | |
if (mFieldDepth > 0 && !mNodesToSkip.contains(node)) | |
node.remove(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class FieldResultFormatter implements IFieldResultFormatter { | |
private final String mNumberFormat; | |
private final String mDateFormat; | |
private final ArrayList mNumberFormatInvocations = new ArrayList(); | |
private final ArrayList mDateFormatInvocations = new ArrayList(); | |
public FieldResultFormatter(String numberFormat, String dateFormat) { | |
mNumberFormat = numberFormat; | |
mDateFormat = dateFormat; | |
} | |
public FieldResultFormatter() { | |
mNumberFormat = null; | |
mDateFormat = null; | |
} | |
public String format(String arg0, int arg1) { | |
// TODO Auto-generated method stub | |
return null; | |
} | |
public String format(double arg0, int arg1) { | |
// TODO Auto-generated method stub | |
return null; | |
} | |
public String formatNumeric(double value, String format) { | |
// TODO Auto-generated method stub | |
mNumberFormatInvocations.add(new Object[] { value, format }); | |
return (mNumberFormat.isEmpty() || mNumberFormat == null) ? null | |
: String.format(mNumberFormat, value); | |
} | |
public String formatDateTime(Date value, String format, int calendarType) { | |
mDateFormatInvocations | |
.add(new Object[] { value, format, calendarType }); | |
return (mDateFormat.isEmpty() || mDateFormat == null) ? null : String | |
.format(mDateFormat, value); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
DocumentBuilder builder = new DocumentBuilder(); | |
Document document = builder.getDocument(); | |
Field field = builder.insertField("=-1234567.89 \\# \"### ### ###.000\"", null); | |
document.getFieldOptions().setResultFormatter(new FieldResultFormatter("[%0$s]", null)); | |
field.update(); | |
document.save(dataDir+"FormatFieldResult_out.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(FormFieldsGetByName.class); | |
Document doc = new Document(dataDir + "FormFields.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// FormFieldCollection formFields = doc.getRange().getFormFields(); | |
FormFieldCollection documentFormFields = doc.getRange().getFormFields(); | |
FormField formField1 = documentFormFields.get(3); | |
FormField formField2 = documentFormFields.get("Text2"); | |
System.out.println("Name: " + formField2.getName()); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(FormFieldsGetFormFieldsCollection.class); | |
Document doc = new Document(dataDir + "FormFields.doc"); | |
FormFieldCollection formFields = doc.getRange().getFormFields(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(FormFieldsWorkWithProperties.class); | |
Document doc = new Document(dataDir + "FormFields.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
FormFieldCollection documentFormFields = doc.getRange().getFormFields(); | |
FormField formField = doc.getRange().getFormFields().get(3); | |
if (formField.getType() == FieldType.FIELD_FORM_TEXT_INPUT) | |
formField.setResult("Field Name :" + formField.getName()); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(GetFieldNames.class); | |
Document doc = new Document(dataDir + "Rendering.doc"); | |
String[] fieldNames = doc.getMailMerge().getFieldNames(); | |
System.out.println("\nDocument have " + fieldNames.length + " fields."); | |
for (String name : fieldNames) { | |
System.out.println(name); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertAdvanceFieldWithOutDocumentBuilder.class); | |
Document doc = new Document(dataDir + "in.doc"); | |
// Get paragraph you want to append this merge field to | |
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(1); | |
// We want to insert an Advance field like this:// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 } | |
// Create instance of FieldAdvance class and lets build the above field code | |
FieldAdvance field = (FieldAdvance) para.appendField(FieldType.FIELD_ADVANCE, false); | |
// { ADVANCE \\d 10 " } | |
field.setDownOffset("10"); | |
// { ADVANCE \\d 10 \\l 10 } | |
field.setLeftOffset("10"); | |
// { ADVANCE \\d 10 \\l 10 \\r -3.3 } | |
field.setRightOffset("-3.3"); | |
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 } | |
field.setUpOffset("0"); | |
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 } | |
field.setHorizontalPosition("100"); | |
// { ADVANCE \\d 10 \\l 10 \\r -3.3 \\u 0 \\x 100 \\y 100 } | |
field.setVerticalPosition("100"); | |
// Finally update this Advance field | |
field.update(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertASKFieldWithOutDocumentBuilder.class); | |
Document doc = new Document(dataDir + "in.doc"); | |
// Get paragraph you want to append this merge field to | |
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(1); | |
// We want to insert an Ask field like this: | |
// { ASK \"Test 1\" Test2 \\d Test3 \\o } | |
// Create instance of FieldAsk class and lets build the above field code | |
FieldAsk field = (FieldAsk) para.appendField(FieldType.FIELD_ASK, false); | |
// { ASK \"Test 1\" " } | |
field.setBookmarkName("Test 1"); | |
// { ASK \"Test 1\" Test2 } | |
field.setPromptText("Test2"); | |
// { ASK \"Test 1\" Test2 \\d Test3 } | |
field.setDefaultResponse("Test3"); | |
// { ASK \"Test 1\" Test2 \\d Test3 \\o } | |
field.setPromptOnceOnMailMerge(true); | |
// Finally update this Advance field | |
field.update(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertField.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.insertField("MERGEFIELD MyFieldName \\* MERGEFORMAT"); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
FieldUnknown field = (FieldUnknown)builder.insertField(FieldType.FIELD_NONE, false); | |
dataDir = dataDir + "InsertFieldNone_out.docx"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertFormFields.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
String[] items = {"One", "Two", "Three"}; | |
builder.insertComboBox("DropDown", items, 0); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "in.doc"); | |
//Get paragraph you want to append this INCLUDETEXT field to | |
Paragraph para = (Paragraph)doc.getChildNodes(NodeType.PARAGRAPH, true).get(1); | |
//We want to insert an INCLUDETEXT field like this: | |
//{ INCLUDETEXT "file path" } | |
//Create instance of FieldAsk class and lets build the above field code | |
FieldIncludeText fieldincludeText = (FieldIncludeText)para.appendField(FieldType.FIELD_INCLUDE_TEXT, false); | |
fieldincludeText.setBookmarkName("bookmark"); | |
fieldincludeText.setSourceFullName(dataDir+"IncludeText.docx"); | |
doc.getFirstSection().getBody().appendChild(para); | |
//Finally update this INCLUDETEXT field | |
fieldincludeText.update(); | |
dataDir = dataDir + "InsertIncludeFieldWithoutDocumentBuilder_out.doc"; | |
doc.save(dataDir); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertMailMergeAddressBlockFieldUsingDOM.class); | |
Document doc = new Document(dataDir + "in.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Get paragraph you want to append this merge field to | |
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(1); | |
// Move cursor to this paragraph | |
builder.moveTo(para); | |
// We want to insert a mail merge address block like this: | |
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" } | |
// Create instance of FieldAddressBlock class and lets build the above field code | |
FieldAddressBlock field = (FieldAddressBlock) builder.insertField(FieldType.FIELD_ADDRESS_BLOCK, false); | |
// { ADDRESSBLOCK \\c 1" } | |
field.setIncludeCountryOrRegionName("1"); | |
// { ADDRESSBLOCK \\c 1 \\d" } | |
field.setFormatAddressOnCountryOrRegion(true); | |
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 } | |
field.setExcludedCountryOrRegionName("Test2"); | |
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 } | |
field.setNameAndAddressFormat("Test3"); | |
// { ADDRESSBLOCK \\c 1 \\d \\e Test2 \\f Test3 \\l \"Test 4\" } | |
field.setLanguageId("Test4"); | |
// Finally update this merge field | |
field.update(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertMergeFieldUsingDOM.class); | |
Document doc = new Document(dataDir + "in.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Get paragraph you want to append this merge field to | |
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(1); | |
// Move cursor to this paragraph | |
builder.moveTo(para); | |
// We want to insert a merge field like this: | |
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" } | |
// Create instance of FieldMergeField class and lets build the above field code | |
FieldMergeField field = (FieldMergeField) builder.insertField(FieldType.FIELD_MERGE_FIELD, false); | |
// { " MERGEFIELD Test1" } | |
field.setFieldName("Test1"); | |
// { " MERGEFIELD Test1 \\b Test2" } | |
field.setTextBefore("Test2"); | |
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 } | |
field.setTextAfter("Test3"); | |
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m" } | |
field.isMapped(true); | |
// { " MERGEFIELD Test1 \\b Test2 \\f Test3 \\m \\v" } | |
field.isVerticalFormatting(true); | |
// Finally update this merge field | |
field.update(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertNestedFields.class); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Insert few page breaks (just for testing) | |
for (int i = 0; i < 5; i++) | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
// Move DocumentBuilder cursor into the primary footer. | |
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY); | |
// We want to insert a field like this: | |
// { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" } | |
Field field = builder.insertField("IF "); | |
builder.moveTo(field.getSeparator()); | |
builder.insertField("PAGE"); | |
builder.write(" <> "); | |
builder.insertField("NUMPAGES"); | |
builder.write(" \"See Next Page\" \"Last Page\" "); | |
// Finally update the outer field to recalcaluate the final value. Doing this will automatically update | |
// the inner fields at the same time. | |
field.update(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir+ "in.doc"); | |
// Get paragraph you want to append this TOA field to | |
Paragraph para = (Paragraph) doc.getChildNodes(NodeType.PARAGRAPH, true).get(1); | |
// We want to insert TA and TOA fields like this: | |
// { TA \c 1 \l "Value 0" } | |
// { TOA \c 1 } | |
// Create instance of FieldA class and lets build the above field code | |
FieldTA fieldTA = (FieldTA) para.appendField(FieldType.FIELD_TOA_ENTRY,false); | |
fieldTA.setEntryCategory("1"); | |
fieldTA.setLongCitation("Value 0"); | |
doc.getFirstSection().getBody().appendChild(para); | |
para = new Paragraph(doc); | |
// Create instance of FieldToa class | |
FieldToa fieldToa = (FieldToa) para.appendField(FieldType.FIELD_TOA,false); | |
fieldToa.setEntryCategory("1"); | |
doc.getFirstSection().getBody().appendChild(para); | |
// Finally update this TOA field | |
fieldToa.update(); | |
dataDir = dataDir + "InsertTOAFieldWithoutDocumentBuilder_out.doc"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
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 | |
doc.save(dataDir + "output.docx", SaveFormat.DOCX); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(RemoveField.class); | |
Document doc = new Document(dataDir + "Field.RemoveField.doc"); | |
Field field = doc.getRange().getFields().get(0); | |
// Calling this method completely removes the field from the document. | |
field.remove(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* Shows how to rename merge fields in a Word document. | |
*/ | |
public class RenameMergeFields { | |
private static final String dataDir = Utils.getSharedDataDir(RenameMergeFields.class) + "Fields/"; | |
/** | |
* Finds all merge fields in a Word document and changes their names. | |
*/ | |
public static void main(String[] args) throws Exception { | |
// Specify your document name here. | |
Document doc = new Document(dataDir + "RenameMergeFields.doc"); | |
// Select all field start nodes so we can find the merge fields. | |
NodeCollection fieldStarts = doc.getChildNodes(NodeType.FIELD_START, true); | |
for (FieldStart fieldStart : (Iterable<FieldStart>) fieldStarts) { | |
if (fieldStart.getFieldType() == FieldType.FIELD_MERGE_FIELD) { | |
MergeField mergeField = new MergeField(fieldStart); | |
mergeField.setName(mergeField.getName() + "_Renamed"); | |
} | |
} | |
doc.save(dataDir + "RenameMergeFields Out.doc"); | |
} | |
} | |
/** | |
* Represents a facade object for a merge field in a Microsoft Word document. | |
*/ | |
class MergeField { | |
private final Node mFieldStart; | |
private final Node mFieldSeparator; | |
private final Node mFieldEnd; | |
private static final Pattern G_REGEX = Pattern.compile("\\s*(MERGEFIELD\\s|)(\\s|)(\\S+)\\s+"); | |
MergeField(FieldStart fieldStart) throws Exception { | |
if (fieldStart.equals(null)) | |
throw new IllegalArgumentException("fieldStart"); | |
if (fieldStart.getFieldType() != FieldType.FIELD_MERGE_FIELD) | |
throw new IllegalArgumentException("Field start type must be FieldMergeField."); | |
mFieldStart = fieldStart; | |
// Find the field separator node. | |
mFieldSeparator = fieldStart.getField().getSeparator(); | |
if (mFieldSeparator == null) | |
throw new IllegalStateException("Cannot find field separator."); | |
mFieldEnd = fieldStart.getField().getEnd(); | |
} | |
/** | |
* Gets or sets the name of the merge field. | |
*/ | |
String getName() throws Exception { | |
return ((FieldStart) mFieldStart).getField().getResult().replace("«", "").replace("»", ""); | |
} | |
void setName(String value) throws Exception { | |
// Merge field name is stored in the field result which is a Run | |
// node between field separator and field end. | |
Run fieldResult = (Run) mFieldSeparator.getNextSibling(); | |
fieldResult.setText(java.text.MessageFormat.format("«{0}»", value)); | |
// But sometimes the field result can consist of more than one run, delete these runs. | |
removeSameParent(fieldResult.getNextSibling(), mFieldEnd); | |
updateFieldCode(value); | |
} | |
private void updateFieldCode(String fieldName) throws Exception { | |
// Field code is stored in a Run node between field start and field separator. | |
Run fieldCode = (Run) mFieldStart.getNextSibling(); | |
Matcher matcher = G_REGEX.matcher(((FieldStart) mFieldStart).getField().getFieldCode()); | |
matcher.find(); | |
String newFieldCode = java.text.MessageFormat.format(" {0}{1} ", matcher.group(1).toString(), fieldName); | |
fieldCode.setText(newFieldCode); | |
// But sometimes the field code can consist of more than one run, delete these runs. | |
removeSameParent(fieldCode.getNextSibling(), mFieldSeparator); | |
} | |
/** | |
* Removes nodes from start up to but not including the end node. Start and | |
* end are assumed to have the same parent. | |
*/ | |
private static void removeSameParent(Node startNode, Node endNode) throws Exception { | |
if ((endNode != null) && (startNode.getParentNode() != endNode.getParentNode())) | |
throw new IllegalArgumentException("Start and end nodes are expected to have the same parent."); | |
Node curChild = startNode; | |
while ((curChild != null) && (curChild != endNode)) { | |
Node nextChild = curChild.getNextSibling(); | |
curChild.remove(); | |
curChild = nextChild; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(UpdateDocFields.class); | |
Document doc = new Document(dataDir + "Rendering.doc"); | |
doc.updateFields(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// update fields | |
doc.updateFields(); | |
doc.save(dataDir + "output.docx"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
class ReplaceEvaluatorFindAndHighlight implements IReplacingCallback { | |
/** | |
* This method is called by the Aspose.Words find and replace engine for each match. | |
* This method highlights the match string, even if it spans multiple runs. | |
*/ | |
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()); | |
// This array is used to store all nodes of the match for further highlighting. | |
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); | |
} | |
// Now highlight all runs in the sequence. | |
for (Run run : (Iterable<Run>) runs) | |
run.getFont().setHighlightColor(Color.YELLOW); | |
// Signal to the replace engine to do nothing because we have already done all what we wanted. | |
return ReplaceAction.SKIP; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class FindAndHighlightText { | |
private static final String dataDir = Utils.getSharedDataDir(FindAndHighlightText.class) + "FindAndReplace/"; | |
public static void main(String[] args) throws Exception { | |
Document doc = new Document(dataDir + "TestFile.doc"); | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.ReplacingCallback = new ReplaceEvaluatorFindAndHighlight(); | |
// We want the "your document" phrase to be highlighted. | |
Pattern regex = Pattern.compile("your document", Pattern.CASE_INSENSITIVE); | |
doc.getRange().replace(regex, "", options); | |
// Save the output document. | |
doc.save(dataDir + "TestFile_out.doc"); | |
} | |
} | |
class ReplaceEvaluatorFindAndHighlight implements IReplacingCallback { | |
/** | |
* This method is called by the Aspose.Words find and replace engine for | |
* each match. This method highlights the match string, even if it spans | |
* multiple runs. | |
*/ | |
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()); | |
// This array is used to store all nodes of the match for further highlighting. | |
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); | |
} | |
// Now highlight all runs in the sequence. | |
for (Run run : (Iterable<Run>) runs) | |
run.getFont().setHighlightColor(Color.YELLOW); | |
// 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 static 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Initialize a Document. | |
Document doc = new Document(); | |
// Use a document builder to add content to the document. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.writeln("This is Line 1"); | |
builder.writeln("This is Line 2"); | |
FindReplaceOptions findReplaceOptions = new FindReplaceOptions(); | |
doc.getRange().replace("This is Line 1&pThis is Line 2", "This is replaced line", findReplaceOptions); | |
builder.moveToDocumentEnd(); | |
builder.write("This is Line 1"); | |
builder.insertBreak(BreakType.PAGE_BREAK); | |
builder.writeln("This is Line 2"); | |
doc.getRange().replace("This is Line 1&mThis is Line 2", "Page break is replaced with new text.", findReplaceOptions); | |
dataDir = dataDir + "MetaCharactersInSearchPattern_out.docx"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
builder.getFont().setName("Arial"); | |
builder.writeln("First section"); | |
builder.writeln(" 1st paragraph"); | |
builder.writeln(" 2nd paragraph"); | |
builder.writeln("{insert-section}"); | |
builder.writeln("Second section"); | |
builder.writeln(" 1st paragraph"); | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.getApplyParagraphFormat().setAlignment(ParagraphAlignment.CENTER); | |
// Double each paragraph break after word "section", add kind of underline and make it centered. | |
int count = doc.getRange().replace("section&p", "section&p----------------------&p", options); | |
// Insert section break instead of custom text tag. | |
count = doc.getRange().replace("{insert-section}", "&b", options); | |
dataDir = dataDir + "ReplaceTextContaingMetaCharacters_out.docx"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
static class FindAndInsertHtml 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(); | |
// create Document Buidler and insert MergeField | |
DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument()); | |
builder.moveTo(currentNode); | |
builder.insertHtml(e.getReplacement()); | |
currentNode.remove(); | |
//Signal to the replace engine to do nothing because we have already done all what we wanted. | |
return ReplaceAction.SKIP; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.getSharedDataDir(ReplaceTextWithField.class) + "FindAndReplace/"; | |
String html = "<p>“Some Text”</p>"; | |
// Initialize a Document. | |
Document doc = new Document(); | |
// Use a document builder to add content to the document. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("{PLACEHOLDER}"); | |
FindReplaceOptions findReplaceOptions = new FindReplaceOptions(); | |
findReplaceOptions.setReplacingCallback(new FindAndInsertHtml()); | |
findReplaceOptions.setPreserveMetaCharacters(true); | |
doc.getRange().replace("{PLACEHOLDER}", html, findReplaceOptions); | |
dataDir = dataDir + "ReplaceHtmlTextWithMetaCharacters_out.doc"; | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class ReplaceWithEvaluator { | |
private static final String dataDir = Utils.getSharedDataDir(ReplaceWithEvaluator.class) + "FindAndReplace/"; | |
public static void main(String[] args) throws Exception { | |
Document doc = new Document(dataDir + "Range.ReplaceWithEvaluator.doc"); | |
FindReplaceOptions options = new FindReplaceOptions(); | |
options.ReplacingCallback = new MyReplaceEvaluator(); | |
doc.getRange().replace(Pattern.compile("[s|m]ad"), "", options); | |
doc.save(dataDir + "Range.ReplaceWithEvaluator_Out.doc"); | |
} | |
} | |
class MyReplaceEvaluator implements IReplacingCallback { | |
private int mMatchNumber; | |
/** | |
* This is called during a replace operation each time a match is found. | |
* This method appends a number to the match string and returns it as a | |
* replacement string. | |
*/ | |
public int replacing(ReplacingArgs e) throws Exception { | |
e.setReplacement(e.getMatch().group() + Integer.toString(mMatchNumber)); | |
mMatchNumber++; | |
return ReplaceAction.REPLACE; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class ReplaceWithEvaluator { | |
public static void main(String[] args) throws Exception { | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(ReplaceWithEvaluator.class); | |
Document doc = new Document(dataDir + "Document.doc"); | |
doc.getRange().replace(Pattern.compile("[s|m]ad"), new ReplaceCallback(), true); | |
doc.save(dataDir + "output.doc"); | |
} | |
} | |
class ReplaceCallback implements IReplacingCallback { | |
private int count = 0; | |
@Override | |
public int replacing(ReplacingArgs args) throws Exception { | |
count++; | |
args.setReplacement("HAPPY-" + count); | |
return ReplaceAction.REPLACE; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "ReplaceWithRegex.doc"); | |
FindReplaceOptions options = new FindReplaceOptions(); | |
doc.getRange().replace(Pattern.compile("[s|m]ad"), "happy", options); | |
doc.save(dataDir + "ReplaceWithRegex_Out.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ReplaceWithRegex.class); | |
Document doc = new Document(dataDir + "Document.doc"); | |
doc.getRange().replace(Pattern.compile("[s|m]ad"), "happy"); | |
doc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(dataDir + "ReplaceWithString.doc"); | |
doc.getRange().replace("sad", "bad", new FindReplaceOptions(FindReplaceDirection.FORWARD)); | |
doc.save(dataDir + "ReplaceWithString_out.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ReplaceWithString.class); | |
Document doc = new Document(dataDir + "test.docx"); | |
doc.getRange().replace("sad", "bad", false, true); | |
doc.save(dataDir + "output.doc"); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
/** | |
* Splits text of the specified run into two runs. Inserts the new run just | |
* after the specified run. | |
*/ | |
private static 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ReplaceHyperlinks.class); | |
String NewUrl = "http://www.aspose.com"; | |
String NewName = "Aspose - The .NET & Java Component Publisher"; | |
// Open the document. | |
Document doc = new Document(dataDir + "ReplaceHyperlinks.doc"); | |
for (Field field : doc.getRange().getFields()) { | |
if (field.getType() == FieldType.FIELD_HYPERLINK) { | |
FieldHyperlink hyperlink = (FieldHyperlink) field; | |
// Some hyperlinks can be local (links to bookmarks inside the document), ignore these. | |
if (hyperlink.getSubAddress() != null) | |
continue; | |
hyperlink.setAddress(NewUrl); | |
hyperlink.setResult(NewName); | |
} | |
doc.save(dataDir + "output.doc"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class AddWatermarkToADocument { | |
private static final String dataDir = Utils.getSharedDataDir(AddWatermarkToADocument.class) + "Document/"; | |
public static void main(String[] args) throws Exception { | |
Document doc = new Document(dataDir + "Document.doc"); | |
insertWatermarkText(doc, "CONFIDENTIAL"); | |
doc.save(dataDir + "Document_out.doc"); | |
} | |
/** | |
* Inserts a watermark into a document. | |
* | |
* @param doc | |
* The input document. | |
* @param watermarkText | |
* Text of the watermark. | |
*/ | |
private static void insertWatermarkText(Document doc, String watermarkText) throws Exception { | |
// Create a watermark shape. This will be a WordArt shape. | |
// You are free to try other shape types as watermarks. | |
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT); | |
// Set up the text of the watermark. | |
watermark.getTextPath().setText(watermarkText); | |
watermark.getTextPath().setFontFamily("Arial"); | |
watermark.setWidth(500); | |
watermark.setHeight(100); | |
// Text will be directed from the bottom-left to the top-right corner. | |
watermark.setRotation(-40); | |
// Remove the following two lines if you need a solid black text. | |
watermark.getFill().setColor(Color.GRAY); // Try LightGray to get more Word-style watermark | |
watermark.setStrokeColor(Color.GRAY); // Try LightGray to get more Word-style watermark | |
// Place the watermark in the page center. | |
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE); | |
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE); | |
watermark.setWrapType(WrapType.NONE); | |
watermark.setVerticalAlignment(VerticalAlignment.CENTER); | |
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER); | |
// Create a new paragraph and append the watermark to this paragraph. | |
Paragraph watermarkPara = new Paragraph(doc); | |
watermarkPara.appendChild(watermark); | |
// Insert the watermark into all headers of each document section. | |
for (Section sect : doc.getSections()) { | |
// There could be up to three different headers in each section, since we want | |
// the watermark to appear on all pages, insert into all headers. | |
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY); | |
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST); | |
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN); | |
} | |
} | |
private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception { | |
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType); | |
if (header == null) { | |
// There is no header of the specified type in the current section, create it. | |
header = new HeaderFooter(sect.getDocument(), headerType); | |
sect.getHeadersFooters().add(header); | |
} | |
// Insert a clone of the watermark into the header. | |
header.appendChild(watermarkPara.deepClone(true)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Set name to be able to remove it afterwards | |
watermark.setName("WaterMark"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ExtractImagesToFiles.class); | |
Document doc = new Document(dataDir + "Image.SampleImages.doc"); | |
NodeCollection<Shape> shapes = (NodeCollection<Shape>) doc.getChildNodes(NodeType.SHAPE, true); | |
int imageIndex = 0; | |
for (Shape shape : shapes) { | |
if (shape.hasImage()) { | |
String imageFileName = String.format( | |
"Image.ExportImages.{0}_out_{1}", imageIndex, FileFormatUtil.imageTypeToExtension(shape.getImageData().getImageType())); | |
shape.getImageData().save(dataDir + imageFileName); | |
imageIndex++; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertBarcodeImage.class); | |
Document doc = new Document(dataDir + "Image.SampleImages.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// The number of pages the document should have. | |
int numPages = 4; | |
// The document starts with one section, insert the barcode into this existing section. | |
InsertBarcodeIntoFooter(builder, doc.getFirstSection(), 1, HeaderFooterType.FOOTER_PRIMARY); | |
InsertBarcodeIntoFooter(builder, doc.getFirstSection(), 1, HeaderFooterType.FOOTER_PRIMARY); | |
for (int i = 1; i < numPages; i++) { | |
// Clone the first section and add it into the end of the document. | |
Section cloneSection = (Section) doc.getFirstSection().deepClone(false); | |
// cloneSection.getPageSetup().getSectionStart() = SectionStart.NEW_PAGE; | |
doc.appendChild(cloneSection); | |
// Insert the barcode and other information into the footer of the section. | |
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType.FOOTER_PRIMARY); | |
} | |
dataDir = dataDir + "Document_out_.docx"; | |
// Save the document as a PDF to disk. You can also save this directly to a stream. | |
doc.save(dataDir); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(InsertBarcodeImage.class); | |
Document doc = new Document(dataDir + "Image.SampleImages.doc"); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// The number of pages the document should have. | |
int numPages = 4; | |
// The document starts with one section, insert the barcode into this existing section. | |
InsertBarcodeIntoFooter(builder, doc.getFirstSection(), 1, HeaderFooterType.FOOTER_PRIMARY); | |
InsertBarcodeIntoFooter(builder, doc.getFirstSection(), 1, HeaderFooterType.FOOTER_PRIMARY); | |
for (int i = 1; i < numPages; i++) { | |
// Clone the first section and add it into the end of the document. | |
Section cloneSection = (Section) doc.getFirstSection().deepClone(false); | |
// cloneSection.getPageSetup().getSectionStart() = SectionStart.NEW_PAGE; | |
doc.appendChild(cloneSection); | |
// Insert the barcode and other information into the footer of the section. | |
InsertBarcodeIntoFooter(builder, cloneSection, i, HeaderFooterType.FOOTER_PRIMARY); | |
} | |
dataDir = dataDir + "Document_out_.docx"; | |
// Save the document as a PDF to disk. You can also save this directly to a stream. | |
doc.save(dataDir); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static final String dataDir = Utils.getDataDir(RemoveWatermark.class); | |
public static void main(String[] args) throws Exception { | |
Document doc = new Document(dataDir + "RemoveWatermark.docx"); | |
removeWatermarkText(doc); | |
doc.save(dataDir + "RemoveWatermark_out.doc"); | |
} | |
private static void removeWatermarkText(Document doc) throws Exception | |
{ | |
for(HeaderFooter hf :(Iterable<HeaderFooter>) doc.getChildNodes(NodeType.HEADER_FOOTER, true)) | |
{ | |
for(Shape shape :(Iterable<Shape>) hf.getChildNodes(NodeType.SHAPE, true)) | |
{ | |
if(shape.getName().contains("WaterMark")) | |
shape.remove(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(AppendDocumentManually.class); | |
Document dstDoc = new Document(dataDir + "TestFile.Destination.doc"); | |
Document srcDoc = new Document(dataDir + "TestFile.Source.doc"); | |
for (Section srcSection : srcDoc.getSections()) { | |
Node dstSection = dstDoc.importNode(srcSection, true, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
dstDoc.appendChild(dstSection); | |
} | |
dstDoc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(BaseDocument.class); | |
Document dstDoc = new Document(); | |
Document srcDoc = new Document(dataDir + "TestFile.Source.doc"); | |
// The destination document is not actually empty which often causes a blank page to appear before the appended document | |
// This is due to the base document having an empty section and the new document being started on the next page. | |
// Remove all content from the destination document before appending. | |
dstDoc.removeAllChildren(); | |
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
dstDoc.save(dataDir + "output.doc"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(ConvertNumPageFields.class); | |
Document dstDoc = new Document(dataDir + "TestFile.Destination.doc"); | |
Document srcDoc = new Document(dataDir + "TestFile.Source.doc"); | |
// Restart the page numbering on the start of the source document. | |
srcDoc.getFirstSection().getPageSetup().setRestartPageNumbering(true); | |
srcDoc.getFirstSection().getPageSetup().setPageStartingNumber(1); | |
// Append the source document to the end of the destination document. | |
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING); | |
// After joining the documents the NUMPAGE fields will now display the total number of pages which | |
// is undesired behaviour. Call this method to fix them by replacing them with PAGEREF fields. | |
convertNumPageFieldsToPageRef(dstDoc); | |
// This needs to be called in order to update the new fields with page numbers. | |
dstDoc.updatePageLayout(); | |
dstDoc.save(dataDir + "output.doc"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment