document_processing_header

In web application development, you often encounter requirements like generating a Word document with an invoice, generating a spreadsheet with product listings or generating a PDF document with the current business metrics. These sorts of requirements are commonly referred to as "document processing."

When it comes to ASP.NET AJAX based web applications, there are a lot of options available to generate these kinds of documents. For example, there is the Open Office XML SDK for generating Office apps or there are open source components like ITextSharp that help you with PDF document generation. In this article, I will take a look at another option: Telerik's Document Processing APIs that are bundled with the UI for ASP.NET AJAX product suite.

What is the Document Processing API?

The UI for ASP.NET AJAX suite is a complete developer toolbox for your ASP.NET AJAX project. It has over 80 controls that provide rich UI and tons of features which are available out-of-the-box. But it isn't limited to just controls; there are certain hidden gems in the suite. One such hidden gem is the Document Processing API.

The Document Processing API helps you generate documents on the fly, at runtime, on your server without requiring any additional software to be installed. You just reference a DLL in your project and you get the power of Word/Excel/PDF generation for your project.

At the moment, our Document Processing API support the following document creations:

  • Word Document Processing;
  • Spreadsheet Document Processing;
  • PDF Document Processing.

Using the Document Processing API

If you do not already have UI for ASP.NET AJAX installed, now would be a good time to grab a trial copy if you'd like to follow along.

The easiest ways to work with the AJAX controls is to create a new project using the project template that ships with them. Open Visual Studio and select File > New Project. In the New Project dialog window, select Telerik > Web from the installed Templates and select " Telerik C# Web Forms Application". Give it a name and location and click "Ok."

You will be presented with additional dialogs from the Project Configuration Wizard. Keep the defaults and proceed with the project creation (Note: For this example, you can skip creating a Data Access ORM model). Visual Studio will go ahead and spin up our new project.

Fig 1: Visual Studio New Project Dialog

Fig 1: Visual Studio New Project Dialog

If you take a look at the Project References, you will see the Document Processing API referenced by default:

Fig 2: Project References with Document Processing API

Fig 2: Project References with Document Processing API

If you would like to use the Document Processing API on an existing project, you will need to reference the assemblies below.

For Word Processing:

  • Telerik.Windows.Documents.Core
  • Telerik.Windows.Documents.Flow
  • Telerik.Windows.Zip
  • Telerik.Windows.Documents.Flow.FormatProviders.Pdf
  • Telerik.Windows.Documents.Fixed

For Spreadsheet Processing:

  • Telerik.Windows.Documents.Core.dll
  • Telerik.Windows.Documents.Spreadsheet.dll
  • Telerik.Windows.Maths.dll
  • Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml.dll
  • Telerik.Windows.Documents.Spreadsheet.FormatProviders.Pdf.dll
  • Telerik.Windows.Zip.dll

For PDF Processing:

  • Telerik.Windows.Documents.Core.dll
  • Telerik.Windows.Documents.Fixed.dll
  • Telerik.Windows.Zip.dll

Next, let's take a whirlwind tour of the 3 Document Processing APIs, one by one.

Word Document Processing

RadWordsProcessing is the Word Document Processing API that allows you to create, load, modify and export documents to variety of formats. Here are some of the features of RadWordsProcessing:

  • Import and export documents to several formats;
  • Supports tables, images, hyperlinks, headers and footers;
  • Easy-to-use API for generating and manipulating documents;
  • Built-in themes and styles.

Creating a Word Document

In order to create a document we first have to make use of RadFlowDocument to create a flow document. We add text/images/tables using the RadFlowDocumentEditor. RadFlowDocument and RadFlowDocumentEditor are available under the namespace Telerik.Windows.Document.Flow.Model and Telerik.Windows.Document.Flow.Model.Editing.

The below code demonstrates how to create a document:

