Create Grids in PDF using Free API in C#

Introduction

A grid or a table is a great way to present data into groups. Manual generation of grids can appear as a boring task one could rather prefer to be automated. As a part of this article, I’ll dive into details of automatic grid creation and generation and show how to create perfect grids using a few small pieces of C# code and free .NET PDF component as the main tool.

The component used for generating grids is a simple and tiny class library that helps programmers to process PDF files on .NET platform. A grid in the library is represented by the PdfGrid class, helping to automate the creation of tabulated data in PDF. Its rows are represented by the PdfGridRow objects and cells by the PdfGirdCell objects. Each of them has a Style property that allows us to format the gird elements easily.

The following sections will demonstrate:

  • How to create a simple grid
  • How to merge cells, format text and cells in grid
  • How to dynamically create a grid using the data exported from database

Part 1. Simple grid with uniform cells

Let’s create the document containing a simple grid with uniform cells, using the code below.


//create a pdf object, add a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//create a 2x4 gird object 
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
grid.Columns.Add(4);
//set column width
foreach (PdfGridColumn col in grid.Columns)
{
    col.Width = 60f;
}
//insert data
for (int i = 0; i < grid.Columns.Count; i++)
{
    row1.Cells[i].Value = String.Format("col{0}", i+1);
    row2.Cells[i].Value = String.Format("{0}", i + 1);
}
//draw grid on pdf page
PdfLayoutResult result = grid.Draw(page, new PointF(10, 10));
//save document
doc.SaveToFile("Simple_Grid.pdf");

2017090401

Part 2. Grid with formatted cells, row spans and column spans

When creating a grid in a real PDF report, you may need to change the grid layout by merging certain cells or emphasize the important information by applying styles. The following code snippets will show you how to create an eye-catching and meaningful grid.


//create a pdf object, add a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//create a 4x4 gird object 
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
PdfGridRow row3 = grid.Rows.Add();
PdfGridRow row4 = grid.Rows.Add();
grid.Columns.Add(4);
//set column width
foreach (PdfGridColumn col in grid.Columns)
{
    col.Width = 60f;
}
//insert data
row1.Cells[0].Value = "Orders and Payments";
row2.Cells[0].Value = "Order";
row2.Cells[1].Value = "Date";
row2.Cells[2].Value = "Customer";
row2.Cells[3].Value = "Paid";
row3.Cells[0].Value = "00223";
row3.Cells[1].Value = "02/06/2016";
row3.Cells[2].Value = "JDX Co., Ltd";           
row3.Cells[3].Value = "Yes";
row4.Cells[0].Value = "00224";
row4.Cells[1].Value = "03/06/2016";
row4.Cells[3].Value = "No";
//horizontally and vertically merge certain cells through ColumnSpan and RowSpan
row1.Cells[0].ColumnSpan = 4;
row3.Cells[2].RowSpan = 2;
//align text
row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Justify, PdfVerticalAlignment.Middle);
//set background color of cells
row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Gray;
row3.Cells[3].Style.BackgroundBrush = PdfBrushes.Green;
row4.Cells[3].Style.BackgroundBrush = PdfBrushes.MediumVioletRed;
//set font style
row1.Style.Font = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Bold));
row2.Style.Font = new PdfTrueTypeFont(new Font("Aril", 8f));
row3.Style.Font = new PdfTrueTypeFont(new Font("Aril", 8f));
row4.Style.Font = new PdfTrueTypeFont(new Font("Aril", 8f));
//format cells border
PdfBorders borders = new PdfBorders();
borders.All = new PdfPen(Color.Black, 0.1f);
foreach (PdfGridRow pgr in grid.Rows)
{
    foreach (PdfGridCell pgc in pgr.Cells)
    {
        pgc.Style.Borders = borders;
    }
}
//draw grid on pdf page
PdfLayoutResult result = grid.Draw(page, new PointF(10, 10));
//save document
doc.SaveToFile("Merge_Format_Cells.pdf");

2017090402

Part 3. Dynamically generate a grid from Access data

Often your application will pull data from a database and store it in the form of a DataTable. You may wish to easily insert this data into your document as a grid and quickly apply formatting to the whole grid. This part will demonstrate how to dynamically create a grid from Access data.

The MDB file looks as follows:
2017090403


