为什么我的表格没有使用iTextSharp在我的PDF文件上生成?

时间:2015-04-09 20:53:00

标签: c# pdf-generation itextsharp

我试图在我生成的PDF文件中添加一个表格。我可以直接添加东西""但是希望将各个段落或短语放在表格单元格中,以使所有内容都很好地对齐。

以下代码应添加三个段落" free-form"首先,然后在表中相同的三个。但是,只有前三个显示 - 表格无处可见。这是代码:

try
{
    using (var ms = new MemoryStream())
    {    
        using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))
        {
            using (var writer = PdfWriter.GetInstance(doc, ms))
            {
                doc.Open();

                var titleFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
                var docTitle = new Paragraph("UCSC Direct - Direct Payment Form", titleFont);
                doc.Add(docTitle);

                var subtitleFont = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
                var subTitle = new Paragraph("(not to be used for reimbursement of services)", subtitleFont);
                doc.Add(subTitle);

                var importantNoticeFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
                var importantNotice = new Paragraph("Important: Form must be filled out in Adobe Reader or Acrobat Professional 8.1 or above. To save completed forms, Acrobat Professional is required. For technical and accessibility assistance, contact the Campus Controller's Office.", importantNoticeFont);
                importantNotice.Leading = 0;
                importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings
                importantNotice.ExtraParagraphSpace = 4; // ? test this....
                doc.Add(importantNotice);

                // Add a table
                PdfPTable table = new PdfPTable(10); // the arg is the number of columns

                // Row 1
                PdfPCell cell = new PdfPCell(docTitle);
                cell.Colspan = 3;
                cell.BorderWidth = 0;
                //cell.BorderColor = BaseColor.WHITE; <= this works for me, but if background is something other than white, it wouldn't
                cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                table.AddCell(cell);

                // Row 2
                PdfPCell cellCaveat = new PdfPCell(subTitle);
                cellCaveat.Colspan = 2;
                cellCaveat.BorderWidth = 0;
                table.AddCell(cellCaveat);

                // Row 3
                PdfPCell cellImportantNote = new PdfPCell(importantNotice);
                cellImportantNote.Colspan = 5;
                cellImportantNote.BorderWidth = 0;
                table.AddCell(importantNotice);

                doc.Add(table);

                doc.Close();
            }
            var bytes = ms.ToArray();
            String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
            PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
            var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
            File.WriteAllBytes(testFile, bytes);
            MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
        }
    }
}
catch (DocumentException dex)
{
    throw (dex);
}
catch (IOException ioex)
{
    throw (ioex);
}
catch (Exception ex)
{
    String exMsg = ex.Message;
    MessageBox.Show(String.Format("Boo-boo!: {0}", ex.Message));
}

为什么我的无边框表不可见或不存在?

更新

根据Bruno的答案,并将其应用于我真正需要的输出,这有效:

using (var ms = new MemoryStream())
{
    using (var doc = new Document(PageSize.A4, 50, 50, 25, 25))                     {
        //Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms))
        {

            //Open the document for writing
            doc.Open();

            // Mimic the appearance of Direct_Payment.pdf
            var courierBold11Font = FontFactory.GetFont(FontFactory.COURIER_BOLD, 11, BaseColor.BLACK);
            var docTitle = new Paragraph("UCSC - Direct Payment Form", courierBold11Font);
            doc.Add(docTitle);

            var timesRoman9Font = FontFactory.GetFont("Times Roman", 9, BaseColor.BLACK);
            var subTitle = new Paragraph("(not to be used for reimbursement of services)", timesRoman9Font);
            doc.Add(subTitle);

            var courier9RedFont = FontFactory.GetFont("Courier", 9, BaseColor.RED);
            var importantNotice = new Paragraph("Important: Form must be filled out in Adobe Reader or Acrobat Professional 8.1 or above. To save completed forms, Acrobat Professional is required. For technical and accessibility assistance, contact the Campus Controller's Office.", courier9RedFont);
            importantNotice.Leading = 0;
            importantNotice.MultipliedLeading = 0.9F; // reduce the width between lines in the paragraph with these two settings

            // Add a table
            PdfPTable table = new PdfPTable(1);
            PdfPCell cellImportantNote = new PdfPCell(importantNotice);
            cellImportantNote.BorderWidth = PdfPCell.NO_BORDER;
            table.WidthPercentage = 50;
            table.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(cellImportantNote);
            doc.Add(table);

            doc.Close();
        }
        var bytes = ms.ToArray();
        String PDFTestOutputFileName = String.Format("iTextSharp_{0}.pdf", DateTime.Now.ToShortTimeString());
        PDFTestOutputFileName = PDFTestOutputFileName.Replace(":", "_");
        var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), PDFTestOutputFileName);
        File.WriteAllBytes(testFile, bytes);
        MessageBox.Show(String.Format("{0} written", PDFTestOutputFileName));
    }
}

1 个答案:

答案 0 :(得分:1)

请查看SimpleTable7示例,并将Java代码与您的[?]代码进行比较:

这部分是相关的:

PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.setColspan(5);
cellImportantNote.setBorder(PdfPCell.NO_BORDER);
table.addCell(cellImportantNote);

如果我将您的[?]代码转换为Java,那么您将拥有:

PdfPCell cellImportantNote = new PdfPCell(importantNotice);
cellImportantNote.setColspan(5);
cellImportantNote.setBorder(PdfPCell.NO_BORDER);
table.addCell(importantNotice);

你看到了区别吗?您创建了一个cellImportantNote实例,但您无法在任何地方使用它。您可以添加cellImportantNote段落。

,而不是将importantNotice添加到表格中

这意味着您要创建一个包含10列的表,其中单行 仅采用6个单元(因为您有1个单元格,其中包含colspan 3, 1个细胞用colspan 2和1个细胞用colspan 1)。

默认情况下,iText不会渲染任何不完整的行,并且由于您的表格没有任何完整的行,因此表格不会被渲染。

如果查看生成的PDF simple_table7.pdf,您会注意到我还添加了第二个表格。此表只有三列,但它看起来与您构造的表相同。我没有不正确地使用colspan功能,而是为三列定义了相对宽度:

table = new PdfPTable(3);
table.setWidths(new int[]{3, 2, 5});
cell.setColspan(1);
table.addCell(cell);
cellCaveat.setColspan(1);
table.addCell(cellCaveat);
cellImportantNote.setColspan(1);
table.addCell(cellImportantNote);
document.add(table);

请注意,我也避免使用无意义的数字。例如,而不是:

cell.setHorizontalAlignment(0); // 0 means left

我用:

cell.setHorizontalAlignment(Element.ALIGN_LEFT);

通过这种方式,人们可以阅读这一行的含义,而不必依赖于评论。

更进一步,我取代了:

 cell.setBorderWidth(0);

使用:

 cell.setBorder(PdfPCell.NO_BORDER);

这也只是一种品味问题,但我认为如果你想保持你的代码可维护,这很重要。