C# 使用 iTExtsharp 将表格添加到现有 PDF 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15052202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:53:49  来源:igfitidea点击:

Add table into existing PDF using iTExtsharp

c#asp.netpdfpdf-generationitextsharp

提问by Tushar Maru

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.

我有一个 PDF,因为有一个表格是动态的,我想在我现有的 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.

有什么方法可以在现有表格(不在文档末尾)完成的特定位置在现有 PDF 中添加表格,然后我想添加我的表格。

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

我该如何添加?请给我推荐一些好方法。

As you can see below image.

如下图所示。

enter image description here

在此处输入图片说明

Thanks,

谢谢,

回答by coder

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;
    }

回答by James Duvall

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 PdfStamperclass, but there are also standalone tools such as pdftkand many others. Don't think of this as "editing" a PDF, think of it as dropping something new on top of the original.

到目前为止,最简单的方法是在所需位置创建一个带有所需表格的新 PDF,然后将其标记到现有 PDF 上。这可以使用(例如)PdfStamper类在代码中完成,但也有独立的工具,例如pdftk和许多其他工具。不要将其视为“编辑”PDF,而是将其视为在原始文件之上添加新内容。

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.

@mkl 的原始问题解决了真正有趣且潜在困难的部分 - 如何确定新表的正确位置。如果你能提出几何规则,那么你的状态就很好。如果这涉及对原始文件的任何解析,您应该意识到,像确定现有表中的行数这样(看似)简单的事情有时会非常困难。很有可能,<table>内容流中隐藏着像 html标签这样的注释。有一个实际 PDF 的例子会非常有帮助。PDF 的图像不是一回事。

To give you some background information, parsing the layoutof a PDF is easy, that's what PDF readers do. Parsing the contentof 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 shouldbe 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.

为您提供一些背景信息,解析PDF的布局很容易,这就是 PDF 阅读器所做的。解析PDF的内容是完全不同的,而且要困难得多。举个例子,您发布的 PDF 图像可以从上到下绘制,或者可以先绘制页眉和页脚,然后是所有粗体项目,然后是普通文本。仅仅因为两个事物在物理布局中彼此相邻并不意味着它们在文件结构、对象树或内容流中彼此相邻。它是矢量图形,而不是文本文件或位图。PDF 并非设计为可编辑的,除非创建它的软件专门提供有关如何编辑内容的线索。有很多事情看起来像他们应该很容易,但是一旦您了解了 PDF 的构建方式,就可以理解这很困难。我这样说并不是为了让你气馁,只是为了让你体会到任务的艰巨性。如果您可以追踪创建此 PDF 的源文档,我保证您将获得更多成功,减少挫折。