PDF Tech

Building a Dynamic Parts Catalog as a PDF

by PDF SDK | December 2, 2021

If you’re a user of PDF beyond the basic levels, you may already be familiar with Foxit. For over two decades, Foxit has been creating advanced tools for millions of users for the purpose of creating, signing, and securing PDF documents. 

Foxit has support for complete PDF functionality across all platforms and environments, including the web, Windows, Android, iOS, UWP, Mac, Linux, and more. Their solutions let you integrate functionality to view and edit PDF files and implement digital signatures, with a full eSign workflow.

Today, let’s look at how to set up Foxit’s PDF SDK technology in an ASP.NET web application. This article will help enable you to download items in a catalog as PDF files generated on the fly.

Online Product Catalog

Let’s say a catalog of items is presented online, for example in a webshop, and a user may want to get a list of items prior to purchase. Perhaps they need to get the purchase approved by a superior or send it to a customer for verification. While it’s possible to manually organize and send the user the information, that can be cumbersome and a waste of time. This is where predictably formatted PDF files come in.

In this article you’ll create a basic mock webshop with mock items to be exported to PDF files. These files will be generated on the fly by the Foxit PDF SDK.

> These demo files focus on the versatile technology that Foxit provides, but you can follow Foxit’s PDF SDK documentation to customize your files in any way you want. And you can always follow along with the GitHub repository created for this article.

Building a Product Catalog

Let’s get into how you build an online product catalog step by step.

Creating the .NET Project

The PDF SDK provided by Foxit can be used with a .NET Core project or .NET 5 (or later). We will use .NET 5 to validate this and gain any possible performance and stability improvements that come with every new version of .NET, as well as to support future versions of .NET.

Start out by creating an ASP.NET application. In this case, you’ll use the ASP.NET Core Web App template, to get access to Razor Pages, in order to get started quickly. You can also use the MVC, Web API template, or any other .NET template that suits your specific scenario.

This tutorial is also using Visual Studio, but you can use any IDE or editor you want.

This sets up the boilerplate code to quickly have a web application up and running, which you will extend with content and PDF functionality.

Downloading the Foxit PDF SDK

Next, download the Foxit PDF with a free trial license.

After entering your information into the form, you’ll receive an email with a link to the download. Download a .zip file, containing the .dll files needed as well as two .txt files containing the license information used during the trial period.

Copy the .dll files to a directory in your .NET project. Avoid copying the .txt files, to ensure that these do not get included in your repository and then possibly exposed to people who shouldn’t have access.

In this example, a commonly used practice for open source projects was used and a directory was placed in the root of the project called dep with the subfolder foxitpdfsdk, where the .dll files are located.

Configuring the .NET Project

Next, it’s time to set up the .NET project to use the Foxit PDF SDK .dll files.

First, specify the _Platform target_ for the .NET project, to ensure the correct version of Foxit’s .dll files are used and referenced correctly. This tutorial uses x64, but you will also receive .dll files that support x86. You can easily change this in Visual Studio by right-clicking on the project, picking Properties > Build and changing the setting of Platform Target away from Any CPU to either x64 or x86.

You could also edit the .csproj file for your project and add the following node, under the first <PropertyGroup> node:

<Platforms>x64</Platforms>

This sets up to reference the actual .dll files to the .NET project.

You can also complete this in Visual Studio by right-clicking the Dependencies node of the project, clicking any of the Add *x* Reference options, navigating to the Browse tab, and clicking Browse on the bottom. In the file dialog, you will click through to the correct folder, based on your previous choice of x64 or x86, and reference the fsdk_dotnetcore.dll file.

After referencing the correct file, ensure that the fsdk.dll file is also copied to the output folder when your .NET project builds. Complete this in Visual Studio by referencing the existing file. Right-click on the project, and under Add, pick Existing Item. Change any filtering to _All Files (*.*)_, and select the fsdk.dll file.

If you’re not using Visual Studio, the two previous steps involving fsdk_dotnetcore.dll and fsdk.dll result in the following XML nodes being added to your .csproj file. You can also manually add them yourself.

<ItemGroup>
  <Reference Include="fsdk_dotnetcore">
    <HintPath>..\..\dep\foxitpdfsdk\x64_vc15\fsdk_dotnetcore.dll</HintPath>
  </Reference>
</ItemGroup>

<ItemGroup>
  <None Update="fsdk.dll">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

Online Product Catalog with PDF Functionality

Now let’s build the online product catalog with PDF functionality. In this example, it will be an online catalog of products where each individual product can be downloaded as a PDF file. The catalog is a mock webshop for computer parts, which are hard-coded in this demo app. In a real-life scenario, it would most likely fetch its data from external data sources like a database.

The magic happens when you click View as PDF for the products. That’s when the Foxit PDF SDK kicks in. Let’s go over the important parts of the code for this.

