Subscribe to News feed

Using the PDF Converter for SharePoint from your own code

Posted at: 3:17 PM on 14 October 2009 by Muhimbi

PDFConverterBox When developing a product such as the PDF Converter for SharePoint you start with a fair idea of how customers want to use it and what they may want to use it for. It is not until a product has been selling for a while before you grasp what the market really wants.

One of the first changes we made to the product was making it workflow enabled to allow it to be used from products such as SharePoint Designer and the ever popular Nintex Workflow. This basically cut the number of helpdesk tickets by 75%. Recently, however, we have been getting an increasing number of requests from people who want to use the product from their own source code. Although we never imagined anyone ever wanting to do this, we have decided to document (part of) the public interface to our product.

This post describes the public interface of the PDF Converter and provides a simple code sample illustrating how it can be invoked from your own custom .net code. Please consider reading the following related blog postings as well as they provide an alternative approach for using the PDF Converter from your own code:

The external interface is defined in the following class: Muhimbi.SharePoint.DocumentConverter.PDF.DocumentConverter.

The two main methods for converting documents are:

  • DataTable ConvertToPdf(SPFile sourceFile, SPFolder destinationFolder, string destinationFileName, bool copyMetadata)
  • DataTable ConvertToPdf(SPFolder sourceFolder, SPFolder destinationFolder, bool includeSubFolders, bool copyMetadata)

The interface largely describes itself. The first method can be used for converting a single file whereas the second method is used to convert entire folders.

Each method returns its results in a DataTable with a single row for each converted file. Each row’s fields can be accessed by name as defined in the following public constants on the DocumentConverter class.

  • COLUMN_FILENAME = "Filename";
  • COLUMN_FILEPATH = "Path";
  • COLUMN_RESULT = "Result";
  • COLUMN_MESSAGE = "Message";
  • COLUMN_CONVERTEDITEMID = "ConvertedItemID";

As always, the best way to show how it all works is by example. The code at the end of this article generates the following screen  

PDFConverterSample

  In order to use the code sample below, follow these steps:

  1. Download and install the Muhimbi PDF Converter for SharePoint.
     
  2. Copy the code below into a file named sample.aspx or download it here.
     
  3. Place the file in 12\TEMPLATE\LAYOUTS\Muhimbi.PDFConverter (or anywhere else you want).
     
  4. Access it at http://YOUR_SERVER/SOME_SITE/_layouts/Muhimbi.PDFConverter/sample.aspx.
     
  5. Enter valid values in the text boxes and click ‘Convert’.

 

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="Muhimbi.SharePoint.DocumentConverter.PDF, Version=1.0.1.1, 
                   Culture=neutral, PublicKeyToken=c9db4759c9eaad12" %>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"%>
<%@ Import Namespace="Microsoft.SharePoint.Administration" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="Muhimbi.SharePoint.DocumentConverter.PDF" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" 
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, 
                       PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" 
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, 
                       PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormSection" 
             src="/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" 
             src="/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" 
             src="/_controltemplates/ButtonSection.ascx" %>
<%@ Register Tagprefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" 
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, 
                       PublicKeyToken=71e9bce111e9429c" %>
 
<script runat="server" language="c#">
    // ** The names of the various columns in the result set.
    const string COLUMN_FILENAME = "Filename";
    const string COLUMN_FILEPATH = "Path";
    const string COLUMN_RESULT = "Result";
    const string COLUMN_MESSAGE = "Message";
    const string COLUMN_CONVERTEDITEMID = "ConvertedItemID";
 
    protected void btnOK_OnClick(object sender, EventArgs e)
    {
        try
        {
            textBoxDebug.Text = "";
 
            WriteDebug("==================================");
            WriteDebug("Muhimbi PDF Converter Code Sample.");
            WriteDebug("==================================");
            WriteDebug("");
 
            DataTable resultsTable = null;
            bool includeMetaData = true;
            string sourceFilePath = txtSourceFileName.Text;
            string destinationFolderPath = txtDestinationFilePath.Text;
            string destinationFileName = txtDestinationFileName.Text;
 
            WriteDebug("sourceFilePath: " + sourceFilePath);
            WriteDebug("destinationFolderPath: " + destinationFolderPath);
            WriteDebug("destinationFileName: " + destinationFileName);
            WriteDebug("includeMetaData: " + includeMetaData);
 
            using (SPWeb web = SPContext.Current.Web)
            {
                SPFile sourceFile = web.GetFile(sourceFilePath);
                SPFolder destinationFolder = web.GetFolder(destinationFolderPath);
                DocumentConverter documentConverter = new DocumentConverter();
                resultsTable = documentConverter.ConvertToPdf(sourceFile, destinationFolder, 
                                                      destinationFileName, includeMetaData);
            }
 
            WriteDebug("\r\nConversion Results:");
            foreach(DataRow row in resultsTable.Rows)
            {
                // ** Possible values: Success=0, Error=1, Skipped=2
                string resultCode = row[COLUMN_RESULT].ToString();
                string result = String.Format("- {0} - {1} - {2} - {3}",
                                              row[COLUMN_FILENAME].ToString(), 
                                              row[COLUMN_FILEPATH].ToString(), 
                                              resultCode, row[COLUMN_MESSAGE].ToString());
                WriteDebug(result);
            }
 
        }
        catch(Exception ex)
        {
            WriteDebug("An error occured while converting the file.\r\n" + ex.Message + 
                        "\r\n" + ex.ToString());
        }
    }
 
    private void WriteDebug(string s)
    {
        textBoxDebug.Text += s + "\r\n";
    }
