繁体   English   中英

为什么无法使用iTextSharp在PDF文件上生成表格?

[英]Why is my table not being generated on my PDF file using iTextSharp?

我正在尝试向正在生成的PDF文件中添加表格。 我可以“直接”添加内容,但希望将各种段落或短语放在表格单元格中,以使所有内容很好地对齐。

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

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));
}

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

UPDATE

基于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));
    }
}

请看一下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 cellImportantNote段落。

这意味着您将创建一个包含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);

这也只是一个问题,但是我认为如果要保持代码的可维护性很重要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM