Telerik blogs

Open, view, download and print PDF documents from your ASP.NET Core app with the Telerik PDFViewer. See how!

The Portable Document Format (PDF) file type has become ubiquitous in business and enabling users to view, and download a PDF document is a common application requirement. The PDFViewer component from Progress Telerik UI for ASP.NET Core provides many capabilities out of the box—allowing you to open, view, download and print PDF documents. The component renders the content of a PDF document in the browser as canvas.

There are two alternative ways to process PDFs in the PDFViewer: with the help of PDF.js or the Telerik Document Processing libraries. We will look at the configuration needed for the component to work in both scenarios.

Using PDF.js Processing

You can set up the PDFViewer to use the PDF.js client-side library for processing and rendering a PDF file. PDF.js is a community-driven library for parsing and rendering PDFs supported by Mozilla.

  1. Load the pdf.js library in the application Layout, or in the view you will be using the PDFViewer in.
<script  src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.js"></script>
  1. In the view (e.g., Index.cshtml), declare the PDFViewer and set up its PdfjsProcessing configuration:
@(Html.Kendo().PDFViewer()
  .Name("pdfviewer")
  .PdfjsProcessing(pdf => pdf.File(Url.Content("~/App_Data/sample.pdf")))
  .Height(900)
)

We want a specific file to be displayed when the page loads, so we’ve set the path to the sample.pdf file in the File option within the PdfjsProcessing configuration. In this example, the file is located in the App_Data sub-folder of the application’s wwwroot folder.

The result will look like this:

PDF viewer with options for paging, zooming, selection tools, search, save, download, and print

Apart from displaying a file initially, the PDFViewer allows you to open a different PDF file that exists in the file system through the “Open” button in the toolbar.

Using Telerik Document Processing

The alternative to using PDF.js for processing the PDFs is using the Telerik Document Processing libraries. These libraries process the PDF document on the server and pass the data to the PDFViewer for visualization on the client.

Follow the steps below to set up the PDFViewer with Telerik Document Processing:

  1. Declare the component:
@(Html.Kendo().PDFViewer()
  .Name("pdfviewer1")
  .DplProcessing(dpl =>
    {
      dpl.Read(r => r.Url(Url.Action("GetInitialPdf", "Home")));
      dpl.Upload(upload => upload.Url(Url.Action("GetPdf", "Home")).SaveField("file"));
    })
  .Height(900)
)

We will display the sample.pdf file initially, which is why we need to set the Read option in the DplProcessing configuration. It points to the GetInitialPdf action in the Home controller.

The Upload option is for opening another file from the file system. The action responsible for that is called GetPdf. When the user opens a file, it is sent for processing to the GetPdf action and then the file data is passed back to the PDfViewer, which visualizes it.

  1. Declare the GetInitialPdf and GetPdf actions in the Home controller.
public IActionResult GetInitialPdf(int? pageNumber)
{
  JsonResult jsonResult;
  byte[] file = System.IO.File.ReadAllBytes(@"wwwroot\App_Data\sample.pdf");
  FixedDocument doc = FixedDocument.Load(file, true);

  if (pageNumber == null)
  {
    jsonResult = Json(doc.ToJson());
  }
  else
  {
    jsonResult = Json(doc.GetPage((int)pageNumber));
  }
  return jsonResult;
}

[HttpPost]
public IActionResult GetPdf(IFormFile file)
{
  byte[] data;
  using (Stream inputStream = file.OpenReadStream())
  {
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
      memoryStream = new MemoryStream();
      inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
  }
  FixedDocument dox = FixedDocument.Load(data);
  return Json(dox.ToJson());
}
  1. When you add the two actions, Visual Studio will prompt you for missing dependencies. The processing logic in the actions depends on the Telerik Document Processing assemblies, which come with the Telerik.Web.PDF NuGet package. To resolve the missing dependencies, install the Telerik.Web.PDF NuGet package from Visual Studio’s NuGet Package Manager and add the following “using” statement to the controller:
using Telerik.Web.PDF;

Toolbar Configuration and Customization

Toolbar Items Collection

Once you’ve chosen one of the available processing approaches, you can customize the PDFViewer’s toolbar and hide the tools you don’t need.

The PDFViewer displays a set of default tools in its toolbar. If your use case requires hiding some options, you can use the Toolbar configuration of the component and explicitly declare the tools that will be shown in the toolbar.

In the following exemplary toolbar configuration, the Toolbar.Items collection specifies the tools that will be shown.

Note that the “open” tool is not declared. As a result, the “Open” button will not appear in the toolbar and the user would only be able to view the PDF document you’ve chosen to load in the PDFViewer. They would not be able to open another file.

