我有一个PDF文件,其中有一个动态表格,我想在现有的PDF中动态地添加另一个表格到该表格下方。
有没有办法在现有表格完成后的特定位置添加表格(该位置不在文档末尾)?
如何添加?请建议一些好的方法。
如下图所示。
谢谢。
有没有办法在现有表格完成后的特定位置添加表格(该位置不在文档末尾)?
如何添加?请建议一些好的方法。
如下图所示。
谢谢。
目前最简单的方法是创建一个新的PDF文件,并将所需的表格放置在所需位置,然后将其盖在现有的PDF文件上。可以使用代码(例如PdfStamper
类)来完成此操作,但也有独立工具,如pdftk
等。不要认为这是“编辑”PDF文件,而是将新内容放在原始文件之上。
pdftk original.pdf stamp newtable.pdf output combined.pdf
<table>
标记一样的东西。有一个实际PDF的示例将非常有帮助。PDF的图像不同于PDF本身。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();
}
}
示例数据表:
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;
}