2013-09-25 166 views
27

如何为pdf中的每个页面添加页眉和页脚。使用iTextsharp为PDF添加页眉和页脚

头球将仅包含一个文本 页脚将包含PDF文本和分页(页:4 1)

这怎么可能?我试图添加下面的代码,但是头文件不会以pdf格式显示。

document.AddHeader("Header", "Header Text"); 

这我使用的PDF生成代码:

protected void GeneratePDF_Click(object sender, EventArgs e) 
    { 
     DataTable dt = getData(); 

      Response.ContentType = "application/pdf"; 
      Response.AddHeader("content-disposition", "attachment;filename=Locations.pdf"); 
      Response.Cache.SetCacheability(HttpCacheability.NoCache); 

      Document document = new Document(); 

      PdfWriter.GetInstance(document, Response.OutputStream); 

      document.Open(); 

      iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.COURIER , 8); 

      PdfPTable table = new PdfPTable(dt.Columns.Count); 
      PdfPRow row = null; 
      float[] widths = new float[] { 6f, 6f, 2f, 4f, 2f }; 

      table.SetWidths(widths); 

      table.WidthPercentage = 100; 
      int iCol = 0; 
      string colname = ""; 
      PdfPCell cell = new PdfPCell(new Phrase("Locations")); 

      cell.Colspan = dt.Columns.Count; 

      foreach (DataColumn c in dt.Columns) 
      { 

       table.AddCell(new Phrase(c.ColumnName, font5)); 
      } 

      foreach (DataRow r in dt.Rows) 
      { 
       if (dt.Rows.Count > 0) 
       { 
        table.AddCell(new Phrase(r[0].ToString(), font5)); 
        table.AddCell(new Phrase(r[1].ToString(), font5)); 
        table.AddCell(new Phrase(r[2].ToString(), font5)); 
        table.AddCell(new Phrase(r[3].ToString(), font5)); 
        table.AddCell(new Phrase(r[4].ToString(), font5)); 
       } 
      } 
      document.Add(table); 
      document.Close(); 

      Response.Write(document); 
      Response.End(); 
     } 
    } 
+0

可能对你有帮助。 http://www.mazsoft.com/blog/post/2008/04/30/Code-sample-for-using-iTextSharp-PDF-library.aspx –

回答

6

我们不谈论iTextSharp的了。您正在使用iText 5 for .NET。目前的版本是iText 7 for .NET。

过时的答案:

AddHeader已弃用很久以前和iTextSharp的已被删除。添加页眉和页脚现在使用page events完成。这些示例以Java语言编写,但您可以找到示例herehere的C#端口(滚动至页面底部以获取指向.cs文件的链接)。

请确保您阅读文档。许多开发人员常犯的一个错误是在OnStartPage中添加内容。您只应在OnEndPage中添加内容。很明显,您需要以绝对坐标添加内容(例如使用ColumnText),并且需要通过正确定义文档边距来为页眉和页脚留出足够的空间。

更新答案:

如果你是新来的iText,你应该使用的iText 7和使用事件处理程序添加页眉和页脚。请参阅iText 7 Jump-Start Tutorial for .NET的chapter 3

当您在iText的7有一个PdfDocument,你可以添加事件处理程序:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); 
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler()); 

这是一个例子硬盘的方式对于在绝对位置添加文字(使用PdfCanvas):

protected internal class MyEventHandler : IEventHandler { 
    public virtual void HandleEvent(Event @event) { 
     PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; 
     PdfDocument pdfDoc = docEvent.GetDocument(); 
     PdfPage page = docEvent.GetPage(); 
     int pageNumber = pdfDoc.GetPageNumber(page); 
     Rectangle pageSize = page.GetPageSize(); 
     PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc); 
     //Add header 
     pdfCanvas.BeginText() 
      .SetFontAndSize(C03E03_UFO.helvetica, 9) 
      .MoveText(pageSize.GetWidth()/2 - 60, pageSize.GetTop() - 20) 
      .ShowText("THE TRUTH IS OUT THERE") 
      .MoveText(60, -pageSize.GetTop() + 30) 
      .ShowText(pageNumber.ToString()) 
      .EndText(); 
     pdfCanvas.release(); 
    } 
} 

