Code Snippets

Merging Multiple Word Documents using Alfresco and Docx4j

This sample code shows the way to merge multiple word documents. For more information about Docx4j and this code, refer to this blog post.

private WordprocessingMLPackage mergeDocs(NodeRef parentFolder,List<String> fileList) throws Docx4JException, URISyntaxException 

WordprocessingMLPackage docDest=null;
NodeRef ref=nodeService.getChildByName(productFolder, ContentModel.ASSOC_CONTAINS, fileList.get(0));
if(ref==null) return null;
ContentReader reader=contentService.getReader(ref, ContentModel.PROP_CONTENT);
if(reader==null) return null;
docDest = WordprocessingMLPackage.load(reader.getContentInputStream());
if (fileList.size() == 1) return docDest;
else 
{

for(int i=1;i<fileList.size();i++){
NodeRef ref2=nodeService.getChildByName(productFolder, ContentModel.ASSOC_CONTAINS, fileList.get(i));
ContentReader reader2=contentService.getReader(ref2, ContentModel.PROP_CONTENT);
WordprocessingMLPackage docSource = WordprocessingMLPackage.load(reader2.getContentInputStream());
List<Object> object = docSource.getMainDocumentPart().getContent();
for (Object o : object)docDest.getMainDocumentPart().getContent().add(o);
}

}
return docDest;
}

 

The following code can save word documents and convert it into PDF documents:

 

private NodeRef saveWordToPDF(NodeRef parentFolder,String fileName,WordprocessingMLPackage wordMLPackage)
{

NodeRef ref=fileFolderService.create(parentFolder, fileName+".pdf", ContentModel.TYPE_CONTENT).getNodeRef();
ContentWriter cw = contentService.getWriter(ref, ContentModel.PROP_CONTENT, true);
cw.setMimetype(MimetypeMap.MIMETYPE_WORD);
try {

wordMLPackage.save(cw.getContentOutputStream());
return convertWordToPDF (ref);

} catch (ContentIOException e) {

e.printStackTrace();

} catch (Docx4JException e) {

e.printStackTrace();


return null;

}

private NodeRef convertWordToPDF(NodeRef nodeRef)

{

if (contentService.getReader(nodeRef, ContentModel.PROP_CONTENT) == null)return null;

try {

ContentReader cr = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
ContentWriter cw = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
cw.setMimetype(MimetypeMap.MIMETYPE_PDF);
if (!cr.getMimetype().equals(MimetypeMap.MIMETYPE_PDF)){
ContentTransformer ct = contentService.getTransformer(cr.getMimetype(), MimetypeMap.MIMETYPE_PDF);
if(ct!=null){

ct.transform(cr, cw);
return nodeRef;

}

}

catch (FileExistsException e1)e1.printStackTrace();
catch(Exception e) e.printStackTrace();
return null;

}

 

Resource Tags: