代码之家  ›  专栏  ›  技术社区  ›  Trimack

ITextSharp PDFPcell标题

  •  3
  • Trimack  · 技术社区  · 15 年前

    我想要一张pdfcell类的单元格表,每个单元格都有一个小标题、主字符串和小页脚。我找不到插入它们的方法,因为headerandfooter不允许元素添加到单元格中,一个段落重写另一个段落,依此类推。有什么想法吗?

    提前谢谢

    1 回复  |  直到 9 年前
        1
  •  6
  •   Undo ptrk    9 年前

    可以使用嵌套表。
    不要使用pdfcell,而是插入一个1x1表,表头和表尾都很小。

    编辑:

    让我们忘记ITextSharp的表尾和表头功能,因为当一个表跨越多个页面,然后重复表尾和表头时,它非常有用。在我们的例子中,页眉和页脚属于只包含3个单元格的内部表,所以让我们对所有单元格使用pdfcell。

    那么主要功能是 GetHFCell 这将返回包含自定义标题单元格(高度、字体、文本等)、自定义页脚单元格和包含主文本的中间单元格的PDFPTable。 每当我们想向主表中添加单元格时,都会调用此函数(如何在 GeneratePDF )

        private static PdfPTable GetHFCell(string header, string footer, string text)
        {
            PdfPTable pdft;
            PdfPCell hc;
            PdfPCell fc;
    
            pdft = new PdfPTable(1);
            pdft.WidthPercentage = 100f;
            pdft.DefaultCell.Border = 0;
    
            hc = new PdfPCell(new Phrase(header));
            hc.Top = 0f;
            hc.FixedHeight = 7f;
            hc.HorizontalAlignment = 1;
            hc.BackgroundColor = iTextSharp.text.Color.ORANGE;
            ((Chunk)(hc.Phrase[0])).Font = new iTextSharp.text.Font(((Chunk)(hc.Phrase[0])).Font.Family, 5f);
    
            fc = new PdfPCell(new Phrase(footer));
            hc.Top = 0f;
            fc.FixedHeight = 7f;
            hc.HorizontalAlignment = 1;
            fc.BackgroundColor = iTextSharp.text.Color.YELLOW;
            ((Chunk)(fc.Phrase[0])).Font = new iTextSharp.text.Font(((Chunk)(fc.Phrase[0])).Font.Family, 5f);
    
            pdft.AddCell(hc);
            pdft.AddCell(text);
            pdft.AddCell(fc);
    
            return pdft;
        }
    
        public void GeneratePDF()
        {
            Document document = new Document();
            try
            {            
                PdfWriter.GetInstance(document, new FileStream("File1.pdf", FileMode.Create));
    
                document.Open();
    
                PdfPTable table = new PdfPTable(5);
                table.DefaultCell.Padding = 0;
                table.DefaultCell.BorderWidth = 2f;
                for (int j = 1; j < 6; j++)
                {
                    for (int i = 1; i < 6; i++)
                    {
                        //calling GetHFCell
                        table.AddCell(
                            GetHFCell("header " + ((int)(i + 5 * (j - 1))).ToString(), 
                                      "footer " + ((int)(i + 5 * (j - 1))).ToString(), 
                                      "z" + j.ToString() + i.ToString()));
                    }
                }
    
                document.Add(table);
            }
            catch (DocumentException de)
            {
                //...
            }
            catch (IOException ioe)
            {
                //...
            }
            document.Close();
        }