这是一个稍微更高级别的方式,使用Canvas

protected internal class MyEventHandler : IEventHandler { 
    public virtual void HandleEvent(Event @event) { 
     PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; 
     PdfDocument pdfDoc = docEvent.GetDocument(); 
     PdfPage page = docEvent.GetPage(); 
     int pageNumber = pdfDoc.GetPageNumber(page); 
     Rectangle pageSize = page.GetPageSize(); 
     PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc); 
     //Add watermark 
     Canvas canvas = new Canvas(pdfCanvas, pdfDoc, page.getPageSize()); 
     canvas.setFontColor(Color.WHITE); 
     canvas.setProperty(Property.FONT_SIZE, 60); 
     canvas.setProperty(Property.FONT, helveticaBold); 
     canvas.showTextAligned(new Paragraph("CONFIDENTIAL"), 
      298, 421, pdfDoc.getPageNumber(page), 
      TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45); 
     pdfCanvas.release(); 
    } 
} 

还有其他方法可以在绝对位置添加内容。它们在不同的iText books中描述。

+0

不完全如此。使用页面事件是添加页眉/页脚的一种方法,但是您可以使用“Document.Header”或“Document.Footer”来添加它们。 – Dom

+2

亲爱的Dom,如果你可以用'Document.Header'或'Document.Footer'添加页眉和页脚,你使用的是不再支持的iText版本:http://lowagie.com/itext2 –

+0

我的歉意!谢谢你的信息! – Dom

32

正如@Bruno所回答的,您需要使用pageEvents。

请看看下面的示例代码:

private void CreatePDF() 
{ 
    string fileName = string.Empty;  
    DateTime fileCreationDatetime = DateTime.Now;  
    fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));  
    string pdfPath = Server.MapPath(@"~\PDFs\") + fileName; 

    using (FileStream msReport = new FileStream(pdfPath, FileMode.Create)) 
    { 
     //step 1 
     using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f)) 
     { 
      try 
      { 
       // step 2 
       PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport); 
       pdfWriter.PageEvent = new Common.ITextEvents(); 

       //open the stream 
       pdfDoc.Open(); 

       for (int i = 0; i < 10; i++) 
       { 
        Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));  
        para.Alignment = Element.ALIGN_CENTER;  
        pdfDoc.Add(para);  
        pdfDoc.NewPage(); 
       } 

       pdfDoc.Close();  
      } 
      catch (Exception ex) 
      { 
       //handle exception 
      }  
      finally 
      { 
      }  
     }  
    } 
} 

并创建一个名为ITextEvents一个类文件。cs并添加以下代码:

public class ITextEvents : PdfPageEventHelper 
{  
    // This is the contentbyte object of the writer 
    PdfContentByte cb; 

    // we will put the final number of pages in a template 
    PdfTemplate headerTemplate, footerTemplate; 

    // this is the BaseFont we are going to use for the header/footer 
    BaseFont bf = null; 

    // This keeps track of the creation time 
    DateTime PrintTime = DateTime.Now;  

    #region Fields 
    private string _header; 
    #endregion 

    #region Properties 
    public string Header 
    { 
     get { return _header; } 
     set { _header = value; } 
    } 
    #endregion  

    public override void OnOpenDocument(PdfWriter writer, Document document) 
    { 
     try 
     { 
      PrintTime = DateTime.Now; 
      bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
      cb = writer.DirectContent; 
      headerTemplate = cb.CreateTemplate(100, 100); 
      footerTemplate = cb.CreateTemplate(50, 50); 
     } 
     catch (DocumentException de) 
     {  
     } 
     catch (System.IO.IOException ioe) 
     {  
     } 
    } 

