PDF Tech

Create an Automated Office Conversion Service Using Foxit PDF SDK

by PDF SDK | April 11, 2023
Create an Automated Office Conversion Service Using Foxit PDF SDK

With over 1.2 billion users worldwide, Microsoft Office is the most popular suite of business and productivity applications. However, it isn’t the only one; there are several open source alternatives such as Apache OpenOffice as well as ad-supported free options such as WPS Office.

A wide variety of document file types can be produced using these solutions, but they often don’t come with native PDF support. In some cases, you’re required to install add-ins or print your documents as PDFs. While recent iterations of Microsoft Office allow you to save files as PDFs, what do you do when you receive a DOCX or XLS file and you don’t want to go through the process of opening an entire program or application just to convert it to a PDF? You can accept the file as it is, but documents left in Microsoft Office formats are often seen as unprofessional and many won’t consider these files as official until they’re in PDF format.

The following guide will show you how to build an automated solution that converts Office files into PDFs using Foxit’s PDF SDK.

Why Does PDF Office Conversion Matter?

PDF is one of the most commonly used document file types in business today. PDFs are easy to secure, reliable, version- and platform-independent, and versatile. Most modern browsers have PDF support in the form of a built-in viewer. Thus, whoever you send a PDF document to probably has a way to open it and view its contents.

The contents of PDFs remain the same regardless of what operating system or reader you use to open them. Microsoft Office files don’t always render consistently when they’re opened in third-party applications. For instance, though Google Docs has made it easier for people to share and edit documents created using Office, it still doesn’t always render documents consistently. It particularly struggles with visual elements such as graphs and charts.

You can always trust PDFs to be displayed the way you intend them to be viewed, regardless of the PDF reader version, OS, or device. There are ways to automate Office file to PDF conversion without directly running an application.

Creating Your Own PDF Office Conversion Application

In this section of the guide, you’ll learn how to create your very own PDF conversion solution based on ASP.NET. You’ll create a GUI-based project with a single button. The project uses Foxit’s Web SDK, and while it’s quite a simple project, experience with C# and Visual Studio is highly recommended.

You can find all the code used in this article in this GitHub repo.

Project Prerequisites

You’ll need the following:

* Microsoft Visual Studio: It’s recommended that you use the latest version of Visual Studio (2022 at the time of writing this guide), but any version of VS from the last decade should be adequate. The Community edition is free for students and individuals.

* ASP.NET and web development tools: When installing Microsoft Visual Studio, ensure that you install all ASP.NET and web development workloads as well, though you can also add these components later if you don’t install them initially.

ASP.NET and web developmen

* Foxit .NET PDF SDK: You can use Visual Studio’s built-in NuGet package manager to download the latest version of the Foxit .NET PDF SDK. It will also add the necessary project references.

1. Initialize Your Project

The first thing you must do is create and initialize your project, which you can do with the Visual Studio wizard.

Create a new project using the ASP.NET Core Web App template, which you can use the search bar to find. Alternatively, you can set the language option to C#, the platform option to Windows, and the project type to Web. Once that’s done, the ASP.NET Core Web App project template should appear as the first option in the list:

ASP.NET Core Web App

Name the project something apt, such as OfficePDFConverter. Remember to use PascalCase when naming your project. Then, make sure the Place solution and project in the same directory option is selected and click the Next button:

Name the project

Select .NET Core 3.1 as the framework, leave everything else as is, and click the Create button:

Select .NET Core 3.1 as the framework

2. Add Libraries and References to Your Project

Launch the NuGet Package Manager by going to Tools > NuGet Package Manager > Manage NuGet Packages for Solution:

Manage NuGet Packages for Solution

Click Browse and make sure that the Package source is set to All. Search for Foxit.SDK.Dotnet and click it. Then, make sure your project is selected in the version panel and choose the latest version of the SDK. Finally, click the Install button:

Click Browse and make sure that the Package source is set to All

Visual Studio will ask for confirmation. Click the OK button.

