转换为pdf时数据表之间的空间

时间:2014-06-26 13:27:31

标签: asp.net pdf-generation itextsharp

如何在使用PDFWriter生成PDF文档时在数据表之间包含空格?

这是相关的代码段:

public void ExportToPdf(DataTable dt)
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("E://sample2.pdf", FileMode.Create));
    document.Open();
    iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);
    int col = dt.Columns.Count;
    int row1 = dt.Rows.Count;
    int newcol;

    if (col > Convert.ToInt16(txt_columns.Text))
    {
        newcol = Convert.ToInt16(txt_columns.Text);
    }
    else
    {
        newcol = col;
    }

    int k=0, prev=0, dummy=0;
    dummy = newcol;

    for (int num_table = 1, temp = 0; num_table <= ((col / dummy) + 1); num_table++, temp++)
    {
        if (newcol > 0)
        {
            PdfPTable table = new PdfPTable(newcol);
            PdfPRow row = null;
            float[] widths = new float[newcol];
            for (int i = 0; i < newcol; i++)
            {
                widths[i] = 4f;
            }

            table.SetWidths(widths);
            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Products"));
            cell.Colspan = newcol;
            int j = 1;
            foreach (DataColumn c in dt.Columns)
            {
                if (j > temp * dummy && j <= num_table * dummy)
                {
                    table.AddCell(new Phrase(c.ColumnName, font5));
                }
                j++;
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    for (k=prev; k < ((num_table * dummy > col) ? col : (num_table * dummy)); k++)
                    {
                        table.AddCell(new Phrase(r[k].ToString(), font5));
                    }
                }
            }
            prev = k;

            if (newcol > (col - (num_table * newcol)))
            {
                newcol = (col - (num_table * newcol));
            }
            document.Add(table);
        }
        // need code for gap here
    }
    document.Close();
}

最后需要空间。海报可能会使用开源iText库来生成PDF文档。

谢谢!

1 个答案:

答案 0 :(得分:0)

添加“空间”有不同的方法。在表格的上下文中,您可以使用以下内容:

table.SpacingBefore = 5;
table.SpacingAfter = 5;

第一行在表格之前添加了5pts的空格。第二行在表格之后增加了5个字位。

您还可以添加换行符。有不同的方法:

document.Add(Chunk.NEWLINE); // the height of the newline will depend on the leading
document.Add(new Paragraph("\n")); // you can define a leading for a `Paragraph`; by default it will be 16pt
...

可能还有其他解决方案,但请尝试以上解决方案,让我们知道哪种方案最适合您。