    public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) 
    { 
     base.OnEndPage(writer, document);  
     iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);  
     iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);  
     Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal); 

     //Create PdfTable object 
     PdfPTable pdfTab = new PdfPTable(3); 

     //We will have to create separate cells to include image logo and 2 separate strings 
     //Row 1 
     PdfPCell pdfCell1 = new PdfPCell(); 
     PdfPCell pdfCell2 = new PdfPCell(p1Header); 
     PdfPCell pdfCell3 = new PdfPCell(); 
     String text = "Page " + writer.PageNumber + " of ";  

     //Add paging to header 
     { 
      cb.BeginText(); 
      cb.SetFontAndSize(bf, 12); 
      cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45)); 
      cb.ShowText(text); 
      cb.EndText(); 
      float len = bf.GetWidthPoint(text, 12); 
      //Adds "12" in Page 1 of 12 
      cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45)); 
     } 
     //Add paging to footer 
     { 
      cb.BeginText(); 
      cb.SetFontAndSize(bf, 12); 
      cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30)); 
      cb.ShowText(text); 
      cb.EndText(); 
      float len = bf.GetWidthPoint(text, 12); 
      cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30)); 
     } 

     //Row 2 
     PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal)); 

     //Row 3 
     PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig)); 
     PdfPCell pdfCell6 = new PdfPCell(); 
     PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));  

     //set the alignment of all three cells and set border to 0 
     pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; 
     pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; 
     pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; 
     pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; 
     pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; 
     pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; 
     pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;  

     pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM; 
     pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; 
     pdfCell4.VerticalAlignment = Element.ALIGN_TOP; 
     pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE; 
     pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; 
     pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;  

     pdfCell4.Colspan = 3; 

     pdfCell1.Border = 0; 
     pdfCell2.Border = 0; 
     pdfCell3.Border = 0; 
     pdfCell4.Border = 0; 
     pdfCell5.Border = 0; 
     pdfCell6.Border = 0; 
     pdfCell7.Border = 0;  

     //add all three cells into PdfTable 
     pdfTab.AddCell(pdfCell1); 
     pdfTab.AddCell(pdfCell2); 
     pdfTab.AddCell(pdfCell3); 
     pdfTab.AddCell(pdfCell4); 
     pdfTab.AddCell(pdfCell5); 
     pdfTab.AddCell(pdfCell6); 
     pdfTab.AddCell(pdfCell7); 

     pdfTab.TotalWidth = document.PageSize.Width - 80f; 
     pdfTab.WidthPercentage = 70; 
     //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;  

     //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable 
     //first param is start row. -1 indicates there is no end row and all the rows to be included to write 
     //Third and fourth param is x and y position to start writing 
     pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); 
     //set pdfContent value 

     //Move the pointer and draw line to separate header section from rest of page 
     cb.MoveTo(40, document.PageSize.Height - 100); 
     cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); 
     cb.Stroke(); 

     //Move the pointer and draw line to separate footer section from rest of page 
     cb.MoveTo(40, document.PageSize.GetBottom(50)); 
     cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); 
     cb.Stroke(); 
    } 

    public override void OnCloseDocument(PdfWriter writer, Document document) 
    { 
     base.OnCloseDocument(writer, document); 

     headerTemplate.BeginText(); 
     headerTemplate.SetFontAndSize(bf, 12); 
     headerTemplate.SetTextMatrix(0, 0); 
     headerTemplate.ShowText((writer.PageNumber - 1).ToString()); 
     headerTemplate.EndText(); 

     footerTemplate.BeginText(); 
     footerTemplate.SetFontAndSize(bf, 12); 
     footerTemplate.SetTextMatrix(0, 0); 
     footerTemplate.ShowText((writer.PageNumber - 1).ToString()); 
     footerTemplate.EndText(); 
    } 
} 

我希望它有帮助!成功地工作

+0

我喜欢这个例子,但我有一个问题:如果我使用您的PdfPageEventHelper类作为所有我的PDF文档的公共类,并且我想在每个文档的标题中显示不同的文本(例如作为文件标题...等)如何设置?谢谢。 – user2430797

+0

您可以为每个需要由用户动态设置的项目创建属性。例如“Sample Header Here”,可以用属性替换,它的值可以在运行时设置。我希望这是有道理的。 –

+0

工作完美!由于我在页脚中放置了不同的文本,因此需要帮助将附加的TotalCount删除为页面页脚文本。页数将会出现在我正在放置的任何字符串中 – Bhat

0

易代码:

