Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add table into existing PDF using iTExtsharp

I have one PDF in that there is one table that table is dynamic and I want to add another table below to that table dynamically in my existing PDF.

Is there any way to add the table in existing PDF at specific place that existing table(that is not at the end of document) is completed then I want to add my table.

How can I add? Please suggest me some good way.

As you can see below image.

enter image description here

Thanks,

like image 820
Tushar Maru Avatar asked Feb 24 '13 13:02

Tushar Maru


2 Answers

By far the easiest way to do this is to create a new PDF with the desired table at the desired location, then stamp it onto the existing PDF. This can be done in code using (for example) the PdfStamper class, but there are also standalone tools such as pdftk and many others. Don't think of this as "editing" a PDF, think of it as dropping something new on top of the original.

pdftk original.pdf stamp newtable.pdf output combined.pdf

The really interesting and potentially difficult part was addressed by @mkl's original question - how do you determine the correct position of the new table. If you can come up with a geometric rule, then you are in good shape. If this involves any parsing of the original file, you should be aware that something as (seemingly) simple as determining the number of rows in the existing table can sometimes be extremely difficult. In all likelihood, there is noting like an html <table> tag buried in the content stream. Having an example of an actual PDF would be very helpful. An image of the PDF is not the same thing.

To give you some background information, parsing the layout of a PDF is easy, that's what PDF readers do. Parsing the content of a PDF is completely different and much harder. Just as an example, the PDF image you posted could be drawn from top to bottom, or the headers and footers could be drawn first followed by all the bold face items, followed by the plain faced text. Just because two things are next to each other in the physical layout does not mean they are next to each other in the file structure, the object tree, or the content stream. It's a vector graphic not a text file or a bitmap. PDFs are not designed to be editable unless the software that creates it specifically provides clues as to how the content is to be edited. There are a lot of things that seem like they should be easy, but once you understand how a PDF is built, it makes sense that it's difficult. I'm not saying this to discourage you, just so that you appreciate the magnitude of the task. If you can trace down the source document that this PDF was created from, I guarantee you will have more success with less frustration.

like image 170
James Duvall Avatar answered Oct 03 '22 05:10

James Duvall


using iTextSharp.text;
using iTextSharp.text.pdf;

/// Function which will create pdf document and save in the server folder

private void ExportDataToPDFTable()
    {
      Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
         try
          {
           string pdfFilePath = Server.MapPath(".") + "/pdf/myPdf.pdf";
           //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
           PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));

           doc.Open();//Open Document to write

           Font font8 = FontFactory.GetFont("ARIAL", 7);

           //Write some content
            Paragraph paragraph = new Paragraph("Using ITextsharp I am going to show how to create simple table in PDF document ");

            DataTable dt = GetDataTable();

            if (dt != null)
                {
                 //Craete instance of the pdf table and set the number of column in that table
                 PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                 PdfPCell PdfPCell = null;


                 //Add Header of the pdf table
                 PdfPCell = new PdfPCell(new Phrase(new Chunk("ID", font8)));
                 PdfTable.AddCell(PdfPCell);

                 PdfPCell = new PdfPCell(new Phrase(new Chunk("Name", font8)));
                 PdfTable.AddCell(PdfPCell);


                 //How add the data from datatable to pdf table
                 for (int rows = 0; rows < dt.Rows.Count; rows++)
                    {
                     for (int column = 0; column < dt.Columns.Count; column++)
                         {
                           PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                            PdfTable.AddCell(PdfPCell);
                            }
                        }

                        PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table

                        doc.Add(paragraph);// add paragraph to the document
                        doc.Add(PdfTable); // add pdf table to the document

                    }

                }
                catch (DocumentException docEx)
                {
                    //handle pdf document exception if any
                }
                catch (IOException ioEx)
                {
                    // handle IO exception
                }
                catch (Exception ex)
                {
                    // ahndle other exception if occurs
                }
                finally
                {
                    //Close document and writer
                    doc.Close();

       }
 }

Sample Datatable:

private DataTable GetDataTable()
    {
        // Create an object of DataTable class
        DataTable dataTable = new DataTable("MyDataTable");//Create ID DataColumn
        DataColumn dataColumn_ID = new DataColumn("ID", typeof(Int32));
        dataTable.Columns.Add(dataColumn_ID);//Create another DataColumn Name
        DataColumn dataColumn_Name = new DataColumn("Name", typeof(string));
        dataTable.Columns.Add(dataColumn_Name);
        //Now Add some row to newly created dataTable
        DataRow dataRow;for (int i = 0; i < 5; i++)
        {
            dataRow = dataTable.NewRow();
            // Important you have create New row
            dataRow["ID"] = i;dataRow["Name"] = "Some Text " + i.ToString();
            dataTable.Rows.Add(dataRow);
        }
        dataTable.AcceptChanges();
        return dataTable;
    }
like image 31
coder Avatar answered Oct 03 '22 05:10

coder