Skip to main content Skip to footer

How to Create PDF Services in C1WebApi using .NET Core

The ComponentOne Web API includes a PDF library to help generate, cache, and export PDFs on the server. These are REST-based API services, which communicate with an HTML 5 PDFViewer control to display the PDF documents on the web. Client applications send a request to the PDFDocument service applications to load or export PDF files.

In this blog, we will show how you can set up a PDF Web API for ASP.NET Core 6 and how to display it using the ComponentOne PdfViewer control, which can be used to export the PDF to other formats, including Word and Excel.

Ready to Try It Out? Download ComponentOne Today!

Creating a C1WebApi application in ASP.NET Core

To display in PDF using C1WebApi, we will first create a C1WebApi application in Visual Studio. Create a new project and select C1 Web Api Application for ASP.NET Core template.

C1WebApi

Enter the name of the project and its location. From the Project Settings dialog box, select ASP.NET Core 6 and check the PDF Services checkbox. This will install the necessary NuGet packages required to run the PDF WebApi.

ASP.NET Web API

Once the project is loaded, create a folder inside the wwwroot folder of the project and name it as PdfRoot. This folder will contain the PDFs to be displayed, and we will bind this folder to the WebApi. You can also create multiple folders to store different PDFs. Copy the required PDF to this folder. Once done, add the following code to the Startup.cs file.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
            app.UseC1Api();
            app.UseStaticFiles();

            // do not change the name of defaultCulture
            var defaultCulture = "en-US";
            IList<CultureInfo> supportedCultures = new List<CultureInfo>
            {
                new CultureInfo(defaultCulture)
            };
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new RequestCulture(defaultCulture),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });

            app.UseMvc();

            app.UseStorageProviders()
            .AddDiskStorage("PdfRoot", Path.Combine(env.WebRootPath, "PdfRoot"));
}

This will enable C1WebApi and will bind the PdfRoot folder with the PdfRoot key. The first parameter of the AddDiskStorage method is the key and the second parameter of the Combine method is the folder. Now, whenever a PDF needs to be accessed using the API, the PdfRoot key will be used. You can also add multiple disk storage with different keys to access PDF in different folders.

Run the project and navigate to the following URL:

http://localhost:<port>/api/pdf/PdfRoot/<PDF Name>.pdf/$pdf/status

A similar result should be displayed at your end. The following JSON provides information about the PDF, like whether it is loaded or not or how many pages are there in the PDF.

API Results

Using ComponentOne ASP.NET Core PdfViewer to load and view PDF from server storage

Once the C1WebApi is set up, we need to display the PDF in a PDFViewer. C1 ASP.NET Core's PDFViewer can be used for this purpose. The PDFViewer provides many different options to view a PDF file using its interactive features and user-friendly user interface. PDFViewer is a fast and flexible HTML5 based PDF viewer that allows the user to display PDF files in the web browser.

In the New Project dialog box of Visual Studio, select C1 ASP.NET Core MVC Application.

Viewer Template

Enter the name of the project and set its location. In the Project Settings dialog box, select ASP.NET Core 5.0 and check the Include FlexViewer Library. This will install all the necessary libraries for FlexView support and update tag helpers accordingly.

ASP.NET Core 6.0

After the project is loaded, in the /Home/Index.cs file, add the following code to include the PdfViewer:

<c1-pdf-viewer service-url="http://localhost:<port>/api/pdf" file-path="PdfRoot/<pdf name>.pdf"></c1-pdf-viewer>

The service-url should be the link to your C1WebApi. The api/pdf in the URL is used to let the C1WebApi know that we are using the pdf services. The file path is the path to the PDF. PdfRoot is the key, which was set in the AddDiskStorage method.

Run the project, and a similar output should be displayed depending on your PDF.

PDF Output

Using ComponentOne ASP.NET Core PdfViewer to load and view PDF from client-side

C1PdfViewer also supports displaying PDFs by uploading them from the client's browser. To achieve this, we will need to select a PDF using the input element, upload it to our WebApi application folder and use the WebApi to display it.

Add the following input element in the Index.cshtml file. This will add a select file form to the layout:

<div class="row">
    <label>Select a Pdf file: <input type="file" onchange="uploadPdf(this, '@Url.Content("~")')" accept=".pdf" /></label>
    <label id="message" class="errormessage hidden">(Please select a file with extension ".pdf".)</label>
</div>

<c1-pdf-viewer width="100%" id="pdfViewer"></c1-pdf-viewer>

Notice that we did not add the file-path because it will be generated at runtime. Now add the following Javascript in your application:

var lastTempPdf;
function uploadPdf(fileInput, host) {
    var files = fileInput.files;
    if (!files || !files.length) return;

    var file = files[0];
    if (!file) return;

    if (file.name.slice(-4).toLowerCase() !== '.pdf') {
        return;
    }

    var data = new FormData();
    data.append("file", file);

    var pdfUrl = "PdfRoot/" + file.name;;
    var url = host + "api/storage/" + pdfUrl;

    if (url === lastTempPdf) return;

    $.ajax({
        url: url,
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        success: function (data, success, obj) {
            deleteTempPdf(true);
            lastTempPdf = url;
            loadPdf(pdfUrl);
        }
    });
}

function deleteTempPdf(async) {
    if (!lastTempPdf) {
        return;
    }

    $.ajax({
        url: lastTempPdf,
        type: 'DELETE',
        async: async
    });

    lastTempPdf = null;
}

The uploadPdf method will check whether the file selected is PDF or not, and if it is, it will send this PDF to our C1WebApi, where the new PDF will be stored in the PdfRoot folder. It will also check whether any last PDF is also selected and will delete it so that multiple PDFs do not take up storage on our application.

Once the PDF is uploaded, we will need to update the file-path of the PdfViewer so that it can be displayed:

function loadPdf(filePath) {
    var pdfViewer = wijmo.Control.getControl('#pdfViewer');
    pdfViewer.filePath = filePath;
}

The getControl method will fetch the reference of the C1PdfViewer and update the filePath property returned by the server using Javascript. Once the filePath is updated, the C1PdfViewer will automatically reload the PDF.

Browsing

Searching in PDF

C1 PdfViewer provides searching in PDF out of the box. In the left panel, click the search button, enter the desired search string, and press Enter. The panel will display all the results below, and we can navigate to each result by clicking on it.

Searching

Exporting PDF to various formats

C1PdfViewer also supports exporting PDF to various formats. These formats include:

  • Adobe PDF Document
  • HTML SVG Document
  • TIFF, JPG, PNG, BMP, and GIF Images
  • Open XML Word Document
  • Open XML Excel Document

Note that Word and Excel documents will also contain images.

Click on the Export button next to the Print button. Select the appropriate format, fill in the information accordingly (if required), and click Export.

Exporting

Conclusion

This article described in brief how to create PDF Services with C1WebApi and display a PDF in PdfViewer. For more information, please refer to the following resources:

Ready to Try It Out? Download ComponentOne Today!

comments powered by Disqus