protected void Page_Load(object sender, EventArgs e) 
{ 
. 
.  
using (MemoryStream ms = new MemoryStream()) 
{ 
    . 
    . 
    iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 54, 54); 
    iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms); 
    writer.PageEvent = new HeaderFooter(); 
    doc.Open(); 
    . 
    . 
    // make your document content.. 
    . 
    .     
    doc.Close(); 
    writer.Close(); 

    // output 
    Response.ContentType = "application/pdf;"; 
    Response.AddHeader("Content-Disposition", "attachment; filename=clientfilename.pdf"); 
    byte[] pdf = ms.ToArray(); 
    Response.OutputStream.Write(pdf, 0, pdf.Length); 
} 
. 
. 
. 
} 
class HeaderFooter : PdfPageEventHelper 
{ 
public override void OnEndPage(PdfWriter writer, Document document) 
{ 

    // Make your table header using PdfPTable and name that tblHeader 
    . 
    . 
    tblHeader.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, page.Top, writer.DirectContent); 
    . 
    . 
    // Make your table footer using PdfPTable and name that tblFooter 
    . 
    . 
    tblFooter.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent); 
} 
} 
2

打开文档之前刚刚加入这一行(必须是前):

 document.Header = new HeaderFooter(new Phrase("Header Text"), false); 
     document.Open(); 
+0

嗨,Alvaro,欢迎来到StackOverflow。你能解释一下为什么*你需要这样做,或者*它如何工作? –

+1

嗨,它必须在打开文档之前,如果你想在第一页显示标题,如果你不需要,你可以把它放在后面。我知道新的方法是通过PdfPageEvent,但如果你不需要对页眉或页脚进行太多控制,这是一种简单的方法。它是如何工作的......没有太多关于它的文档。 –

+0

啊哈。非常感谢您解释这一点 - 我希望额外的信息能够帮助其他人。 –

5

对这个问题的答案,而他们是正确的,是非常不必要的复杂。它不需要太多的代码来显示文本在页眉/页脚中。以下是向页眉/页脚添加文本的简单示例。

iTextSharp的当前版本通过实现由IPdfPageEvent接口定义的回调类来工作。据我所知,在OnStartPage方法中添加东西并不是一个好主意,所以我将使用OnEndPage页面方法。事件的触发取决于发生了什么PdfWriter

首先,创建一个实现IPdfPageEvent的类。在:

  ColumnText ct = new ColumnText(cb); 

      cb.BeginText(); 
      cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f); 
      //Note, (0,0) in this case is at the bottom of the document 
      cb.SetTextMatrix(document.LeftMargin, document.BottomMargin); 
      cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this")); 
      cb.EndText(); 

,所以该完整的OnEndPage功能将是:

 public void OnEndPage(PdfWriter writer, Document document) 

功能,通过调用

 PdfContentByte cb = writer.DirectContent; 

现在,您可以添加文字很容易获得PdfContentByte对象:

 public void OnEndPage(PdfWriter writer, Document document) 
     { 
      PdfContentByte cb = writer.DirectContent; 
      ColumnText ct = new ColumnText(cb); 

      cb.BeginText(); 
      cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f); 
      cb.SetTextMatrix(document.LeftMargin, document.BottomMargin); 
      cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this")); 
      cb.EndText(); 

     } 

这将显示在文档的底部。最后一件事。不要忘记分配IPdfPageEvent这样的:

 writter.PageEvent = new PDFEvents(); 

PdfWriter writter对象

对于它是非常相似。只需翻转SetTextMatrix y坐标:

 cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin); 
+1

没有表格的解决方案比其他解决方案更容易。大声笑是疯了,我们必须做些什么来添加一个简单的脚和标题。 –

1

对于iTextSharp的4.1.6,iTextSharp的的最后一个版本被许可为LGPL,由Alvaro Patiño提供的解决方案是既简单又有效。

因为文档有点问题,我想用这段代码扩展他的答案,这段代码可以用来改变页眉和页脚的外观。默认情况下,它们具有相当大的字体大小和厚边框,许多人都想要更改。

// Parameters passed on to the function that creates the PDF 
String headerText = "Your header text"; 
String footerText = "Page"; 

// Define a font and font-size in points (plus f for float) and pick a color 
// This one is for both header and footer but you can also create seperate ones 
Font fontHeaderFooter = FontFactory.GetFont("arial", 8f); 
fontHeaderFooter.Color = Color.GRAY; 

// Apply the font to the headerText and create a Phrase with the result 
Chunk chkHeader = new Chunk(headerText, fontHeaderFooter); 
Phrase p1 = new Phrase(chkHeader); 

// create a HeaderFooter element for the header using the Phrase 
// The boolean turns numbering on or off 
HeaderFooter header = new HeaderFooter(p1, false); 

// Remove the border that is set by default 
header.Border = Rectangle.NO_BORDER; 
// Align the text: 0 is left, 1 center and 2 right. 
header.Alignment = 1; 

// add the header to the document 
document.Header = header; 

// The footer is created in an similar way 

// If you want to use numbering like in this example, add a whitespace to the 
// text because by default there's no space in between them 
if (footerText.Substring(footerText.Length - 1) != " ") footerText += " "; 

Chunk chkFooter = new Chunk(footerText, fontHeaderFooter); 
Phrase p2 = new Phrase(chkFooter); 

// Turn on numbering by setting the boolean to true 
HeaderFooter footer = new HeaderFooter(p2, true); 
footer.Border = Rectangle.NO_BORDER; 
footer.Alignment = 1; 

document.Footer = footer; 

// Open the Document for writing and continue creating its content 
document.Open(); 

欲了解更多信息检查Creating PDFs with iTextSharpiTextSharp - Adding Text with Chunks, Phrases and ParagraphsGitHub上的源代码也可能有用。

0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using iTextSharp; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 
using DataLayer; 

namespace DataMngt.MyCode 
{ 
    public class HeaderFooter : PdfPageEventHelper 
    { 
     #region Startup_Stuff 

     private string[] _headerLines; 
     private string _footerLine; 

     private DefineFont _boldFont; 
     private DefineFont _normalFont; 

     private iTextSharp.text.Font fontTxtBold; 
     private iTextSharp.text.Font fontTxtRegular; 

     private int _fontPointSize = 0; 

     private bool hasFooter = false; 
     private bool hasHeader = false; 

     private int _headerWidth = 0; 
     private int _headerHeight = 0; 

     private int _footerWidth = 0; 
     private int _footerHeight = 0; 

     private int _leftMargin = 0; 
     private int _rightMargin = 0; 
     private int _topMargin = 0; 
     private int _bottomMargin = 0; 

     private PageNumbers NumberSettings; 

     private DateTime runTime = DateTime.Now;    

     public enum PageNumbers 
     { 
      None, 
      HeaderPlacement, 
      FooterPlacement 
     } 

     // This is the contentbyte object of the writer 
     PdfContentByte cb; 

     PdfTemplate headerTemplate; 
     PdfTemplate footerTemplate; 

     public string[] headerLines 
     { 
      get 
      { 
       return _headerLines; 
      } 
      set 
      { 
       _headerLines = value; 
       hasHeader = true; 
      } 
     } 

     public string footerLine 
     { 
      get 
      { 
       return _footerLine; 
      } 
      set 
      { 
       _footerLine = value; 
       hasFooter = true; 
      } 
     } 

     public DefineFont boldFont 
     { 
      get 
      { 
       return _boldFont; 
      } 
      set 
      { 
       _boldFont = value; 
      } 
     } 

     public DefineFont normalFont 
     { 
      get 
      { 
       return _normalFont; 
      } 
      set 
      { 
       _normalFont = value; 
      } 
     } 

     public int fontPointSize 
     { 
      get 
      { 
       return _fontPointSize; 
      } 
      set 
      { 
       _fontPointSize = value; 
      } 
     } 

     public int leftMargin 
     { 
      get 
      { 
       return _leftMargin; 
      } 
      set 
      { 
       _leftMargin = value; 
      } 
     } 

     public int rightMargin 
     { 
      get 
      { 
       return _rightMargin; 
      } 
      set 
      { 
       _rightMargin = value; 
      } 
     } 

     public int topMargin 
     { 
      get 
      { 
       return _topMargin; 
      } 
      set 
      { 
       _topMargin = value; 
      } 
     } 

     public int bottomMargin 
     { 
      get 
      { 
       return _bottomMargin; 
      } 
      set 
      { 
       _bottomMargin = value; 
      } 
     } 

     public int headerheight 
     { 
      get 
      { 
       return _headerHeight; 
      } 
     } 

