Using ITextSharp to create basic PDF page from item property


  1. Setting up Word Automation Services for SharePoint 2013
  2. Setting up PowerPoint Automation Services for SharePoint 2013
  3. Converting a Library’s Word Documents to PDF
  4. Converting a Library’s PowerPoint documents to PDF
  5. Using ITextSharp to Merge PDF’s into one
  6. Using ITextSharp to create basic PDF page from item property

This is the final post in this series, I’ve shown you how to set up Word and PowerPoint Automation, how to convert Word and PowerPoint to PDF, and in the last blog post I showed you how to merge all your pdf’s into one. This post is to demonstrate how to create a PDF page using ITextSharp. ITextSharp is a port of the iText open source java library for PDF generation written entirely in C# for the .NET platform. http://itextpdf.com. Please see my previous blog on how to add the itextsharp dll to the Visual Studio project.

In this demonstration, I will read in the first item of a list, and then copy all the visible columns by creating a table like structure which will be saved in my document library as a PDF file. The purpose of this post is to introduce to you what you can do with ITextSharp, there is plenty I don’t know about ITextSharp, and I’ve only learnt enough to solve my proof of concept I was doing for a client. If you are interested in ITextSharp, I’d recommend you look up books by Bruno Lowagie.

First, I have created a contact list, and added a single person to this list.

Continuing with my previous Visual Studio solution, I have added a new visual web part. It simply has a text box for the user to enter the list which it will take the first item from and convert to PDF in the Shared document library, and a button that will fire off the event to convert the item.

Below is the code and comments explaining what is happening at different stages of the code.

//Will require these using statements
using iTextSharp.text;
using itextSharp.text.pdf;

protected void btnlistItemToPDF_Click(object sender, EventArgs e)
{
  //Get Current Web context and get Document and user chosen list.
  var web = SPContext.Current.Web;
  SPList doclibrary = web.Lists.TryGetList("Documents");
  SPList list = web.Lists.TryGetList(txtList.text);
 
  //Check if lists are not null, then call code to convert.
  if(doclibrary == null || list == null)
  {
     ListItemToConvertoToPDF(list, doclibrary);
  }
}

private void ListItemToConvertoToPDF(SPList list, SPList doclibrary)
{
   if (list.ItemCount == 0)
        throw new Exception("Unfortunately there are not any items in your list to convert");
 
   Byte[] result = null;
   String returnString = "";

   //Perform Query to return 1 item.
   SPQuery query = new SPQuery();
   query.RowLimit = 1;
   query.ViewFields = list.DefaultView.ViewFields.SchemaXml;

   try
   {
      var collection = list.GetItems(query);
      SPListItem item = collection[0];

      //Get Title name, using default Guid for Title, to create a filename.
      var filename = item[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")] + ".pdf";

      //Creating the Document in memory first.
      using(MemoryStream ms = new MemoryStream())
      {
       //Using the ItextSharp Document
         using(Document document = new Document())
         {
           //Using the ItextSharp PdfWriter to create an instance of the document using the memory stream.
           PdfWriter.GetInstance(document, ms).SetFullCompression();

           //Open the document otherwise you won't be able to add to it.
           document.Open();

           //Create a PDF table with Two Columns
           PdfPTable table = new PdfPTable(2);

           //Create the first Cell, make it span across 2 columns.
           PdfPCell cell = new PdfPCell(new Phrase("Contact Details"));
           cell.Colspan = 2;
           cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right

           //Add the cell to the table.
           table.AddCell(cell);

           //Loop through all the fields in the collection.
           foreach (SPField f in collection.Fields)
           {
               //Obtain the value of the given field.
               var value = item[f.Id];
               //We are only showing if there is a value and the field/column isn't hidden.
               if (value != null && !f.Hidden)
               {
                  //Create a cell and just put the title of the column in it.
                  table.AddCell(f.Title);
                  //Depending on the type of file, depends how we want to add it to the pdf.
                  switch (f.TypeAsString)
                  {
                         //URL to display within the PDF as a URL.
                         case "URL":
                           //Get the field value as a SPFieldURLValue
                           SPFieldUrlValue urlV = new SPFieldUrlValue(value.ToString());
                           //create a new Cell.
                           cell = new PdfPCell();
                           //Use Chunk to add the text
                           var chunk = new Chunk(urlV.Description);
                           //A chunk can have an Anchor tag added to it.
                           chunk.SetAnchor(urlV.Url);
                           //add chunk to the cell.
                           cell.AddElement(chunk);
                           //add the cell to the table. Because this is the second cell added to the table, it is aware that it's the right cell.
                           table.AddCell(cell);
                           break;

                         //Date Time to display a valid date time format.
                         case "DateTime":
                           //Parse the date time to full date and time.
                           var dateV = DateTime.Parse(value.ToString()).ToString("R");
                           //add the cell to the table.
                           table.AddCell(dateV);
                           break;
 
                        //Default captures all other type of field types, numbers, text, etc.
                        default:
                           table.AddCell(value.ToString());
                           break;
                        }
                     }
                  }
                  //Add the table to the document and close the document.
                 document.Add(table);
                 document.Close();
              }
             //Convert the final memory stream into a byte array.
             result = ms.ToArray();
          }
 
          //Write file to document library
          SPFolder rootFolder = doclibrary.RootFolder;
          SPFile newFile = rootFolder.Files.Add(filename, result, true);
      }
      catch (Exception Ex)
      {
           Throw new Exception("Error trying to convert item to pdf. Message: " + Ex.Message);
      }
 }

Once the code is deployed, web part added to the page and ran, I get a pdf file named after the contact’s surname.

If I open the file, I have a table like structure within my PDF displaying all the columns I expected. I’m not going to win any awards for style, however check out the resource link at the bottom of this post to learn ways of jazzing up your tables.

Link to Sample code : OneDrive

 

Resources: http://www.mikesdotnetting.com/article/86/itextsharp-introducing-tables

Advertisements