var document = new RadFlowDocument();
var editor = new RadFlowDocumentEditor(document);
editor.ParagraphFormatting.TextAlignment.LocalValue = Alignment.Justified;
editor.InsertLine("Dear Telerik User,");
editor.InsertText("We're happy to introduce the new Telerik RadWordsProcessing component for WPF. High performance library that enables you to read, write and manipulate documents in DOCX, RTF and plain text format. The document model is independent from UI and ");
Run run = editor.InsertText("does not require");
run.Underline.Pattern = UnderlinePattern.Single;
editor.InsertLine(" Microsoft Office.");
editor.InsertText("The current community preview version comes with full rich-text capabilities including ");
editor.InsertText("bold, ").FontWeight = FontWeights.Bold;
editor.InsertText("italic, ").FontStyle = FontStyles.Italic;
editor.InsertText("underline,").Underline.Pattern = UnderlinePattern.Single;
editor.InsertText(" font sizes and ").FontSize = 20;
editor.InsertText("colors ").ForegroundColor = ThemableColor.FromArgb(100, 92, 230, 0);
editor.InsertLine("as well as text alignment and indentation. Other options include tables, hyperlinks, inline and floating images. Even more sweetness is added by the built-in styles and themes.");
editor.InsertText("Here at Telerik we strive to provide the best services possible and fulfill all needs you as a customer may have. We would appreciate any feedback you send our way through the ");
editor.InsertHyperlink("public forums", "http://www.telerik.com/forums", false, "Telerik Forums");
editor.InsertLine(" or support ticketing system.");
editor.InsertLine("We hope you'll enjoy RadWordsProcessing as much as we do. Happy coding!");
editor.InsertParagraph();
editor.InsertLine("Kind regards,");
editor.InsertLine("Telerik Admin");

The methods used are all fairly self-explanatory. InsertText() inserts text. InsertLine() inserts the text and provides a new line. InsertParagraph() inserts a paragraph and InsertHyperLink() inserts a hyperlink. I have also set the foreground color for text using a RGB value. These are just a few of the possibilities available using the API.

Exporting a Document to DOCX format

The Word Document Processing API provides variety of document formats for exporting flow documents. For the DOCX format, we will need to use the DocxFormatProvider , which is available under the Telerik.Windows.Documents.Flow.FormatProviders.Docx namespace. The format provider exposes an Export() function that accepts a flow document and a stream to export the document to. The below code exports the document created in the prior code snippet to a DOCX file:

var formatProvider = new DocxFormatProvider();
byte[] renderedBytes = null;
using (MemoryStream ms = new MemoryStream())
{
    formatProvider.Export(document, ms);
    renderedBytes = ms.ToArray();
}
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment; filename=ExportedFile.docx" );
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.BinaryWrite(renderedBytes);
Response.End();

Here is a snapshot of the exported Word document:

Fig3

This was just a brief introduction to the RadWordsProcessing API. You can find more scenarios in the online demos, or check the documentation for the Word Document Processing API.

Spreadsheet Document Processing

The spreadsheet document processing is called RadSpreadProcessing and it enables your application to work with most common spreadsheet file formats. RadSpreadProcessing will help you import or export different spreadsheet formats and also has more than 100 built-in formulas. This is a powerful API when it comes to creating spreadsheets on the fly.

Creating a Spreadsheet Document

In order to create a new document, we will need to make use of the Workbook object. Once instantiated, the Workbook object provides a Worksheet collection that we can add worksheets. Each Worksheet has a cells collection and we can set the value of cells using the setValue() method. Each Worksheet contains 1048576 rows and 16384 columns. The following code illustrates how to create new Workbook and add a new Worksheet:

var workbook = new Workbook();
var worksheet = workbook.Worksheets.Add();
//Header Row
worksheet.Cells[0, 0].SetValue("#");
worksheet.Cells[0, 1].SetValue("Product Name");
worksheet.Cells[0, 2].SetValue("Unit Price");
worksheet.Cells[0, 2].SetHorizontalAlignment(RadHorizontalAlignment.Right);
worksheet.Cells[0, 3].SetValue("Units in Stock");
worksheet.Cells[0, 3].SetHorizontalAlignment(RadHorizontalAlignment.Right);
worksheet.Cells[0, 4].SetValue("Sub Total");
worksheet.Cells[0, 4].SetHorizontalAlignment(RadHorizontalAlignment.Right);
//Row 1
worksheet.Cells[0, 0].SetValue("P01");
worksheet.Cells[0, 1].SetValue("Chai");
worksheet.Cells[0, 2].SetValue("21");
worksheet.Cells[0, 3].SetValue("100");
worksheet.Cells[0, 4].SetValue("2100");

