This project has moved. For the latest updates, please go here.

To create your first PdfReport
 
a) Create a new class library project in Visual Studio. We will use it as the base report classes container for both Windows and Web applications.

b) Then add new references to the following assemblies:
PdfReport, iTextSharp and EPPlus.
Or just use the NuGet PowerShell console to add these references automatically:
PM> Install-Package PdfReport
http://nuget.org/packages/PdfReport/

c) Add the following classes to the class library project:

using System.Web;
using System.Windows.Forms;

namespace PdfReportSamples
{
    public static class AppPath
    {
        public static string ApplicationPath
        {
            get
            {
                if (isInWeb)
                    return HttpRuntime.AppDomainAppPath;

                return Application.StartupPath;
            }
        }

        private static bool isInWeb
        {
            get
            {
                return HttpContext.Current != null;
            }
        }
    }
}

We will use this class to specify the location of the produced PDF file.
It needs the following references as well:
- System.Windows.Forms.dll
- System.Web.dll

using System;

namespace PdfReportSamples.IList
{
    public class User
    {
        public int Id { set; get; }
        public string Name { set; get; }
        public string LastName { set; get; }
        public long Balance { set; get; }
        public DateTime RegisterDate { set; get; }
    }
}

"User" class will be used for creating an in-memory generic list data source.
And now add the main report class:

using System;
using System.Collections.Generic;
using PdfReportSamples.Models;
using PdfRpt.Core.Contracts;
using PdfRpt.FluentInterface;

namespace PdfReportSamples.IList
{
    public class IListPdfReport
    {
        public IPdfReportData CreatePdfReport()
        {
            return new PdfReport().DocumentPreferences(doc =>
            {
                doc.RunDirection(PdfRunDirection.LeftToRight);
                doc.Orientation(PageOrientation.Portrait);
                doc.PageSize(PdfPageSize.A4);
                doc.DocumentMetadata(new DocumentMetadata { Author = "Vahid", Application = "PdfRpt", Keywords = "IList Rpt.", Subject = "Test Rpt", Title = "Test" });
            })
            .DefaultFonts(fonts =>
            {
                fonts.Path(Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\arial.ttf",
                                  Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\verdana.ttf");
            })
            .PagesFooter(footer =>
            {
                footer.DefaultFooter(DateTime.Now.ToString("MM/dd/yyyy"));
            })
            .PagesHeader(header =>
            {
                header.DefaultHeader(defaultHeader =>
                {
                    defaultHeader.RunDirection(PdfRunDirection.LeftToRight);
                    defaultHeader.ImagePath(AppPath.ApplicationPath + "\\Images\\01.png");
                    defaultHeader.Message("Our new rpt.");
                });
            })
            .MainTableTemplate(template =>
            {
                template.BasicTemplate(BasicTemplate.ClassicTemplate);
            })
            .MainTablePreferences(table =>
            {
                table.ColumnsWidthsType(TableColumnWidthType.Relative);
                table.NumberOfDataRowsPerPage(5);
            })
            .MainTableDataSource(dataSource =>
            {
                var listOfRows = new List<User>();
                for (int i = 0; i < 200; i++)
                {
                    listOfRows.Add(new User { Id = i, LastName = "LastName " + i, Name = "Name " + i, Balance = i + 1000 });
                }
                dataSource.StronglyTypedList(listOfRows);
            })
            .MainTableSummarySettings(summarySettings =>
            {
                summarySettings.OverallSummarySettings("Summary");
                summarySettings.PreviousPageSummarySettings("Previous Page Summary");
                summarySettings.PageSummarySettings("Page Summary");
            })
            .MainTableColumns(columns =>
            {
                columns.AddColumn(column =>
                {
                    column.PropertyName("rowNo");
                    column.IsRowNumber(true);
                    column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                    column.IsVisible(true);
                    column.Order(0);
                    column.Width(1);
                    column.HeaderCell("#");
                });

columns.AddColumn(column =>
                {
                    column.PropertyName<User>(x => x.Id);
                    column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                    column.IsVisible(true);
                    column.Order(1);
                    column.Width(2);
                    column.HeaderCell("Id");
                });

columns.AddColumn(column =>
                {
                    column.PropertyName<User>(x => x.Name);
                    column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                    column.IsVisible(true);
                    column.Order(2);
                    column.Width(3);
                    column.HeaderCell("Name");
                });

columns.AddColumn(column =>
                {
                    column.PropertyName<User>(x => x.LastName);
                    column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                    column.IsVisible(true);
                    column.Order(3);
                    column.Width(3);
                    column.HeaderCell("Last Name");
                });

columns.AddColumn(column =>
                {
                    column.PropertyName<User>(x => x.Balance);
                    column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                    column.IsVisible(true);
                    column.Order(4);
                    column.Width(2);
                    column.HeaderCell("Balance");
                    column.ColumnItemsTemplate(template =>
                    {
                        template.TextBlock();
                        template.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj));
                    });
                    column.AggregateFunction(aggregateFunction =>
                    {
                        aggregateFunction.NumericAggregateFunction(AggregateFunction.Sum);
                        aggregateFunction.DisplayFormatFormula(obj => obj == null ? string.Empty : string.Format("{0:n0}", obj));
                    });
                });

})
            .MainTableEvents(events =>
            {
                events.DataSourceIsEmpty(message: "There is no data available to display.");
            })
            .Export(export =>
            {
                export.ToExcel();
                export.ToCsv();
                export.ToXml();
            })
            .Generate(data => data.AsPdfFile(AppPath.ApplicationPath + "\\Pdf\\RptIListSample.pdf"));
        }
    }
}