//create a pdf document object, insert a page
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
//initialize a pdf grid
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(2, 2, 2, 2);
//export data from database to grid
DataTable dataTable = new DataTable(); 
DataTable newTable = new DataTable();
using (OleDbConnection conn = new OleDbConnection())
{
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=demo.mdb";
    OleDbCommand command = new OleDbCommand();
    command.CommandText
        = " select Name, '' as Flag, Capital, Continent, Area, Population, Flag as FlagData from country ";
    command.Connection = conn;
    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command))
    {
        dataAdapter.Fill(dataTable);
        dataAdapter.Fill(newTable);                 
        newTable.Columns.RemoveAt(newTable.Columns.Count - 1); 
        grid.DataSource = newTable;//export data from data table to grid
    }
}
//transfer binary flag data as images and insert them to grid cells
for (int i = 0; i < dataTable.Rows.Count; i++)
{
    PdfGridCellTextAndStyleList lst = new PdfGridCellTextAndStyleList();
    PdfGridCellTextAndStyle textAndStyle = new PdfGridCellTextAndStyle();
    byte[] imageData = dataTable.Rows[i][dataTable.Columns.Count - 1] as byte[];
    using (MemoryStream ms = new MemoryStream(imageData))
    {
        textAndStyle.Image = PdfImage.FromStream(ms);
        textAndStyle.ImageSize = new SizeF(10f, 10f);
        textAndStyle.ContentAlign = PdfGridCellContentAndAlign.Center;
        lst.List.Add(textAndStyle);
        grid.Rows[i].Cells[1].Value = lst;
        lst = null;
    }
}
//format header
grid.Headers[0].Style.BackgroundBrush = PdfBrushes.Gray;
grid.Headers[0].Style.Font= new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Bold));
foreach (PdfGridCell cell in grid.Headers[0].Cells)
{
    cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Center,PdfVerticalAlignment.Middle);     
    cell.Style.TextBrush = PdfBrushes.White;
}
//set column width
foreach (PdfGridColumn col in grid.Columns)
{
    col.Width = 80f;          
}         
//horizontally and vertically align text
for (int rowIndex = 0; rowIndex < grid.Rows.Count; rowIndex++)
{
    for (int i = 0; i < grid.Rows[rowIndex].Cells.Count; i++)
    {
        grid.Rows[rowIndex].Cells[i].StringFormat= new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
    }
    //apply alternate style for odd and even rows
    if (rowIndex % 2 == 0)
    {
        grid.Rows[rowIndex].Style.BackgroundBrush = PdfBrushes.LightYellow;
    }
    else
        grid.Rows[rowIndex].Style.BackgroundBrush = PdfBrushes.LightBlue;
}
//draw grid on pdf page
PdfLayoutResult result = grid.Draw(page, new PointF(10, 10));
//save document
doc.SaveToFile("Generate_Grid_From_Database.pdf");

2017090404

Advertisements

Add SmartArt to Slide in C#

PowerPoint SmartArt is a special type of graphic object that gives you the ability to construct fancy graphical lists and diagrams in your slide quickly and easily. With just one click, you’re able to create a flow chart, an organization chart or a timeline in slide. This article gives you an example of how to add an organization chart to slide using Spire.Presentation with C#.


//create an instance of Presentation
Presentation ppt = new Presentation();

//set slide size
ppt.SlideSize.Type = SlideSizeType.Screen16x9;

//append an organization chart and specify position and size
ISmartArt smartArt = ppt.Slides[0].Shapes.AppendSmartArt(50, 50, 450, 250, SmartArtLayoutType.OrganizationChart);

//set the style and color of smartart
smartArt.Style = SmartArtStyleType.IntenceEffect;
smartArt.ColorStyle = SmartArtColorType.ColorfulAccentColors3to4;

//remove default notes (represent shape in smartart)
foreach (ISmartArtNode node in smartArt.Nodes)
{
smartArt.Nodes.RemoveNode(node);
}

//add nested shapes to smartart
ISmartArtNode node1 = smartArt.Nodes.AddNode();
ISmartArtNode node1_1 = node1.ChildNodes.AddNode();
ISmartArtNode node1_1_1 = node1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_2 = node1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_3 = node1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_4 = node1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_5 = node1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_6 = node1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_1_1 = node1_1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_1_2 = node1_1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_1_3 = node1_1_1.ChildNodes.AddNode();
ISmartArtNode node1_1_3_1 = node1_1_3.ChildNodes.AddNode();
ISmartArtNode node1_1_3_2 = node1_1_3.ChildNodes.AddNode();
ISmartArtNode node1_1_6_1 = node1_1_6.ChildNodes.AddNode();
ISmartArtNode node1_1_6_2 = node1_1_6.ChildNodes.AddNode();
ISmartArtNode node1_1_6_3 = node1_1_6.ChildNodes.AddNode();

//add text to every shape
node1.TextFrame.Text = "Board of Directors";
node1_1.TextFrame.Text = "General Manager";
node1_1_1.TextFrame.Text = "Supply Department";
node1_1_2.TextFrame.Text = "Sales Department";
node1_1_3.TextFrame.Text = "Productive Department";
node1_1_4.TextFrame.Text = "Finance Department";
node1_1_5.TextFrame.Text = "HR Department";
node1_1_6.TextFrame.Text = "Quality Center";
node1_1_1_1.TextFrame.Text = "Purchase Department";
node1_1_1_2.TextFrame.Text = "Warehouse Manager";
node1_1_1_3.TextFrame.Text = "Logistics Department";
node1_1_3_1.TextFrame.Text = "Production Department";
node1_1_3_2.TextFrame.Text = "Maintenance Department";
node1_1_6_1.TextFrame.Text = "Production Quality Management";
node1_1_6_2.TextFrame.Text = "Production Safety Management";
node1_1_6_3.TextFrame.Text = "Environmental Management";