You can also manually download the Foxit PDF SDK (.NET Core library) and add the reference manually. If you elect to do this, the first thing you must do is unzip the SDK archive after it’s done downloading.

download the Foxit PDF SDK

Next, open Visual Studios, click the Projects menu item and select Add Project Reference/Add Reference.

Add Reference

This will open the Reference Manager window. Make sure the Browse tab is selected and click the Browse button.

browse

Navigate to where you unpacked the SDK. Open the lib folder, select the folder that corresponds to your system’s architecture (x86/x64_vc15). Select the fsdk.dll file and click the Add button.

fsdk.dll

Make sure the fsdk.dll is selected and then click the OK button. 

3. Create Your GUI

Visual Studio will create a template web application. Instead of creating new pages or classes, you’ll edit and repurpose the given code. In the Solution Explorer panel that’s on the right side of the IDE by default, expand the Pages folder under your project and double-click the Index.cshtml file:

PAGE

Remove the existing <div> HTML component from Index.cshtml. The code should look like this:

html
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

Add a new <div> HTML component with container as its class type attribute:

html
<div class="container">

Next, add a new form component to the <div> section and assign a post method as its only attribute:

html
<form method="post">

In the container section, add a heading to your page to make your web app’s usage instructions clear. For example:

html
<H3>Enter directory for conversion:</H3>

Build your text input field to specify the directory that houses your source files for conversion. First, add a label to the container section that marks the text field:

html
<label>Directory:</label>

Next, create the text field by declaring a text input type and assigning directory to both its id and name attributes. The line of code should look like this:

html
<input type= 'text' id="directory" name="directory" >

You’ll need to create a submit button that will be used to trigger the conversion process. Since it would look better underneath the text field as opposed to next to it, first add two line breaks with <br><br>. Then, declare a submit input type with Convert as its attribute:

html
<input type="submit" value="Convert">

Your Index.cshtml file should now look something like this:

asp
@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="container">
    <form method="post">
        <H3>Enter directory for conversion:</H3>
        <label>Directory:</label>
        <input type= 'text' id="directory" name="directory" ><br><br>
        <input type="submit" value="Convert">    
    </form>
</div>

Once you’re done building your client using the above code, you’ll need to create the backend logic for it. Your backend code will heavily rely on the Foxit PDF SDK’s libraries, which must be initialized using a serial number and license key combination.

4. Install and Initialize the Foxit Library

The Foxit library must be initialized in the Index model CS file. While you have the Index.cshtml file selected in your editor, press the F7 key. This is the easiest way to view the model code.

After you open the model file, import the necessary Foxit libraries and namespaces. The two you’re mainly concerned with are the foxit and foxit.common libraries. Import both into the Index.cshtml.cs file:

csharp
using foxit;
using foxit.common;

Next, add two new class strings to the IndexModel class. These strings will be used to hold the Foxit serial number and license key. Accordingly, one string must be named sn and the other key. Your declaration for both strings should look similar to this:

csharp
static string sn = "";
static string key = "";

The above declarations are incomplete. You should assign the serial number and license key to them, respectively. Foxit includes these values with their SDK packages as text files, and you’ll need to use your operating system’s file explorer or manager to access them. In the Solution Explorer panel on the right side of the IDE window, expand the Packages folder under the Dependencies section, then right-click the Foxit.SDK.Dotnet folder and select the Open Folder in File Explorer item from the context menu:

Open Folder in File Explorer

Now that you have the SDK’s source folder opened, look for the file labeled gsdk_sn.txt. Open the file, copy the contents after the SN= characters, and assign them to the sn string variable you created earlier:

SN

Your serial number string should look similar to the following:

csharp
static string sn = "eHZELU0twWL0OuhsAlDNXxxjJvqGKETmxG6Y4zlgGnPdI8dBNRKv7w==";

Next, close the gsdk_sn.txt file, then find the gsdk_key.txt file from the same directory and open it. As you did with the serial number, copy the key value after the Sign= characters in the file and assign it to the key string variable you created for the IndexModel class:

The declaration code for the string should look similar to the following:

