Monday 9 September 2013

Converting Word Documents to PDF using SharePoint Server 2010 and Word Services

This article describes the following steps to show how to call the Word Automation Services to convert a document:

  1. Creating a SharePoint 2010 list definition application solution in Visual Studio 2010.
  2. Adding a reference to the Microsoft.Office.Word.Server assembly.
  3. Adding an event receiver.
  4. Adding the sample code to the solution.



Creating a SharePoint 2010 List Definition Application in Visual Studio 2010

This article uses a SharePoint 2010 list definition application for the sample code.

To create a SharePoint 2010 list definition application in Visual Studio 2010

  1. Start Microsoft Visual Studio 2010 as an administrator.
  2. From the File Menu, point to the Project menu and then click New.
  3. In the New Project dialog box select the Visual C# SharePoint 2010 template type in the Project Templates pane.
  4. Select List Definition in the Templates pane.
  5. Name the project and solution ConvertWordToPDF.
    Figure 1. Creating the Solution
    Creating the solution
  6. To create the solution, click OK.
  7. Select a site to use for debugging and deployment.
  8. Select the site to use for debugging and the trust level for the SharePoint solution.
    noteNote:
    Make sure to select the trust level Deploy as a farm solution. If you deploy as a sandboxed solution, it does not work because the solution uses the Microsoft.Office.Word.Server assembly. This assembly does not allow for calls from partially trusted callers.

    Figure 2. Selecting the trust level
    Creating the solution
  9. To finish creating the solution, click Finish.

Adding a Reference to the Microsoft Office Word Server Assembly

To use Word Automation Services, you must add a reference to the Microsoft.Office.Word.Server to the solution.

To add a reference to the Microsoft Office Word Server Assembly

  1. In Visual Studio, from the Project menu, select Add Reference.
  2. Locate the assembly. By using the Browse tab, locate the assembly. The Microsoft.Office.Word.Server assembly is located in the SharePoint 2010 ISAPI folder. This is usually located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. After the assembly is located, click OK to add the reference.
    Figure 3. Adding the Reference
    Adding the reference

Adding an Event Receiver

This article uses an event receiver that uses the Microsoft.Office.Word.Server assembly to create document conversion jobs and add them to the Word Automation Services conversion job queue.

To add an event receiver

  1. In Visual Studio, on the Project menu, click Add New Item.
  2. In the Add New Item dialog box, in the Project Templates pane, click the Visual C# SharePoint 2010 template.
  3. In the Templates pane, click Event Receiver.
  4. Name the event receiver ConvertWordToPDFEventReceiver and then click Add.
    Figure 4. Adding an Event Receiver
    Adding an event receiver
  5. The event receiver converts Word Documents after they are added to the List. Select the An item was added item from the list of events that can be handled.
    Figure 5. Choosing Event Receiver Settings
    Choosing even receiver settings
  6. Click Finish to add the event receiver to the project.

Adding the Sample Code to the Solution

Replace the contents of the ConvertWordToPDFEventReceiver.cs source file with the following code.
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

using Microsoft.Office.Word.Server.Conversions;

namespace ConvertWordToPDF.ConvertWordToPDFEventReceiver
{
  /// <summary>
  /// List Item Events
  /// </summary>
  public class ConvertWordToPDFEventReceiver : SPItemEventReceiver
  {
    /// <summary>
    /// An item was added.
    /// </summary>
    public override void ItemAdded(SPItemEventProperties properties)
    {
      base.ItemAdded(properties);

      // Verify the document added is a Word document
      // before starting the conversion.
      if (properties.ListItem.Name.Contains(".docx") 
        || properties.ListItem.Name.Contains(".doc"))
      {
        //Variables used by the sample code.
        ConversionJobSettings jobSettings;
        ConversionJob pdfConversion;
        string wordFile;
        string pdfFile;

        // Initialize the conversion settings.
        jobSettings = new ConversionJobSettings();
        jobSettings.OutputFormat = SaveFormat.PDF;

        // Create the conversion job using the settings.
        pdfConversion = 
          new ConversionJob("Word Automation Services", jobSettings);

        // Set the credentials to use when running the conversion job.
        pdfConversion.UserToken = properties.Web.CurrentUser.UserToken;

        // Set the file names to use for the source Word document
        // and the destination PDF document.
        wordFile = properties.WebUrl + "/" + properties.ListItem.Url;
        if (properties.ListItem.Name.Contains(".docx"))
        {
          pdfFile = wordFile.Replace(".docx", ".pdf");
        }
        else
        {
          pdfFile = wordFile.Replace(".doc", ".pdf");
        }

        // Add the file conversion to the conversion job.
        pdfConversion.AddFile(wordFile, pdfFile);

        // Add the conversion job to the Word Automation Services 
        // conversion job queue. The conversion does not occur
        // immediately but is processed during the next run of
        // the document conversion job.
        pdfConversion.Start();

      }
    }
  }
}

Get Credentials from Secure Store AppllicationID - Code Snippet




Private enum SecureStoreCredentials { Username, Password, LoginUrl}

Private void SomeMethod()
{

Dictionary<SecureStoreCredentials, string> credentialMapDocuSign = helper_GetSecureStoreCredentials("ApplicationId");

string value = string.Empty;
string username = string.Empty;
string password = string.Empty;
string url = string.Empty;

if (credentialMapDocuSign.TryGetValue(SecureStoreCredentials.Username, out value))
{
        username = value;
}
if (credentialMapDocuSign.TryGetValue(SecureStoreCredentials.Password, out value))
{
        password = value;
}           
if (credentialMapDocuSign.TryGetValue(SecureStoreCredentials.LoginUrl, out value))
{
       url = value;
}

}


private Dictionary<SecureStoreCredentials, string> helper_GetSecureStoreCredentials(string applicationid)
{
try

{
Dictionary<SecureStoreCredentials, string> credentialMap = new Dictionary<SecureStoreCredentials, string>();
//get handle to secure store
SecureStoreProvider prov = new SecureStoreProvider();
//get the service context this code is running under
SPServiceContext context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default); //SPServiceContext.GetContext(web.Site);
prov.Context = context;
//get the credentials from the secure store
SecureStoreCredentialCollection cc = prov.GetCredentials(applicationid);

foreach (SecureStoreCredential c in cc)
{
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(c.Credential);

string sDecrypString = System.Runtime.InteropServices.Marshal.PtrToStringUni(ptr);

switch (c.CredentialType)
{
case SecureStoreCredentialType.WindowsUserName:

credentialMap.Add(
SecureStoreCredentials.Username, sDecrypString);

break;

case SecureStoreCredentialType.WindowsPassword:

credentialMap.Add(
SecureStoreCredentials.Password, sDecrypString);

break;

case SecureStoreCredentialType.Generic:

credentialMap.Add(
SecureStoreCredentials.LoginUrl, sDecrypString);

break; 


}

return credentialMap;

}
catch (Exception ex)
{
throw ex;

}

}