You can find its latest version here too: (+)

To use this class and create a new PDF report file, we can write:

var rpt = new IListPdfReport().CreatePdfReport();
// rpt.FileName


- In "DocumentPreferences" method we can specify the direction of the report (PdfRunDirection: RTL or LTR), page size (PdfPageSize), its orientation (PageOrientation) and so on.

- Then it's necessary to determine the default report font files in "DefaultFonts" method. First font will be the main font and second font will be used as the fallback font.

- PdfReport comes with a built-in footer and header samples. It's possible to customize these elements by implementing the IPageFooter and IPageHeader interfaces. We will discuss it in the other How-To's.

- By using the "MainTableTemplate" we can define the main grid's template. There are some predefined templates available in PdfReport library. Also it's possible to create the new templates by implementing the ITableTemplate interface.

- "MainTablePreferences" method will be used for specifying the settings of the main report's grid, such as how many rows per page should be available (if we don't specify it, rows count will be calculated automatically based on the page size).
"ColumnsWidthsType" method accepts 4 different values:
a) Relative: Each column has a relative width equal to 1. Example: Relative values = 2, 1, 1. This means that you want to divide the width of the table into four parts (2 + 1 + 1): two parts for the first column, one part for columns two and three.
b) Absolute: The absolute width expressed in user space units.
c) EquallySized: Equally sized columns. In this case, all of the specified widths will be ignored.
d) FitToContent: Tries to resize the columns automatically. In this case, all of the specified widths will be ignored.

- "MainTableDataSource" method sets the data source of the main grid. For instance in the above example "StronglyTypedList" method will process list of the users.
There are other built-in data source methods in PdfReport library. For example if you want to use raw SQL and work with the database directly, try the following methods:

//SQL server data source
public void SqlDataReader(string connectionString, string sql, params object[] parametersValues)

//.mdb or .accdb files
public void AccessDataReader(string filePath, string password, string sql, params object[] parametersValues)

//Odbc data source
public void OdbcDataReader(string connectionString, string sql, params object[] parametersValues)

// A generic data reader data source
public void GenericDataReader(string providerName, string connectionString, string sql, params object[] parametersValues)

It's possible to write parametric queries in all of the above methods. These parameters should start with @ symbol.
Here is the quick sample which shows how to work with SQLite databases in PdfReport:

                dataSource.GenericDataReader(
                    providerName: "System.Data.SQLite",
                    connectionString: "Data Source=" + AppPath.ApplicationPath + "\\data\\blogs.sqlite",
                    sql: @"SELECT [url], [name], [NumberOfPosts], [AddDate]
                               FROM [tblBlogs]
                               WHERE [NumberOfPosts]>=@p1",
                    parametersValues: new object[] { 10 }
                );

Add a reference to System.Data.SQLite assembly and then use the above generic data reader. Same rule applies to MySQL and other databases.

- "MainTableSummarySettings" method determines the auto generated summary/total labels and their position to show. It's optional.

- By using the optional "MainTableColumns" method, it's possible to determine the exact columns of the report's grid. Each column should be present in the data source. Also it's possible to define calculated fields as well. It will be discussed in other How-To's later. In "MainTableColumns" method, you can specify the related property of the column, its width, visibility, order and so on.
Here by using the "ColumnItemsTemplate" method, we can determine the type of the current field and how it should be displayed. If it should be displayed as a text, use template.TextBlock() method (it's the default method). Also there are some other built-in cell templates such as image, hyperlinks, etc. It's possible to use custom column templates by implementing the IColumnItemsTemplate interface too.
If you want to format the cell's value before rendering, use the  template.DisplayFormatFormula method. It's a callback method, which gives you the actual value of the cell and then you can format it and return the final result to show on the report.
By using the column.AggregateFunction method, we can determine the related aggregate method of the current column.
There are some predefined numeric aggregate functions available in PdfReport library. Also it's possible to write the custom ones by implementing the IAggregateFunc interface.

- "MainTableEvents" method, provides access to the internal events of the main grid. For instance if the data source is empty, "DataSourceIsEmpty" event will be raised.

- Also it's possible to export the main table's data as excel, csv, xml, etc files. all of these exported files will be embedded in the final PDF file automatically.

Last edited Nov 5, 2012 at 1:28 PM by VahidN, version 2

Comments

No comments yet.