@(Html.Kendo().PDFViewer()
  .Name("pdfviewer")
  .PdfjsProcessing(pdf => pdf
    .File(Url.Content("~/Content/pdf/sample.pdf"))
  )
  .Toolbar(toolbar =>
    toolbar.Items(items =>
    {
      items.Add().Name("pager");
      items.Add().Name("spacer");
      items.Add().Name("zoom");
      items.Add().Name("zoomInOut");
      items.Add().Name("toggleSelection");
      items.Add().Name("spacer");
      items.Add().Name("search");
      items.Add().Name("download");
      items.Add().Name("print");
    })
  )
  .Height(900)
)

You will notice that the “spacer” tool is declared twice. Its purpose is to create an empty space between the tools. You can use it to group some of the tools or to isolate one tool from the rest.

You will get the following toolbar with the configuration posted above:

options for paging, zooming, selection tools, search, save, download, and print

Toolbar Item Template

You can go even further in the customization of the PDFViewer’s toolbar and declare custom tools by using the Template option.

The example below shows a button added as a custom tool along with some of the default tools:

.Toolbar(toolbar =>
  toolbar.Items(items =>
  {
    items.Add().Name("pager");
    items.Add().Name("spacer");
    items.Add().Name("Custom").Template("<button class='k-button k-button-solid k-button-md k-rounded-md k-button-solid-base k-icon-button'><span class='k-button-icon k-icon k-i-cog'></span></button>");
    items.Add().Name("search");
    items.Add().Name("download");
    items.Add().Name("print");
  })
)

You can attach a “click” handler to the button and execute your custom logic in it.

Next, we will look at a different scenario that involves both customizing the PDFViewer’s toolbar and using the API of the component.

Taking Advantage of the API

You may have a requirement to disable the download of PDF files, until the user accepts a terms of use agreement. A message will ask the user to confirm that they accept the agreement and want to download the file by clicking on a button outside the PDFViewer.

To achieve this requirement, you can handle the button’s “click” event and initiate the download of the file that is currently displayed by the PDFViewer with the help of the available API.

  1. Hide the “download” tool by not including it in the Toolbar.Items collection:
.Toolbar(toolbar =>
  toolbar.Items(items =>
  {
    items.Add().Name("pager");
    items.Add().Name("spacer");
    items.Add().Name("zoom");
    items.Add().Name("zoomInOut");
    items.Add().Name("toggleSelection");
    items.Add().Name("spacer");
    items.Add().Name("search");
    items.Add().Name("open");
    items.Add().Name("print");
  })
)
  1. The button that the user will click to confirm the agreement and start the download could look like this:
<button class="k-button k-button-solid-base k-button-solid k-button-md k-rounded-md" onclick="onAgreeButtonClick()">Agree and Download PDF</button>
  1. In the button’s click handler, the download is triggered by executing the “DownloadCommand” of the PDFViewer:
<script>
  function onAgreeButtonClick() {
    // get a reference to the PDFViewer
    var pdfviewer = $("#pdfviewer").data("kendoPDFViewer");
    // execute the Download command programmatically
    pdfviewer.execute({command:"DownloadCommand"});
  }
</script>

Working with Larger Files

Finally, we will use a feature of the PDFViewer that allows you to load a large PDF document without sacrificing performance and causing the page to become unresponsive.

In scenarios that involve loading large PDF documents, use the load-on-demand functionality of the PDFViewer. It is available when the component is configured to use Telerik Document Processing.

The following snippet shows how to enable the LoadOnDemand option:

@(Html.Kendo().PDFViewer()
  .Name("pdfviewer")
  .DplProcessing(dpl => {
    dpl.Read(r => r.Url(Url.Action("GetInitialPdf", "PdfViewer")));
    dpl.Upload(upload => upload.Url(Url.Action("GetPdf", "PdfViewer")).SaveField("file"));
    dpl.LoadOnDemand(true);
  })
  .Height(900)
)

With the LoadOnDemand option enabled, instead of requesting and visualizing all the pages of the document, the component requests and renders pages on demand, which improves performance by reducing the initial load time.

If you’re interested in learning more about the PDFViewer component, check out the folowing:

Try out the Telerik UI for ASP.NET Core PDFViewer Today

If you like what you’ve read and want to start taking advantage of the ASP.NET Core PDFViewer, or any of the other 110+ ready-made components, we invite you to start a free trial today. Experience firsthand that building rich interactive applications for half the time is just a click away.

Try Telerik UI for ASP.NET Core

Sharing is Caring

Once you try the ASP.NET Core PDFViewer component, don’t forget to share your experience and ideas in the comments sections below or by visiting the Telerik UI for ASP.NET Core Feedback Portal. Your input makes a difference.


About the Author

Ivan Danchev

Ivan Danchev is a Product Owner at Progress for the Telerik UI for ASP.NET MVC components. He joined the company in 2015 as a Technical Support Engineer in the AJAX team. Outside work, fast cars are one of Ivan’s greatest passions. As a devoted car enthusiast, he craves the adrenaline that racing and spirited driving generate.

Related Posts

Comments

Comments are disabled in preview mode.