Sunday, January 5, 2014

Extract PDF file from K2 PDF SmartObject

In K2 workflow, we can create PDF file using PDF SmartObject, located in System node:

image

PDF Converter is a built-in SmartObject in K2 to create PDF and save it in PDF File SmartOject. The PDF is saved as BLOB. Actually it is a column contains XML and in the XML contains PDF as binary content.

The problem is, I have to extract the PDF and copy it to the file server using Windows File Sharing. K2 does not have built-in feature to extract PDF to physical file, thus I have to create it.

The following code utilizes SmartObject Client API to communicate with PDF File SmartObject in K2 Blackpearl server.

   1:  public void ExtractPDFWithSmartObject(int snapshotID, string fileName)
   2:  {
   3:      var smartObjServer = new SmartObjectClientServer();
   4:   
   5:      using (var connection = smartObjServer.CreateConnection())
   6:      {
   7:          connection.Open(k2WorkflowServer);
   8:          //smartObjServer.Connection.Open();
   9:   
  10:          var pdfSmartObj = smartObjServer.GetSmartObject("PDFFile");
  11:          pdfSmartObj.MethodToExecute = "Load";
  12:          pdfSmartObj.Properties["ID"].Value = snapshotID.ToString();
  13:   
  14:          var result = smartObjServer.ExecuteScalar(pdfSmartObj);
  15:          var file = (SmartFileProperty)pdfSmartObj.Properties["PDF"];
  16:          byte[] data = Convert.FromBase64String(file.Content);
  17:          File.WriteAllBytes(fileName, data);
  18:      }
  19:  }



Add reference to SourceCode.HostClientAPI.dll and SourceCode.SmartObjects.Client.dll


Parameter snapshotID is an ID created by Create* method of PDF Converter and parameter fileName is a physical file name to be created in file system.


In line 7, we have to create string variable named k2WorkflowServer, this variable will be populated as connection string to K2 Blackpearl server.


The complete code can be downloaded from here, it is a .NET DLL file and can be referenced from K2 workflow.


 


Call this DLL from K2 Workflow



To use this DLL (PDFHelper.dll), open your K2 workflow (.kprx) using K2 Designer for Visual Studio, add Code Reference Event and add reference to PDFHelper.dll


In Code Reference Event, add call constructor and pass the K2 Connection String as parameter.
image


then call instance method ExtractPDFWithSmartObject and pass snapshot ID and filename as parametersOpen-mouthed smile:


image




Do I have to use Visual Studio to use this DLL in my K2 workflow?


If I use K2 Studio to add reference to this workflow, strangely I cannot call constructor and call instance method, it seems K2 Studio cannot load PDFHelper.dll. But if I use Visual Studio, I can add reference, call constructor, and call instance method smoothly.

No comments:

Post a Comment