csharp
static string key = "8f3gFcGNtR8N+Td6AF43CmmH5xt1p8I6Ezse924Y/yIH9u/kcPAE40puFED3oBj7KMrlzYnceCvGoVdvKfiK3Z60JuWDq3fX5hWwd+Dv2B7wUXQpqvIPfarxpgSou3T1hJGpvX1Mp1TZEJ2VcFAckgTqtH4Ru+8Ek8f/YWbv3rPXMsr9Phw9DvYOf4SL9OI1Vm23IiDLLpTnIeMc/MlhILiyQxIT1BYDWX9O6R2IpRaV8cTNRqk/8Qv4nGZ16YJKddfZIrRcPhs0Gbg91cTFDWJsjUxG93xBhoCWhTN76tNeOLNxMVrAuoUS8T5biYio0t06jEm9YjHF/lqCyTRQrBRuWsYE77BlCqoSgjrKsDvDgomn80mT0sKyhorVa0STK0E4zinfQLP/cQmpcbL4P98UnXsRPbNekRNrYId9+Y9GZl/j7HO1f1UJVbjgrsCiOO67aIuPyW7iIphydtDj+92Ky99h9seAA5b9E2ZxR3bV1E4eFBREU36I3DlyhuKtlS6/CsiEpyTYFCYt8TS/77vPkGlEiCm/VpJ/DW7Tlifs4/LYzd02b8eIgYtw4xb4kTpSrp3lMNc8Zc4uq4e3RO4L7RLdNXe2Zpf0QZsBLI9zlW7DMLNy7+vHMd8u6Zfal27Q2MaKC/W+1g4SgN91Zh3GlcMxSfXo2njcNg3nxrck3bJ6lFvkr605K1r1Gb2AaccWr+urqh7X/h1fGj0IokWCJuZYzXDNEIVjYmW8k1AAroC0mD0aPZe4mr6C22rfM/STCBGuSIuglm8hDiPwchqpTC5/MM53kU7yg7IZ1IU3SQTmMBGp2m3p1PqKUUw+30V1+zHKL0KnsNYP/zDZ51qAOfyKJblZvBseKzNwioSUk/HMo3hyqtsP5C/7tJkmjGTtH3y2K9OOPhu4FIa/jdMWsFJ/IMDza63XiXUP5HGu3zZJb58NQ3FqZR+p6Wmgeoyo9OYc0Wt0EUkyOpuDD17PxSSc67baC3y88TjI9JM4Q5+FhE+cm+CMlX6/rZ8KDrz3Xeq78zMoLBA9vOiXmQLqYz7QXEip1LBPDp7xsYeet9nTe9WYb76ukYCSRAJZIqw5NMzWDHsfyknH2C1jq+VgzlVwoCifmfejOsZHtLnl/3u15FZ/ORSsDlCrwTFugmnJJXmDBCsRGlZBbAaSrsd7orbjUNoaOsQQ+xJdcl6ey6IC7uJxo6RtkAsQljFGYQHEMwu+B2xicd99QExRQbcv6Owzl34rvN5+BpXa16ZJWDWgptD7EqP0IjKEDq1RdxFBmErAfYFtMrGIuRQsjVbdIaDJBYLJTlenVpN/XERWfisLnkP6HEM=";

Now that you’ve assigned your license key and serial number to their respective in-code variables, you can use them to initialize the Foxit SDK.

First, create an instance of the foxit.common.ErrorCode enumerator. You can name it error_code or something similar. This enumerator will be used to contain the result of the initialization process, which will be carried out by the foxit.common.Library class’s Initialize method.

The Initialize method accepts two string variables: the Foxit serial number (sn) and license key (key) strings you assigned to two of your class strings earlier on. Pass the sn and key strings as the argument to the Initialize method:

csharp
ErrorCode error_code = Library.Initialize(sn, key);

Add some code to help you determine if the Foxit PDF SDK was successfully initialized and to help you with rudimentary error handling. For now, declare a new public string called message and initialize it with an empty string:

csharp
public string message = "";

