Click here to Skip to main content
15,861,172 members
Articles / Programming Languages / C#
Tip/Trick

Exporting a DataTable to PDF

Rate me:
Please Sign up or sign in to vote.
4.97/5 (20 votes)
27 Mar 2012CPOL1 min read 148.5K   13.8K   32   28
Using MigraDoc as an open source .NET library to export a DataTable to PDF.

pdf

Introduction

MigraDoc Foundation is an Open Source .NET library that easily creates documents based on an object model with paragraphs, tables, styles, etc. and renders them into PDF, XPS, or RTF. A new feature I have added is when you provide a datatable (.NET) it will be easily converted to a PDF file.

Using the code

The zip file is a Visual Studio 2010 solution. PdfForm.cs has the functionality for converting a datatable to PDF and the remaining work is done using code inside the Default.aspx file.

C#
public Document CreateDocument()
{
    // Create a new MigraDoc document
    this.document = new Document();
    this.document.Info.Title = "";
    this.document.Info.Subject = "";
    this.document.Info.Author = "Aftab";

    DefineStyles();
    CreatePage();
    FillContent();
    return this.document;
}

Here, CreateDocument() in PDFform.cs creates a new MigraDoc. Take a look at the three functions called for creating style and page and fill the content of the tables.

C#
//
void DefineStyles()
{
    // Get the predefined style Normal.
    Style style = this.document.Styles["Normal"];
    // Because all styles are derived from Normal, the next line changes the 
    // font of the whole document. Or, more exactly, it changes the font of
    // all styles and paragraphs that do not redefine the font.
    style.Font.Name = "Verdana";

    style = this.document.Styles[StyleNames.Header];
    style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);

    style = this.document.Styles[StyleNames.Footer];
    style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);

    // Create a new style called Table based on style Normal
    style = this.document.Styles.AddStyle("Table", "Normal");
    style.Font.Name = "Verdana";
    style.Font.Name = "Times New Roman";
    style.Font.Size = 9;

    // Create a new style called Reference based on style Normal
    style = this.document.Styles.AddStyle("Reference", "Normal");
    style.ParagraphFormat.SpaceBefore = "5mm";
    style.ParagraphFormat.SpaceAfter = "5mm";
    style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
}

DefineStyles() does the job of styling the document:

C#
void CreatePage()
{
    // Each MigraDoc document needs at least one section.
    Section section = this.document.AddSection();
 
    // Put a logo in the header
    Image image= section.AddImage(path);

    image.Top = ShapePosition.Top;
    image.Left = ShapePosition.Left;
    image.WrapFormat.Style = WrapStyle.Through;
   
    // Create footer
    Paragraph paragraph = section.Footers.Primary.AddParagraph();
    paragraph.AddText("Health And Social Services.");
    paragraph.Format.Font.Size = 9;
    paragraph.Format.Alignment = ParagraphAlignment.Center;

    ............

    // Create the item table
    this.table = section.AddTable();
    this.table.Style = "Table";
    this.table.Borders.Color = TableBorder;
    this.table.Borders.Width = 0.25;
    this.table.Borders.Left.Width = 0.5;
    this.table.Borders.Right.Width = 0.5;
    this.table.Rows.LeftIndent = 0;

    // Before you can add a row, you must define the columns
    Column column;
    foreach (DataColumn col in dt.Columns)
    {
        column = this.table.AddColumn(Unit.FromCentimeter(3));
        column.Format.Alignment = ParagraphAlignment.Center;
    }

    // Create the header of the table
    Row row = table.AddRow();
    row.HeadingFormat = true;
    row.Format.Alignment = ParagraphAlignment.Center;
    row.Format.Font.Bold = true;
    row.Shading.Color = TableBlue;

    for (int i = 0; i < dt.Columns.Count; i++)
    {
        row.Cells[i].AddParagraph(dt.Columns[i].ColumnName);
        row.Cells[i].Format.Font.Bold = false;
        row.Cells[i].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[i].VerticalAlignment = VerticalAlignment.Bottom;
    }
    
    this.table.SetEdge(0, 0, dt.Columns.Count, 1, Edge.Box, 
         BorderStyle.Single, 0.75, Color.Empty);
}

Here CreatePage() adds a header, footer, and different sections into the document and then the table is created to display the records. Columns from the datatable are added into the table inside the document and then a header row that contains the column names is added.

C#
column = this.table.AddColumn(Unit.FromCentimeter(3)); 
//creates a new column and width of the column is passed as a parameter.

Row row = table.AddRow();
//A new header row is created  

row.Cells[i].AddParagraph(dt.Columns[i].ColumnName);
//this will add the column name to header of the row.

this.table.SetEdge(0, 0, dt.Columns.Count, 1, Edge.Box, 
           BorderStyle.Single, 0.75, Color.Empty);
//sets the border of the row


void FillContent()
{
    ...............

    Row row1;
    for (int i = 0; i < dt.Rows.Count; i++)
    {

        row1 = this.table.AddRow();
        row1.TopPadding = 1.5;

        for (int j = 0; j < dt.Columns.Count; j++)
        {
            row1.Cells[j].Shading.Color = TableGray;
            row1.Cells[j].VerticalAlignment = VerticalAlignment.Center;
           
            row1.Cells[j].Format.Alignment = ParagraphAlignment.Left;
            row1.Cells[j].Format.FirstLineIndent = 1;
            row1.Cells[j].AddParagraph(dt.Rows[i][j].ToString());

            this.table.SetEdge(0, this.table.Rows.Count - 2, dt.Columns.Count, 1, 
                 Edge.Box, BorderStyle.Single, 0.75);
        }
    }

    .............

}

