使用 iTextSharp 将数据添加到 C# 中的 pdf 文件

本文关键字:中的 pdf 文件 添加 iTextSharp 数据 使用 | 更新日期: 2023-09-27 17:56:51

>我有一个方法可以转换pdf格式的数据表。在pdf中,我将有一个表格。现在我想做的是在该表上方添加一些数据。如何在 C# 中做到这一点?

我的代码如下。

    public void ExportToPdf(DataTable dt, string htmlFilepath)
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(htmlFilepath, FileMode.Create));
        document.Open();
        iTextSharp.text.Font fontbold = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10);
        iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 7);

        PdfPTable table = new PdfPTable(dt.Columns.Count);
        PdfPRow row = null;
        float[] widths = new float[] { 4f, 4f, 4f ,4f ,4f ,4f};
        table.SetWidths(widths);
        table.WidthPercentage = 100;
        int iCol = 0;
        string colname = "";
        PdfPCell cell = new PdfPCell(new Phrase("Products"));
        cell.Colspan = dt.Columns.Count;
        foreach (DataColumn c in dt.Columns)
        {
            table.AddCell(new Phrase(c.ColumnName, fontbold));
        }
        foreach (DataRow r in dt.Rows)
        {
            if (dt.Rows.Count > 0)
            {
                table.AddCell(new Phrase(r[0].ToString(), font5));
                table.AddCell(new Phrase(r[1].ToString(), font5));
                table.AddCell(new Phrase(r[2].ToString(), font5));
                table.AddCell(new Phrase(r[3].ToString(), font5));
                table.AddCell(new Phrase(r[4].ToString(), font5));
                table.AddCell(new Phrase(r[5].ToString(), font5));
            }
        } document.Add(table);
        document.Close();
    }

使用 iTextSharp 将数据添加到 C# 中的 pdf 文件

您可以使用

"段落"添加数据,如下所示

Chunk ch= new Chunk("Here is your data");
Phrase ph = new Phrase(beginning);
Paragraph p = new Paragraph();
p.Add(ph);
document.Add(p);//this line must be added before you add table to document.

现在请注意,正如我上面提到的。 段落对象必须在添加表格之前添加到文档中,因为您希望此数据位于表格上方。