With the above steps complete, the additions to your IndexModel class file should resemble the following:

csharp

public string message = "";
static string sn = "eHZELU0twWL0OuhsAlDNXxxjJvqGKETmxG6Y4zlgGnPdI8dBNRKv7w==";
static string key = "8f3gFcGNtR8N+Td6AF43CmmH5xt1p8I6Ezse924Y/yIH9u/kcPAE40puFED3oBj7KMrlzYnceCvGoVdvKfiK3Z60JuWDq3fX5hWwd+Dv2B7wUXQpqvIPfarxpgSou3T1hJGpvX1Mp1TZEJ2VcFAckgTqtH4Ru+8Ek8f/YWbv3rP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6Owzl34rvN5+BpXa16ZJWDWgptD7EqP0IjKEDq1RdxFBmErAfYFtMrGIuRQsjVbdIaDJBYLJTlenVpN/XERWfisLnkP6HEM=";

ErrorCode error_code = Library.Initialize(sn, key);

Note: Please use the serial numbers and license keys provided by Foxit. The values used in this example are most likely expired.

Next, create a post method for the form component section to handle the bulk of the backend logic. Declare a new OnPost method underneath the OnGet method, following the basic structure of the OnGet method. As such, it must be public and have void as its return type:

csharp
public void OnPost(){}

Once you’ve declared the OnPost method, check if the Foxit PDF SDK was initialized successfully. You’ll of course be using the message variable you declared earlier on. Add the following code to the OnPost method:

csharp
if (error_code != ErrorCode.e_ErrSuccess)
    message = "Foxit SDK failed to initialize";

For now, your OnPost method should resemble the following:

csharp
public void OnPost()
{
    if (error_code != ErrorCode.e_ErrSuccess)
        message = "Foxit SDK failed to initialize";
}

Now that you’ve added initialization code for the SDK, you can begin to build the document conversion process.

5. Build the Conversion Process

You can view the source code for the entire Index.cshtml.cs file here.

Before you continue with the rest of the steps, scroll to the top of the IndexModel class file and ensure that both the System.IO and System libraries are imported:

csharp
using System.IO;
using System;

You’ll use their components in the OnPost method for directory and file verification.

Now, create a variable that will contain the string value from your client’s main input text field. Scroll down slightly and declare a new public string class variable to the IndexModel class. Name it directory and assign an empty string to it:

csharp
public string directory = "";

Scroll back down to the OnPost method and map the directory string to the corresponding text field from the client:

csharp
directory = Request.Form["directory"];

Next, declare an array that will store all the file paths from the specified directory. Use the GetFiles(string path) method from the Directory class to retrieve all these file paths:

csharp
string[] filePaths = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);

Ensure that the filePaths array isn’t empty before using it. Declare an if statement that checks if the array’s length is greater than zero:

csharp
if(filePaths.Length > 0)  

The rest of the steps will focus on the body of this if statement.

Add a new string called savepath. This path will be used to store the converted files, and you can hard-code it with any value you desire. However, the best option would be to create a folder relative to the directory you entered into the text field:

csharp
string savepath = directory + "\\converted files\\";

Next, declare an additional embedded if statement that will validate the existence of the output directory. If the output directory doesn’t exist, your code will create it in the body of the if statement:

csharp
if (!Directory.Exists(savepath))
{
    Directory.CreateDirectory(savepath);
}

You now need to create a mechanism that loops through the files and converts them according to their file type. Declare a foreach loop that will parse through the filePaths array:

csharp
foreach (string file in filePaths)

Make sure the body of the foreach loop checks the file type of each element of the filePath array and applies the necessary conversion.

Declare an instance of the FileInfo class with the array element as the argument:

csharp
FileInfo fi = new FileInfo(file);

Next, declare three separate if statements in the body of the foreach loop, checking if the file is of .doc type, .ppt type, or .xls type:

csharp
if (fi.Extension == ".doc")   		//Post office-1997 versions 
if (fi.Extension == ".ppt")
if (fi.Extension == ".xls")