     public int footerHeight 
     { 
      get 
      { 
       return _footerHeight; 
      } 
     } 

     public PageNumbers PageNumberSettings 
     { 
      get 
      { 
       return NumberSettings; 
      } 

      set 
      { 
       NumberSettings = value; 
      } 
     } 

     #endregion 

     #region Write_Headers_Footers 

     public override void OnEndPage(PdfWriter writer, Document document) 
     { 
      if (hasHeader) 
      { 
       // left side is the string array passed in 
       // right side is a built in string array (0 = date, 1 = time, 2(optional) = page) 
       float[] widths = new float[2] { 90f, 10f }; 

       PdfPTable hdrTable = new PdfPTable(2); 
       hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin); 
       hdrTable.WidthPercentage = 95; 
       hdrTable.SetWidths(widths); 
       hdrTable.LockedWidth = true; 

       for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx ++) 
       { 
        string leftLine = (hdrIdx < _headerLines.Length ? _headerLines[hdrIdx] : string.Empty); 

        Paragraph leftPara = new Paragraph(5, leftLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular)); 

        switch (hdrIdx) 
        { 
         case 0: 
          { 
           leftPara.Font.Size = _fontPointSize; 

           PdfPCell leftCell = new PdfPCell(leftPara); 
           leftCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           leftCell.Border = 0; 

           string rightLine = string.Format(SalesPlanResources.datePara, runTime.ToString(SalesPlanResources.datePrintMask)); 
           Paragraph rightPara = new Paragraph(5, rightLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular)); 
           rightPara.Font.Size = _fontPointSize; 

           PdfPCell rightCell = new PdfPCell(rightPara); 
           rightCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           rightCell.Border = 0; 

           hdrTable.AddCell(leftCell); 
           hdrTable.AddCell(rightCell); 

           break; 
          } 

         case 1: 
          { 
           leftPara.Font.Size = _fontPointSize; 

           PdfPCell leftCell = new PdfPCell(leftPara); 
           leftCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           leftCell.Border = 0; 

           string rightLine = string.Format(SalesPlanResources.timePara, runTime.ToString(SalesPlanResources.timePrintMask)); 
           Paragraph rightPara = new Paragraph(5, rightLine, (hdrIdx == 0 ? fontTxtBold : fontTxtRegular)); 
           rightPara.Font.Size = _fontPointSize; 

           PdfPCell rightCell = new PdfPCell(rightPara); 
           rightCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           rightCell.Border = 0; 

           hdrTable.AddCell(leftCell); 
           hdrTable.AddCell(rightCell); 

           break; 
          } 

         case 2: 
          { 
           leftPara.Font.Size = _fontPointSize; 

           PdfPCell leftCell = new PdfPCell(leftPara); 
           leftCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           leftCell.Border = 0; 

           string rightLine; 
           if (NumberSettings == PageNumbers.HeaderPlacement) 
           { 
            rightLine = string.Concat(SalesPlanResources.pagePara, writer.PageNumber.ToString()); 
           } 
           else 
           { 
            rightLine = string.Empty; 
           } 
           Paragraph rightPara = new Paragraph(5, rightLine, fontTxtRegular); 
           rightPara.Font.Size = _fontPointSize; 

           PdfPCell rightCell = new PdfPCell(rightPara); 
           rightCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           rightCell.Border = 0; 

           hdrTable.AddCell(leftCell); 
           hdrTable.AddCell(rightCell); 

           break; 
          } 

