AnsweredAssumed Answered

transformDocument() in Java, not in Javascript?

Question asked by talija83 on Sep 9, 2010
Latest reply on Sep 14, 2010 by talija83
Is there a way to easily transform content from one mimetype to another, using Java?  :?:  (For example, HTML file to Word document.)

I know that it can be done easily using transformDocument() function in Javascript, but I'm interested in how it's done in Java. In Alfresco 3.3g, it seems that custom actions done in JS, triggered from web-client, have some problem with permissions, therefore this script needs to be translated to Java. I've tried using ContentWriter, ContentReader and ContentTransformer, but the document I get in Word cannot be opened if it contains a photo - it says it's too big to be opened.  :!:

Basically, what I'm trying to do is 'translate' this:

var word_doc = html_doc.transformDocument("application/msword");

into something like this:

 private void transformDocument(NodeRef sourceNodeRef, NodeRef targetNodeRef, String sourceMimetype, String targetMimetype)
    {
      ContentService contentService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService();      
      ContentReader reader = contentService.getReader(sourceNodeRef, ContentModel.PROP_CONTENT);
      
      // If there is a reader…
      if (reader.exists() && reader != null)
      {
         // …we create the transformer…
         ContentTransformer transformer = contentService.getTransformer(sourceMimetype, targetMimetype);
         
                        // …and if it is valid…
         if (transformer != null)
         {
            ContentWriter writer = contentService.getWriter(targetNodeRef, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(targetMimetype);
            
            try
            {
                                        // …we transform the content.
               transformer.transform(reader, writer);

               reader = writer.getReader();
               
               if (!reader.exists())
                  throw new ContentIOException("The transformation did not write any content, yet: \n" + " transformer: " + transformer + "\n" + " temp writer: " + writer);
            }
            
            catch (ContentIOException e) {
               logger.debug(e.getMessage());
            }
         }
         else
            logger.debug("Transformer wasn't created successfully…");
      }
      else
         logger.debug("Reader doesn't exist…");
    }

The call in Java would now be:

transformDocument(html_doc, word_doc, MimetypeMap.MIMETYPE_HTML, MimetypeMap.MIMETYPE_WORD);

Does anyone have an idea how could this be done more easily? And without any strange messages from MS Office, when reading the converted document later?

Thanks in advance.  :)

Outcomes