Blog Post

Using the PDF Converter for SharePoint from Your Own Code

Clavin Fernandes
Illustration: Using the PDF Converter for SharePoint from Your Own Code

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 https://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="/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>
Author
Clavin Fernandes Developer Relations and Support Services

Clavin is a Microsoft Business Applications MVP who supports 1,000+ high-level enterprise customers with challenges related to PDF conversion in combination with SharePoint on-premises Office 365, Azure, Nintex, K2, and Power Platform mostly no-code solutions.

Explore related topics

Share post
Free trial Ready to get started?
Free trial