Exporting Document to XLSX Format

The Spreadsheet Processing API supports the XLSX, PDF, TXT and CSV formats for exporting. There are different providers to export to different formats. For example, the XlsxFormatProvider is for the XLSX format. The provider provides an Export() method that expects the workbook and a stream to which the workbook will be exported. Here is a code snippet showing how to export the workbook to a XSLX format:

byte[] renderedBytes = null;
var formatProvider = new XlsxFormatProvider();
using (MemoryStream ms = new MemoryStream())
{
    formatProvider.Export(workbook, ms);
    renderedBytes = ms.ToArray();
}
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment; filename=ExportedFile.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(renderedBytes);
Response.End();

Below is a snapshot of the Excel sheet that it generates:

Fig 4: Exported Excel Document

Fig 4: Exported Excel Document

The Spreadsheet Processing API has much more functionality. For more information about the API, take a look at the online demos or refer to the documentation.

PDF Document Processing

To generate PDF documents, we'll use the RadPdfProcessing API that allows you to create, import and export PDF documents. This easy-to-use API also supports images and shapes. Let's take a look at how to create a PDF document and export it.

Creating a PDF Document

In order to create a new document, we will have to make use of RadFixedDocument, which is the root element in the PDF processing library. RadFixedDocument is available under the namespace Telerik.Windows.Documents.Fixed.Model. The following code creates a new PDF document:

var document = new RadFixedDocument();
var page = document.Pages.AddPage();
FixedContentEditor editor = new FixedContentEditor(page);
editor.Position.Translate(50, 50);
Block block = new Block();
block.GraphicProperties.FillColor = RgbColors.Black;
block.HorizontalAlignment = HorizontalAlignment.Left;
block.TextProperties.Font = FontsRepository.HelveticaBoldOblique;
block.TextProperties.FontSize = 40;
block.InsertText("RadPdfProcessing");
block.TextProperties.Font = FontsRepository.Helvetica;
block.TextProperties.FontSize = 30;
block.InsertText(" is a document processing library that enables your application to " + 
                 "import and export files to and from PDF format. The document model is " +
                 "entirely independent from UI and allows you to generate sleek documents " +
                 "with differently formatted text, images, shapes and more.");
editor.DrawBlock(block,new System.Windows.Size(500, double.PositiveInfinity));

Exporting a PDF Document

The PDF Processing API provides a PdfFormatProvider class that is required to export a document to the PDF format. The PdfFormatProvider class provides an Export() method that accepts a RadFixedDocument and a stream where document will be exported. Below we export the document created earlier as a PDF file:

var pdfProvider = new PdfFormatProvider();
byte[] renderedBytes = null;
using (MemoryStream ms = new MemoryStream())
{
    pdfProvider.Export(document, ms);
    renderedBytes = ms.ToArray();
}
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=PdfDocument.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(renderedBytes);
Response.End();

Below is a screenshot of the exported PDF document:

Fig 5: Exported PDF Document

Fig 5: Exported PDF Document

As with RadWordProcessing and RadSpreadProcessing, the RadPdfProcessing API also has online demos and API documentation.

Conclusion

As we discussed, the UI for ASP.NET AJAX suite not only includes controls, but also useful APIs such as Document Processing API. Without needing to install any server side software, you get spreadsheet , Word and PDF document generation. All you need are the UI for Asp.NET AJAX document processing assemblies and your requirements for on-the-fly document generation or document processing are taken care of. Go ahead and give it a try and be sure to let us know what you think.

Header image courtesy of Jabiz Raisdana


Telerik Blogging Ninja
About the Author

The Telerik Team

 

Related Posts

Comments

Comments are disabled in preview mode.