使用iTextSharp和C#

时间:2017-03-14 14:09:26

标签: c# .net pdf datagridview itext

我已使用iTextSharp将DataGridView数据导出为PDF。列宽都完全相同,并且某些标题列字被错误地分解。我尝试做的是自动调整标题列宽度以适应每个标题文本长度。

这是我的代码:

 PdfPTable table = new PdfPTable(dgv.Columns.Count);
        for (int j = 0; j < dgv.Columns.Count; j++)
        {
            Font font = new Font(Font.FontFamily.COURIER, 14, Font.ITALIC);
            font.Color = BaseColor.BLUE;

            if (j == 0)
            {
                Phrase p1 = new Phrase(dgv.Columns[j].HeaderText, font);
                table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.WidthPercentage = 100;
                table.AddCell(p1);
            }

            else
            {
                string header = dgv.Columns[j].HeaderText;
                header = Regex.Replace(dgv.Columns[j].HeaderText, "[A-Z]", " $0").Trim();
                Phrase p = new Phrase(header, font);
                table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                table.WidthPercentage = 100;
                table.AddCell(p);
            }
        }
        table.HeaderRows = 1;

        for (int i = 0; i < dgv.Rows.Count; i++)
            for (int k = 0; k < dgv.Columns.Count; k++)
                if (dgv[k, i].Value != null)
                {
                    Phrase p = new Phrase(dgv[k, i].Value.ToString());
                    table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(p);
                }


        doc.Add(table);

这是PDF输出:

enter image description here

1 个答案:

答案 0 :(得分:5)

要自动调整列大小,您需要自己计算标题字符串的宽度,然后设置表格列宽。

首先是一个简单的辅助方法,用于从任意字符串集合中获取列宽:

public float[] GetHeaderWidths(Font font, params string[] headers)
{ 
    var total = 0;
    var columns = headers.Length;
    var widths = new int[columns];
    for (var i = 0; i < columns; ++i)
    {
        var w = font.GetCalculatedBaseFont(true).GetWidth(headers[i]);
        total += w;
        widths[i] = w;
    }
    var result = new float[columns];
    for (var i = 0; i < columns; ++i) 
    {
        result[i] = (float)widths[i] / total * 100;
    }
    return result;
}

然后设置表格列宽:

string[] headers = new string[]
{ 
    "Order Id", "Customer Id", "Customer Name", "Product Id",
    "Product Description", "Quantity", "Product Received"
};
Font font = new Font(Font.FontFamily.COURIER, 14, Font.ITALIC);
font.Color = BaseColor.BLUE;
var table = new PdfPTable(headers.Length) { WidthPercentage = 100 };
table.SetWidths(GetHeaderWidths(font, headers));

using (var stream = new MemoryStream())
{
    using (var document = new Document(PageSize.A4.Rotate()))
    {
        PdfWriter.GetInstance(document, stream);
        document.Open();
        for (int i = 0; i < headers.Length; ++i)
        {
            table.AddCell(new PdfPCell(new Phrase(headers[i], font)));
        }
        document.Add(table);
    }
    File.WriteAllBytes(OUT_FILE, stream.ToArray());
}

输出:

enter image description here