//save to file
ppt.SaveToFile("output.pptx", FileFormat.Pptx2013);

Output

2017-08-02_163332

Insert Image and Formatted Text in Excel Header or Footer in C#

Excel header or footer, which presents information like page numbers, the creation date, the logo of your company, and even customized text, can be of use in printed worksheets. In this article, you’ll learn how to insert images and formatted text in Excel header or footer in C#.

This solution relies on Spire.XLS, an Excel processing library, which provides a PageSetup class to deal with all page setup settings. Specifically, it contains LeftHeader, CenterHeader, LeftHeaderImage, OddHeaderStringand similar properties that represent header/footer text, image, odd header/footer and even header/footer in Excel. Besides, this component provides some special script commands, which are used to get the dynamic value like page number or format the header or footer text.

Script D
&P The current page number
&N The total number of pages
&D The current data
&T The current time
&G A picture
&A The worksheet name
&F The file name
&B Make text bold
&I Italicize text
&U Underline text
&”font name” Represents a font name, for example, &”Aril”
&font size Represents font size, for example, &12
&K Represents font color, for example, &KFF0000

Insert Image to Header

  //create a word document
Workbook wb = new Workbook();

//get the first worksheet
Worksheet sheet = wb.Worksheets[0];

//load a pic to Image object
Image image = Image.FromFile("company-logo.jpg");

//scale the image
Bitmap bitmap = new Bitmap(image, new Size(image.Width / 4, image.Height / 4));

//insert image to left header
sheet.PageSetup.LeftHeaderImage = bitmap;
sheet.PageSetup.LeftHeader = "&G";

//save the file
wb.SaveToFile("Insert_Text_Footer.xlsx", ExcelVersion.Version2013);

2017-06-26_152908

Insert Formatted Text to Footer

 //create an object of Workbook class   
Workbook wb = new Workbook();

//get the first sheet  
Worksheet sheet = wb.Worksheets[0];

//format a string with script commands and assign it to CenterFooter   
sheet.PageSetup.CenterFooter = "&\"Arial\"&B&12&KFF0000Copyright © 2017 JMD. All Rights Reserved.";

//save the file
wb.SaveToFile("Insert_Text_Footer.xlsx", ExcelVersion.Version2013);

2017-06-26_153656

Convert PPT/PPTX to PNG in C#

It is not uncommon that we may need to convert a PowerPoint file to images or a PDF file in our work. In my previous post, I have introduced how to export PPT/PPTX files as PDFs. This article will introduce how we can convert a PPT/PPTX file into PNGs by using Spire.Presentation in C#.

Here come the code snippets:


using Spire.Presentation;
using System.Drawing;

namespace Conversion
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of Presentation class
            Presentation presentation = new Presentation();

            //Load a PowerPoint document
            presentation.LoadFromFile("Template.pptx");

            //Traverse each slide in PowerPoint and save as png image
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                Image image = presentation.Slides[i].SaveAsImage();
                String fileName = String.Format("Result-{0}.png", i);
                image.Save(fileName);
            }
        }
    }
}

Output

2017-05-08_152546

Compress PDF Files in C#

Knowing how to reduce PDF file size can save you from a number of different frustrating hold-ups—like trying to send a large file via email, only to get the annoying popup telling us the file is too large to send. This post provides two solutions in C# to make PDFs smaller.

Before start, you should download .NET PDF component and add the dll file as reference to your Visual Studio.

Reducing PDF file size by compressing content

Content compression involves removing all extra space characters, inserting a single repeat character to indicate a string of repeated characters and substituting smaller bit strings for frequently occurring characters.

//Creates a new PDF document
PdfDocument doc = new PdfDocument();
//Load file
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\example.pdf");
//Disables the incremental update
doc.FileInfo.IncrementalUpdate = false;
//Sets the compression level to best
doc.CompressionLevel = PdfCompressionLevel.Best;
//Save file
doc.SaveToFile("Compressed.pdf");
doc.Close();

Reducing PDF file size by shrinking all images

For PDF files that contain many images, compressing/changing the quality of them all can make a noticeable difference in making your PDF smaller.

//Creates a new PDF document
PdfDocument pdf = new PdfDocument();
//Load file
pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\Image_PDF.pdf");
pdf.FileInfo.IncrementalUpdate = false;

foreach (PdfPageBase page in pdf.Pages)
{
    Image[] images = page.ExtractImages();
    if (images != null && images.Length > 0)
    {
        for (int j = 0; j < images.Length; j++)
        {
            Image image = images[j];
            PdfBitmap bp = new PdfBitmap(image);
            bp.Quality = 20; //Reduces the quality of the image
            page.ReplaceImage(j, bp);
        }
    }
}
//Save file
pdf.SaveToFile("image_compressed.pdf");