簡體   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