在创建表格时设置字体大小

时间:2019-01-31 16:54:29

标签: itext

我已使用ITextSharp(使用Excel文档中的数据)在.pdf文档中成功创建了表格。我已经设置了.pdf表的列宽,因此它与Excel文档相同。

但是,当我查看.pdf文档时,其布局与Excel文档的布局不匹配。

我认为问题出在创建表时使用的字体样式/大小。 我已经在网上搜索了如何更改.pdf中创建的表格的默认字体样式/大小,但是我尚不清楚它的完成方式(我从未使用过字体)。

这就是我的意思。

private void WritePDFTable(ExcelWorksheet sheet, Document doc)
    {
        var start = sheet.Dimension.Start;
        var end = sheet.Dimension.End;

        float[] ColumnWidths = new float[end.Column];
        float TotalWidth = 0f;
        int row;
        int column;

        if (sheet.Dimension != null)    // make sure the sheet isn't empty
        {
            if (end.Column > 0) // create a table to hold the columns in the passed worksheet
            {
                for (column = start.Column; column <= end.Column; column++)
                {
                    ColumnWidths[column - 1] = (float)(sheet.Column(column).Width);
                    TotalWidth = TotalWidth + (float)(sheet.Column(column).Width);
                }

                    // creat a pdf table with  the same # of columns as were found in the workbook
                    PdfPTable PdfPTable = new PdfPTable(end.Column);

                    // set absolute width of the columns
                PdfPTable.SetWidths(ColumnWidths);  

                PdfPTable.SpacingBefore = 20f;
                PdfPTable.SpacingAfter = 30f;


                for (row = start.Row; row <= end.Row;row++)                    {
                    for (column = start.Column; column <= end.Column; column++)                         {
                        PdfPTable.AddCell(sheet.Cells[row, column].Text);
                    }
                }
                doc.Add(PdfPTable);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

如果您使用所需的Font font值定义fontSize,例如像这样

Font font = new Font(Font.FontFamily.HELVETICA, fontSize);

或这个

Font font = FontFactory.GetFont("Arial", fontSize, Font.NORMAL, BaseColor.BLACK);

(使用iTextSharp Font类,而不是Windows API Font类),只需替换

PdfPTable.AddCell(sheet.Cells[row, column].Text);

通过

PdfPTable.AddCell(new Phrase(sheet.Cells[row, column].Text, font));

获取具有所需大小的文本的单元格。

相关问题