In the demo app, the PDF generation functionality is run in the PdfGenerator.cs file. This file is registered as a singleton service in the ASP.NET app, meaning that its constructor is only run once and the instance is kept alive for the lifetime of the application. This is why the constructor includes the code for initializing the Foxit PDF SDK.

var result = Library.Initialize("Serial_No", "Key");
if (result != ErrorCode.e_ErrSuccess)
{
    throw new ApplicationException($"Failed to initialize Foxit PDF SDK: {result}");
}

The Serial_No and Key are found in the gsdk_key.txt and gsdk_sn.txt files that you got in the .zip file downloaded for the trial.

You want to make sure that the result of .Initialize is a success (ErrorCode.e_ErrSuccess). Otherwise, you would need to throw an exception to bring immediate attention to the fact that this fundamental step has gone wrong.

Next, move on to creating the PDF document, form, and page that you’ll be populating with the product information:

using var doc = new PDFDoc();
using var form = new Form(doc);
using var page = doc.InsertPage(0, PDFPage.Size.e_SizeLetter);

From this, use the form and page objects to add your elements containing the product information. In the demo application, you’ll use a helper method named AddField to quickly add three fields, containing the ID, name, and price of the product. The method AddField looks like this:

private static void AddField(string title, string text, int offset, Form form, PDFPage page)
{
    var rect = new RectF(50f, 600f - offset, 500f, 640f - offset);

    using var control = form.AddControl(page, title, Field.Type.e_TypeTextField, rect);

    using var field = control.GetField();

    field.SetValue(text);
}

The method takes as arguments the title of the control added to the form, the text content of the text field, an offset used by the method’s rect object to not place all the fields on top of each other, as well as the needed form and page that you’ll be adding content to.

As a last step in the PDF generation, use the helper method GetPdfStream. This uses the Foxit PDF SDK to write the PDF to disk in a temp path, then loads it into memory to be able to send back the file content in your ASP.NET application. Delete the temporary file on disk to avoid using up unnecessary disk space over time.

Finally, in Pdf.cshtml.cs, use the IPdfGenerator interface, whose implementation is the PdfGenerator class, to return the generated Stream as a FileStreamResult to the user. This will enable the user’s browser to directly display the PDF file, instead of forcing a download of the file.

public IActionResult OnGet(long id)
{
    var product = _productService.GetProduct(id);
    if (product == null)
    {
        return NotFound();
    }

    var pdfStream = _pdfGenerator.GenerateForProduct(product);
    return new FileStreamResult(pdfStream, "application/pdf");
}

Troubleshooting Checklist

If you’re having problems with the setup, make sure you double-check a few of the following items.

Use the Correct Serial Number and Key

The file gsdk_key.txt is a multiline file with six lines of content. What you want to use in your app when initializing the Foxit PDF SDK is the content after Sign= until the end of the line, excluding the equal sign (=) character.

When it comes to the gsdk_sn.txt file, only use the content after SN= and include any trailing equals sign (=) characters.

Download the Correct PDF SDK Library

If you’re working with .NET Core or .NET 5 (or later), make sure you download the file titled _Foxit PDF SDK for Windows (.NET Core Library)_.

Use the Correct Version of the PDF SDK .dll Files

If you’ve set the Platform target of your project to x64, make sure you reference the .dll files in the x64_vc15 folder from the downloaded Foxit PDF SDK. If you’re using x86, use the files in the x86_vc15 folder.

Error AccessViolationException During PDF Generation

You may be experiencing the following exception while generating the PDF file:

AccessViolationException - Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

In that case, you probably haven’t initialized the PDF SDK correctly. First, verify that calling the Library.Initialize method was successful, as described above. Then make sure that Library.Initialize is only run once and that Library.Release has not been run.

Error Mismatch of Processor Architecture

You may get the following error or warning message while building your project:

warning MSB3270: There was a mismatch between the processor architecture of the project being build MSIL and the processor architecture of the reference

This can be mitigated by ensuring that all your projects have the correct Platform target set and that the right version of the Foxit PDF SDK is referenced.

In the demo application on GitHub, for example, two projects are used to simulate a scenario that’s more realistic than a traditional single-project application, ensuring that it’s a typical scenario.

Conclusion

Regardless of how simple or complicated your use case is for PDF functionality, you’ve seen how easy it can be to implement using Foxit PDF SDK.

PDF is not known to be an easy standard to deal with manually, but the Foxit PDF SDK allows you to programmatically create and edit PDF files according to your own needs. By leveraging the strength and predictability built into the PDF standard, you can send a file to colleagues and customers with confidence that it will look and perform as expected on their machines and software.

Be sure to check out Foxit’s documentation for their PDF SDK, and get inspired by the many powerful scenarios it enables you to easily implement on your favorite platform.

Author: Sebastian Nilsson