FillContent() fills the rows from the datatable into the table inside the document:

C#
row1.Cells[j].AddParagraph(dt.Rows[i][j].ToString());
//adds the value of column into the table row

The Default.aspx file contains the code for generating the PDF:

C#
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System.Diagnostics;

MigraDoc libraries are used for generating PDF documents, and System.Diagnostics for starting a PDF Viewer:

C#
PDFform pdfForm = new PDFform(GetTable(), Server.MapPath("img2.gif"));

// Create a MigraDoc document
Document document = pdfForm.CreateDocument();
document.UseCmykColor = true;

// Create a renderer for PDF that uses Unicode font encoding
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);

// Set the MigraDoc document
pdfRenderer.Document = document;


// Create the PDF document
pdfRenderer.RenderDocument();

// Save the PDF document...
string filename = "PatientsDetail.pdf";

pdfRenderer.Save(filename);
// ...and start a viewer.
Process.Start(filename);

The PdfForm object is created and using it, a new MigraDoc is generated. PdfDocumentRenderer renders the PDF document and then saves it. Process.Start(filename) starts a PDF viewer to open the PDF file created using MigraDoc.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to save pdf with different name at every time (i want to save data report at every moment) Pin
Member 1264953122-Jul-16 21:06
Member 1264953122-Jul-16 21:06 
QuestionException Pin
Member 99199115-Mar-14 3:21
Member 99199115-Mar-14 3:21 
QuestionUsing a Dataset Pin
Member 99199115-Mar-14 1:08
Member 99199115-Mar-14 1:08 
Questioncreate password to PDF file Pin
IshaqSalam10-Dec-13 21:25
IshaqSalam10-Dec-13 21:25 
AnswerRe: create password to PDF file Pin
Heeut21-Apr-14 22:28
professionalHeeut21-Apr-14 22:28 
QuestionExporting a DataTable to PDF (VB.net) Pin
IshaqSalam8-Dec-13 22:14
IshaqSalam8-Dec-13 22:14 
AnswerRe: Exporting a DataTable to PDF (VB.net) Pin
hongdida9-Dec-13 16:59
hongdida9-Dec-13 16:59 
QuestionNICE ARTICLE Pin
Member 842699112-Jun-13 19:14
Member 842699112-Jun-13 19:14 
AnswerMessage Closed Pin
12-Jun-13 19:15
Member 842699112-Jun-13 19:15 
GeneralMy vote of 5 Pin
Member 842699112-Jun-13 19:13
Member 842699112-Jun-13 19:13 
QuestionHow I can manage table content Pin
Bhavank-SAP6-May-13 1:05
Bhavank-SAP6-May-13 1:05 
Questionmultiple pages based on datatable Pin
pegaxus5-Apr-13 5:03
pegaxus5-Apr-13 5:03 
AnswerRe: multiple pages based on datatable Pin
M.AFTAB.ALAM9-Apr-13 21:32
M.AFTAB.ALAM9-Apr-13 21:32 
QuestionExport unicode Pin
vhdysf10-Mar-13 20:40
vhdysf10-Mar-13 20:40 
GeneralMy vote of 5 Pin
Shahan Ayyub6-Nov-12 23:32
Shahan Ayyub6-Nov-12 23:32 
QuestionTable width Pin
Mike Fed27-Sep-12 10:39
Mike Fed27-Sep-12 10:39 
AnswerRe: Table width Pin
M.AFTAB.ALAM27-Sep-12 21:14
M.AFTAB.ALAM27-Sep-12 21:14 
AnswerRe: Table width Pin
M.AFTAB.ALAM3-Oct-12 20:11
M.AFTAB.ALAM3-Oct-12 20:11 
QuestionPortrait vs Lanscape Pin
Mike Fed25-Sep-12 9:05
Mike Fed25-Sep-12 9:05 
AnswerRe: Portrait vs Lanscape Pin
M.AFTAB.ALAM25-Sep-12 20:16
M.AFTAB.ALAM25-Sep-12 20:16 
GeneralRe: Portrait vs Lanscape Pin
Mike Fed27-Sep-12 9:47
Mike Fed27-Sep-12 9:47 
GeneralGood Project~ can export to PDF with more than 1 pages? Pin
HT Ng23-Jul-12 21:59
HT Ng23-Jul-12 21:59 
GeneralRe: Good Project~ can export to PDF with more than 1 pages? Pin
M.AFTAB.ALAM23-Jul-12 23:50
M.AFTAB.ALAM23-Jul-12 23:50 
GeneralRe: Good Project~ can export to PDF with more than 1 pages? Pin
HT Ng23-Jul-12 23:54
HT Ng23-Jul-12 23:54 
GeneralRe: Good Project~ can export to PDF with more than 1 pages? Pin
M.AFTAB.ALAM24-Jul-12 18:24
M.AFTAB.ALAM24-Jul-12 18:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.