Please find below the sample program and the doc sample file attached for your testing.
import com.aspose.words.;
import java.util.Date;
public class TestAsposeSave {
public static void main(String[] args) throws Throwable {
new TestAsposeSave().loadASPOSELicense();
new MergeDoc().start();
new ConvertPDF().start();
}
public static class MergeDoc extends Thread {
public void run(){
try {
Document completeDocument = getNewDocument();
Document asposeDocument = getDocument(“d:\Document1.doc”);
appendDoc(completeDocument, asposeDocument, true);
System.out.println(“merging doc 1 over”);
asposeDocument = getDocument(“d:\Document2.doc”);
appendDoc(completeDocument, asposeDocument, true);
System.out.println(“merging doc 2 over”);
asposeDocument = getDocument(“d:\Document3.doc”);
appendDoc(completeDocument, asposeDocument, true);
System.out.println(“merging doc 3 over”);
DocumentBuilder docBuilder = getDocBuilder(completeDocument);
insertReportIdentifier(docBuilder, “abcd”);
System.out.println(“TOC Update Started.”);
insertTOCAtBookMark(completeDocument, “TOC”, “Table of Contents”);
System.out.println(“TOC Update over”);
System.out.println(“Before saving Document :”+ new Date());
saveDocument(completeDocument, “d:\Document.doc”);
System.out.println(“After saving Document :”+ new Date());
} catch (Throwable throwable) {
throwable.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
public static class ConvertPDF extends Thread {
public void run(){
try {
InputStream blobInputStream = new FileInputStream(“d:\Test.doc”);
System.out.println(“Loading doc file for PDF conversion complete.”);
PdfSaveOptions saveOpt = new PdfSaveOptions();
//Diaply TOC in word as bookmarks up to level(section level) 9
saveOpt.setHeadingsOutlineLevels(9);
Document doc = new Document(blobInputStream);
blobInputStream.close();
System.out.println(“Conversion of PDF started.”);
ByteArrayOutputStream pdfOS = new ByteArrayOutputStream();
doc.save(pdfOS, saveOpt);
System.out.println(“Conversion of PDF Over.”);
FileOutputStream fos = new FileOutputStream(“d:\Test.PDF”);
fos.write(pdfOS.toByteArray());
fos.close();
pdfOS.close();
} catch (Throwable throwable) {
throwable.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
/
* Returns a reference to a blank document
*
* @return Document
* @throws Exception
*/
public static Document getNewDocument() throws Exception {
Document newDoc = new Document();
return newDoc;
}
/
* Gets a document for a given file path
*
* @param filePath
* @return Document
* @throws Exception
*/
public static Document getDocument(String filePath) throws Exception {
Document newDoc = new Document(filePath);
return newDoc;
}
/
* Converts Word Output Stream into Pdf Input Stream
*
* @param blobInputStream
* @return is ByteArrayInputStream
* @throws Exception
*/
public static InputStream processPdfStreamFromWordStream(InputStream blobInputStream) throws Exception{
PdfSaveOptions saveOpt = new PdfSaveOptions();
//Diaply TOC in word as bookmarks up to level(section level) 9
saveOpt.setHeadingsOutlineLevels(9);
Document doc = new Document(blobInputStream);
blobInputStream.close();
ByteArrayOutputStream pdfOS = new ByteArrayOutputStream();
doc.save(pdfOS, saveOpt);
blobInputStream = new ByteArrayInputStream(pdfOS.toByteArray());
pdfOS.close();
return blobInputStream;
}
/
* Saves the given section document
*
* @param document
* @param filePath
*/
public static void saveDocument(Document document, String filePath) throws Exception {
if (null != document) {
document.save(filePath);
}
}
/
* Inserts the given Report Identifier as footer in the given document
*
* @param builder
* @param reportIdentifier
* @return DocumentBuilder
* @throws Throwable
*/
public static DocumentBuilder insertReportIdentifier(DocumentBuilder builder, String reportIdentifier) throws Throwable {
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
builder.write(reportIdentifier);
return builder;
}
/
* Appends a document to another.
*
* @param dstDoc – Destination document
* @param srcDoc – Source document
* @param includeSection - if true the sections from srcDoc will be copied as it is, else only the internal nodes will be copied
* @throws Throwable
*/
public static void appendDoc(Document dstDoc, Document srcDoc,
boolean includeSection) throws Throwable {
// Loop through all sections in the source document.
// Section nodes are immediate children of the Document node so we can
// just enumerate the Document.
if (includeSection) {
for (Section srcSection : srcDoc.getSections()) {
Node dstNode = dstDoc.importNode(srcSection, true,
ImportFormatMode.USE_DESTINATION_STYLES);
dstDoc.appendChild(dstNode);
}
} else {
//find the last paragraph of the last section
Node node = dstDoc.getLastSection().getBody().getLastParagraph();
if (node == null) {
node = new Paragraph(srcDoc);
dstDoc.getLastSection().getBody().appendChild(node);
}
if ((node.getNodeType() != NodeType.PARAGRAPH)
& (node.getNodeType() != NodeType.TABLE)) {
throw new Exception(“Use appendDoc(dstDoc, srcDoc, true) instead of appendDoc(dstDoc, srcDoc, false)”);
}
insertDocumentAfterNode(node, dstDoc, srcDoc);
}
}
/
* Inserts content of the external document after the specified node.
* Section breaks and section formatting of the inserted document are
* ignored. Node in the destination document
* after which the content should be inserted. This node should be a block
* level node (paragraph or table).
*/
public static void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc,
Document srcDoc) throws Throwable {
// 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.”);
//We will be inserting into the parent of the destination paragraph.
CompositeNode dstStory = insertAfterNode.getParentNode();
//Remove empty paragraphs from the end of document
while (null != srcDoc.getLastSection().getBody().getLastParagraph() &&
!srcDoc.getLastSection().getBody().getLastParagraph().hasChildNodes()) {
srcDoc.getLastSection().getBody().getLastParagraph().remove();
}
NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
//Loop through all sections in the source document.
int sectCount = srcDoc.getSections().getCount();
for (int sectIndex = 0; sectIndex < sectCount; sectIndex++) {
Section srcSection = srcDoc.getSections().get(sectIndex);
//Loop through all block level nodes (paragraphs and tables) in the body of the section.
int nodeCount = srcSection.getBody().getChildNodes().getCount();
for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) {
Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
Node newNode = importer.importNode(srcNode, true);
dstStory.insertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
/
* Returns a reference to a builder for a given document
*
* @param document
* @return DocumentBuilder
* @throws Exception
*/
public static DocumentBuilder getDocBuilder(Document document) throws Exception {
DocumentBuilder newDocBuilder = new DocumentBuilder(document);
return newDocBuilder;
}
private void loadASPOSELicense() throws Exception {
System.out.println(this.getClass().getName());
InputStream asposeLicW = this.getClass().getClassLoader().
getResourceAsStream(“com/ags/resources/Aspose.Total.Java.lic”);
com.aspose.words.License licenseW = new com.aspose.words.License();
licenseW.setLicense(asposeLicW);
InputStream asposeLicC = this.getClass().getClassLoader().
getResourceAsStream(“com/ags/resources/Aspose.Total.Java.lic”);
com.aspose.cells.License licenseC = new com.aspose.cells.License();
licenseC.setLicense(asposeLicC);
}
/**
* This method inserts a TOC field at the bookmark
* If the bookmark name is null the TOC is added at the begining of the Document
* Standard TOC field codes are used \o “1-3” \h \z \u
*
* @param document Document
* @param bookMarkName - name of the bookmark
* @param heading – heading to put as the TOC heading
* @throws Throwable Throwable
*/
public static void insertTOCAtBookMark(Document document, String bookMarkName, String heading) throws Throwable {
if (document == null) return;
//create a builder
DocumentBuilder builder = new DocumentBuilder(document);
// delete the content of the bookmark before inserting.
Bookmark bm = document.getRange().getBookmarks().get(bookMarkName.trim());
if (bm != null) {
bm.setText("");
}
if (bookMarkName != null && bookMarkName.trim().length() > 0) {
//move to the bookmark
boolean moveResult = builder.moveToBookmark(bookMarkName);
//if bookmark not found move to begining of document
if (!moveResult) {
builder.moveToDocumentStart();
}
} else {
builder.moveToDocumentStart();
}
//if a heading is needed add it here
if (heading != null && heading.trim().length() > 0) {
builder.getFont().setBold(true);
builder.writeln(heading);
//reset the font
builder.setBold(false);
}
//now add the TOC
builder.insertTableOfContents("\o “1-3” \h \z \u");
document.getRange().updateFields();
}
}