         default: 
          { 
           leftPara.Font.Size = _fontPointSize; 

           PdfPCell leftCell = new PdfPCell(leftPara); 
           leftCell.HorizontalAlignment = Element.ALIGN_LEFT; 
           leftCell.Border = 0; 
           leftCell.Colspan = 2;        

           hdrTable.AddCell(leftCell); 

           break; 
          } 
        } 
       } 

       hdrTable.WriteSelectedRows(0, -1, _leftMargin, document.PageSize.Height - _topMargin, writer.DirectContent); 

       //Move the pointer and draw line to separate header section from rest of page 
       cb.MoveTo(_leftMargin, document.Top + 10); 
       cb.LineTo(document.PageSize.Width - _leftMargin, document.Top + 10); 
       cb.Stroke(); 
      } 

      if (hasFooter) 
      { 
       // footer line is the width of the page so it is centered horizontally 
       PdfPTable ftrTable = new PdfPTable(1); 
       float[] widths = new float[1] {100 }; 

       ftrTable.TotalWidth = document.PageSize.Width - 10; 
       ftrTable.WidthPercentage = 95; 
       ftrTable.SetWidths(widths); 

       string OneLine; 

       if (NumberSettings == PageNumbers.FooterPlacement) 
       { 
        OneLine = string.Concat(_footerLine, writer.PageNumber.ToString()); 
       } 
       else 
       { 
        OneLine = _footerLine; 
       } 

       Paragraph onePara = new Paragraph(0, OneLine, fontTxtRegular); 
       onePara.Font.Size = _fontPointSize; 

       PdfPCell oneCell = new PdfPCell(onePara); 
       oneCell.HorizontalAlignment = Element.ALIGN_CENTER; 
       oneCell.Border = 0; 
       ftrTable.AddCell(oneCell); 

       ftrTable.WriteSelectedRows(0, -1, _leftMargin, (_footerHeight), writer.DirectContent); 

       //Move the pointer and draw line to separate footer section from rest of page 
       cb.MoveTo(_leftMargin, document.PageSize.GetBottom(_footerHeight + 2)); 
       cb.LineTo(document.PageSize.Width - _leftMargin, document.PageSize.GetBottom(_footerHeight + 2)); 
       cb.Stroke(); 
      } 
     } 

     #endregion 


     #region Setup_Headers_Footers_Happens_here 

     public override void OnOpenDocument(PdfWriter writer, Document document) 
     { 
      // create the fonts that are to be used 
      // first the hightlight or Bold font 
      fontTxtBold = FontFactory.GetFont(_boldFont.fontFamily, _boldFont.fontSize, _boldFont.foreColor); 
      if (_boldFont.isBold) 
      { 
       fontTxtBold.SetStyle(Font.BOLD); 
      } 
      if (_boldFont.isItalic) 
      { 
       fontTxtBold.SetStyle(Font.ITALIC); 
      } 
      if (_boldFont.isUnderlined) 
      { 
       fontTxtBold.SetStyle(Font.UNDERLINE); 
      } 

      // next the normal font 
      fontTxtRegular = FontFactory.GetFont(_normalFont.fontFamily, _normalFont.fontSize, _normalFont.foreColor); 
      if (_normalFont.isBold) 
      { 
       fontTxtRegular.SetStyle(Font.BOLD); 
      } 
      if (_normalFont.isItalic) 
      { 
       fontTxtRegular.SetStyle(Font.ITALIC); 
      } 
      if (_normalFont.isUnderlined) 
      { 
       fontTxtRegular.SetStyle(Font.UNDERLINE); 
      } 

      // now build the header and footer templates 
      try 
      { 
       float pageHeight = document.PageSize.Height; 
       float pageWidth = document.PageSize.Width; 

       _headerWidth = (int)pageWidth - ((int)_rightMargin + (int)_leftMargin); 
       _footerWidth = _headerWidth; 

       if (hasHeader) 
       { 
        // i basically dummy build the headers so i can trial fit them and see how much space they take. 
        float[] widths = new float[1] { 90f }; 

        PdfPTable hdrTable = new PdfPTable(1); 
        hdrTable.TotalWidth = document.PageSize.Width - (_leftMargin + _rightMargin); 
        hdrTable.WidthPercentage = 95; 
        hdrTable.SetWidths(widths); 
        hdrTable.LockedWidth = true; 

        _headerHeight = 0; 

        for (int hdrIdx = 0; hdrIdx < (_headerLines.Length < 2 ? 2 : _headerLines.Length); hdrIdx++) 
        { 
         Paragraph hdrPara = new Paragraph(5, hdrIdx > _headerLines.Length - 1 ? string.Empty : _headerLines[hdrIdx], (hdrIdx > 0 ? fontTxtRegular : fontTxtBold)); 
         PdfPCell hdrCell = new PdfPCell(hdrPara); 
         hdrCell.HorizontalAlignment = Element.ALIGN_LEFT; 
         hdrCell.Border = 0; 
         hdrTable.AddCell(hdrCell); 
         _headerHeight = _headerHeight + (int)hdrTable.GetRowHeight(hdrIdx); 
        } 

        // iTextSharp underestimates the size of each line so fudge it a little 
        // this gives me 3 extra lines to play with on the spacing 
        _headerHeight = _headerHeight + (_fontPointSize * 3); 

       } 

       if (hasFooter) 
       { 
        _footerHeight = (_fontPointSize * 2); 
       } 

       document.SetMargins(_leftMargin, _rightMargin, (_topMargin + _headerHeight), _footerHeight); 

       cb = writer.DirectContent; 

       if (hasHeader) 
       { 
        headerTemplate = cb.CreateTemplate(_headerWidth, _headerHeight); 
       } 

       if (hasFooter) 
       { 
        footerTemplate = cb.CreateTemplate(_footerWidth, _footerHeight); 
       } 
      } 
      catch (DocumentException de) 
      { 

      } 
      catch (System.IO.IOException ioe) 
      { 

      } 
     } 

     #endregion 

     #region Cleanup_Doc_Processing 

     public override void OnCloseDocument(PdfWriter writer, Document document) 
     { 
      base.OnCloseDocument(writer, document); 

      if (hasHeader) 
      { 
       headerTemplate.BeginText(); 
       headerTemplate.SetTextMatrix(0, 0); 

       if (NumberSettings == PageNumbers.HeaderPlacement) 
       { 
       } 

       headerTemplate.EndText(); 
      } 

      if (hasFooter) 
      { 
       footerTemplate.BeginText(); 
       footerTemplate.SetTextMatrix(0, 0); 

       if (NumberSettings == PageNumbers.FooterPlacement) 
       { 
       } 

       footerTemplate.EndText(); 
      } 
     } 

     #endregion 

    } 
} 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using iTextSharp; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