</script>
 
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">
</asp:Content>
 
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
    Muhimbi PDF Converter Code Sample.
</asp:Content>
 
<asp:Content ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">
    Muhimbi PDF Converter Code Sample.
</asp:Content>
 
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
Use this sample page to convert a source file in any of the supported formats to a PDF file.
Both absolute as well as relative URLs are supported. For the latest news and code samples
please visit <a href="http://www.muhimbi.com/blog/">Muhimbi's Blog</a>.<br /><br />
Full source code is included and can be viewed on the server in 
"\12\TEMPLATE\LAYOUTS\Muhimbi.PDFConverter\Sample.aspx".
<br /><br />
</asp:Content>
 
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
 
    <!-- Area to display error message -->
    <table id="filterTable" class="ms-propertysheet" border="0" width="100%" cellspacing="5" 
           cellpadding="0" style="table-layout:fixed;">
        <colgroup><col width="*" /><col width="375" /></colgroup>
 
        <tr>
            <td class="ms-vb">Please enter source file name / path:</td>
            <td>
                <wssawc:InputFormTextBox
                class="ms-input"
                ID="txtSourceFileName"
                Columns="35"
                Runat="server"
                MaxLength="124"
                size="10" 
                style="width:100%"
                Text="Shared Documents/somefile.doc"/>
            </td>
        </tr>
 
        <tr>
            <td class="ms-vb">Please enter destination path:</td>
            <td>
                <wssawc:InputFormTextBox
                class="ms-input"
                ID="txtDestinationFilePath"
                Columns="35"
                Runat="server"
                MaxLength="124"
                size="10" 
                style="width:100%"
                Text="Shared Documents"/>
            </td>
        </tr>
 
        <tr>
            <td class="ms-vb">Please enter destination file name:</td>
            <td>
                <wssawc:InputFormTextBox
                class="ms-input"
                ID="txtDestinationFileName"
                Columns="35"
                Runat="server"
                MaxLength="124"
                size="10" 
                style="width:100%"
                Text="somefile.pdf"/>
            </td>
        </tr>
 
        <tr>
            <td colspan="2">
                <asp:TextBox id="textBoxDebug" style="width:100%" runat="server" Rows="12" 
                             TextMode="MultiLine" />
            </td>
        </tr>
 
        <!-- Submit Button -->
        <wssuc:ButtonSection runat="server" TopButtons="true" BottomSpacing="11" 
                             ShowSectionLine="false">
            <Template_Buttons>
                <asp:Button UseSubmitBehavior="false" runat="server" 
                            class="ms-ButtonHeightWidth" style="width:100px" 
                            OnClick="btnOK_OnClick" Text="Convert" id="btnOK"/>
            </Template_Buttons>
        </wssuc:ButtonSection>
 
    </table>
 
</asp:Content>

Labels: ,

7 Comments:

  • This saves loads of time over the way I was doing pdf's in sharepoint - cheers!

    By Anonymous sharepointCode.co.uk, At 23 September, 2010 10:37  

  • You may want to have a look at the Web Services or workflow interface as well. It is much more flexible, see http://blog.muhimbi.com/2009/12/converting-office-files-to-pdf-format.html

    By Blogger Muhimbi, At 23 September, 2010 10:39  

  • Where is the documentConverter object is getting closed ?

    is there a way to close the object as my memory usage is going up when i used the above code ?

    By Anonymous Anonymous, At 09 October, 2010 04:14  

  • There is no need to close it, all resources are being cleaned up internally.

    You may want to profile your code to see exactly what leaks. Note that the actual conversions are being carried out inside 'Muhimbi.DocumentConverter.Service.exe' and to the best of our knowledge that is absolutely rock solid.

    You may want to have a look at carrying out conversions using the web services interface. For an example see http://blog.muhimbi.com/2009/12/converting-office-files-to-pdf-format.html

    By Blogger Muhimbi, At 11 October, 2010 07:54  

  • Which .asmx do I need to call with the Nintex 'call web service'? I tried 'Web Url/_vti_bin/documentconverterservice.asmx' but this errored.

    By Anonymous Anonymous, At 23 November, 2010 14:21  

  • Hi Anonymous,

    For a web services example see http://blog.muhimbi.com/2009/12/converting-office-files-to-pdf-format.html. This document includes the WS URL as well.

    You can also get the WS URL from the PDF Converter's Central Administration screen at http://your_ca_server/_admin/Muhimbi.PDFConverter/WebAppDocumentConverterSettings.aspx

    Basically the WS URL is http://localhost:41734/Muhimbi.DocumentConverter.WebService/ and the WSDL is located at http://localhost:41734/Muhimbi.DocumentConverter.WebService/?wsdl

    Please note that older versions of the Nintex 'call web service' component have difficulties with WCF based web services (which the PDF Converter is based on). They may have fixed this in newer versions of Nintex though.

    By Blogger Muhimbi, At 23 November, 2010 14:30  

  • You shouldn't be disposing the SPContext.Current.Web

    By Anonymous Anonymous, At 04 September, 2012 15:11  

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

Need support from experts?

Access our Forum

Download Free Trials