You’ll use static methods from the foxit.addon.conversion.Convert class to convert them into PDFs. You can learn more about them from Foxit’s .NET API reference. To keep it simple, you’ll use the default settings for each conversion method.

Once that’s done, you can add closing brackets to the file path verification if statement. You’ll need to declare some code for minor error handling. Add an else statement that sets the message string to “Please enter a valid directory“, then add all the necessary closing brackets.

The final OnPost method should look like this:

csharp
public void OnPost()
        {

            if (error_code != ErrorCode.e_ErrSuccess)
                message = "Foxit SDK failed to initialize";


            directory = Request.Form["directory"];
            string[] filePaths = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);
            if (filePaths.Length > 0)
            {
               string savepath = directory + "\\converted files\\";
                if (!Directory.Exists(savepath))
                {
                    Directory.CreateDirectory(savepath);
                }
                foreach (string file in filePaths)
                {
                    FileInfo fi = new FileInfo(file);
                    if (fi.Extension == ".doc")
                    {
                        using (foxit.addon.conversion.Word2PDFSettingData word_convert_setting_data = new foxit.addon.conversion.Word2PDFSettingData())
                        {
                            foxit.addon.conversion.Convert.FromWord(file, "", savepath + "\\" + fi.Name + ".pdf", word_convert_setting_data);
                        }
                    }
                    else if (fi.Extension == ".ppt")
                    {
                        using (foxit.addon.conversion.PowerPoint2PDFSettingData ppt_convert_setting_data = new foxit.addon.conversion.PowerPoint2PDFSettingData())
                        {
                            foxit.addon.conversion.Convert.FromPowerPoint(file, "", savepath + "\\" + fi.Name + ".pdf", ppt_convert_setting_data);
                        }
                    }
                    else if (fi.Extension == ".xls")
                    {
                        using (foxit.addon.conversion.Excel2PDFSettingData excel_convert_setting_data = new foxit.addon.conversion.Excel2PDFSettingData())
                        {
                            foxit.addon.conversion.Convert.FromExcel(file, "", savepath + "\\" + fi.Name + ".pdf", excel_convert_setting_data);
                        }
                    }
                }
            }
            else
            {
                message = "Please enter a valid directory";
            }
            
            
        }

6. Add Error Handling to the Client

Return to the Index.cshtml file and add the following code that checks if the message string is empty and includes a paragraph component with red text to display the error message:

csharp
@if (Model.message.Length > 0) 
{
     <p style="color:red">@Model.message</p>
   
}

You can now build and run your application. It’s best to use IIS Express as the platform.

You can verify your code by comparing it against the final Index.cshtml file.

Running the Application

The application requires you to supply it with a directory. This directory must contain post-1997 Office file types, which include .doc, .xls, and .ppt . Once you supply the application with a directory, click the Convert button. The application will then scan through the top level folder of the directory to find all eligible files and automatically convert them to PDF for you.

Choose or create a directory on your local storage (such as C:\Test), then add Office documents to it:

create a directory

Run your OfficePDFConverter web application from Visual Studio.

Copy and paste the Office file directory into the text field or type it in, then click the Convert button:

click the Convert button

The web page will load. Once it’s done, you’ll find a new folder in your source directory called converted files:

converted files

The above folder should contain all the converted PDF documents:

converted PDF documents

Of course, you can implement additional features, such as a loading bar or a success message/dialog, to make the application more user-friendly. You can also change the names and labels of the VS templates.

Conclusion

Even as companies such as Microsoft look to make document file types obsolete by expanding into the software as a service (SaaS) market, PDFs still remain the industry standard for digital documentation. They’re secure, reliable, and maintain the same layout regardless of what software you use to view them.

Yet, one advantage that Word docs and Excel spreadsheets still have over PDFs is that they are pliable and easier to work with. You can circumvent these limitations by pairing your workflows with Foxit’s line of SDKs and applications. They can make PDFs more malleable while still conserving all of their advantages. This guide only introduced you to one of many ways you can optimize your Office and PDF workflows. Contact Foxit today to learn more.

Author: Mdu Sibisi