namespace DataMngt.MyCode 
{ 

    // used to define the fonts passed into the header and footer class 
    public struct DefineFont 
    { 
     public string fontFamily { get; set; } 
     public int fontSize { get; set; } 
     public bool isBold { get; set; } 
     public bool isItalic { get; set; } 
     public bool isUnderlined { get; set; } 
     public BaseColor foreColor { get; set; } 
    } 
} 

使用:

Document pdfDoc = new Document(PageSize.LEGAL.Rotate(), 10, 10, 25, 25); 
System.IO.MemoryStream mStream = new System.IO.MemoryStream(); 
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream); 
MyCode.HeaderFooter headers = new MyCode.HeaderFooter(); 
writer.PageEvent = headers; 

.. .. 构建头 字符串数组...

DefineFont passFont = new DefineFont(); 

    // always set this to the largest font used 
    headers.fontPointSize = 8; 

    // set up the highlight or bold font 
    passFont.fontFamily = "Helvetica"; 
    passFont.fontSize = 8; 
    passFont.isBold = true; 
    passFont.isItalic = false; 
    passFont.isUnderlined = false; 
    passFont.foreColor = BaseColor.BLACK; 

    headers.boldFont = passFont; 

    // now setup the normal text font 
    passFont.fontSize = 7; 
    passFont.isBold = false; 

    headers.normalFont = passFont; 

    headers.leftMargin = 10; 
    headers.bottomMargin = 25; 
    headers.rightMargin = 10; 
    headers.topMargin = 25; 

    headers.PageNumberSettings = HeaderFooter.PageNumbers.FooterPlacement; 

    headers.footerLine = "Page"; 
    headers.headerLines = parmLines.ToArray(); 

    pdfDoc.SetMargins(headers.leftMargin, headers.rightMargin, headers.topMargin + headers.headerheight, headers.bottomMargin + headers.footerHeight); 
    pdfDoc.Open(); 

    // the new page is necessary due to a bug in in the current version of itextsharp 
    pdfDoc.NewPage(); 

...现在页眉和页脚自动处理

+0

您认为您的解决方案与现有答案中的解决方案相比有何优势? – mkl

+0

它是一个非常通用的例程,用于为很多不需要图像头的报告生成页眉和页脚。它很容易适应大多数用途只需要改变属性。 – Woody

+0

你可能想要编辑你的答案来解释,因为有这么多的代码几乎没有人会阅读它并发现优点。 – mkl

相关问题