Tuesday, August 2, 2011

Read Alfresco node to byte array in Javascript

When I created response document for all appeals I want replace signature in document too. But I must save signature images in repository because I want nobody can see signatures. Then I write small class and read image node from repository to byte array then send it to jasper report as Base64 encoded.
But how can u read image from byte array and show it in your document? If u are interested about this then u must read my other post :)

My Java code for Javascript object in alfresco:
package az.gov.supremecourt.repo.jscript;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.processor.BaseProcessorExtension;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import java.io.BufferedInputStream;
import java.io.InputStream;

 * @author Vasif Mustafayev
public final class ScUtils extends BaseProcessorExtension {
 private static Log logger = LogFactory.getLog(ScUtils.class );
 /** Content Service */
 private ContentService contentService;

  * Make ContentService aviable from spring context file 
  * <property name="contentService" ref="ContentService"/>
  * @method setContentService
  * @param contentService
 public void setContentService(ContentService contentService) {
  this.contentService = contentService;

  * Get Node Content as Byte Array then encode to Base64
  * @method getNodeByteArrayInBase64
  * @param nodeRef node reference which u want get bytes
  * @return nodeInBase64 string for node in Base64
 public String getNodeByteArrayInBase64(NodeRef nodeRef) {
  String nodeInBase64 = "";
  ContentReader contentReader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);  
  InputStream nodeIS = new BufferedInputStream(contentReader.getContentInputStream(), 4096);  
  try {
   byte[] nodeBytes = IOUtils.toByteArray(nodeIS);
   nodeInBase64 = new String(Base64.encode(nodeBytes));
  } catch (Exception e) {
   if ( logger.isErrorEnabled() )
                logger.error("ScUtils class : getNodeByteArrayInBase64 method : Can't get content as byte Array");
  return nodeInBase64;


And registration for spring:
<!-- Utils for Supreme Court -->
 <bean id="scUtilsScript" parent="baseJavaScriptExtension" class="az.gov.supremecourt.repo.jscript.ScUtils">
  <property name="contentService" ref="ContentService" />
  <property name="extensionName" value="scutils" />

Use it simple:
var signatureNode = companyhome.childByNamePath("signatures/"+person.properties["cm:userName"]+".jpg");
var nodeContentAsBase64 = scutils.getNodeByteArrayInBase64(signatureNode.nodeRef);

1 comment: