对于iTextSharp遇到的问题,我需要帮助。 我想根据页面是否具有页眉/页脚来动态设置边距,而不必始终为每个页面手动设置。这样做的话,尽管它似乎总是在我想要的页面之后执行。我认为这一定是将我的代码放在某些东西之前的问题。我在想,当OnStartPage方法被调用时,Document类的NewPage方法已经被调用了。是吗这是唯一对我有意义的解释。
我可以在创建pdf文件的类上执行此操作。每次调用NewPage方法之前都要调用该方法。但是我想要更自动化的东西。
因此,以下是将创建实际pdf文件的方法:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApplication4.Models
{
public class ITextEvents : PdfPageEventHelper
{
Font FontRegular = new Font(Font.FontFamily.HELVETICA, 12);
// 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;
List<int> PagesWithNoFooter, PagesWithNoHeader;
float LeftMargin, RightMargin, TopMarginWithHeader, TopMarginWithNoHeader, BottomMarginWithFooter, BottomMarginWithNoFooter;
/// <summary>
/// The constructor for getting some presets
/// </summary>
/// <param name="pagesWithNoHeader">List of pages in which the user doesn't want a header.</param>
/// <param name="pagesWithNoFooter">List of pages in which the user doesn't want a footer.</param>
/// <param name="leftMargin">The page's default left margin.</param>
/// <param name="rightMargin">The page's default right margin.</param>
/// <param name="topMarginWithNoHeader">The page's top margin for a page with no header.</param>
/// <param name="topMarginWithHeader">The page's top margin for a page with header.</param>
/// <param name="bottomMarginWithNoFooter">The page's bottom margin for a page with no footer.</param>
/// <param name="bottomMarginWithFooter">The page's bottom margin for a page with footer.</param>
public ITextEvents(List<int> pagesWithNoHeader, List<int> pagesWithNoFooter, float leftMargin, float rightMargin, float topMarginWithNoHeader, float topMarginWithHeader, float bottomMarginWithNoFooter, float bottomMarginWithFooter)
{
PagesWithNoFooter = pagesWithNoFooter.OrderBy(i => i).ToList();
PagesWithNoHeader = pagesWithNoHeader.OrderBy(i => i).ToList();
LeftMargin = leftMargin;
RightMargin = rightMargin;
TopMarginWithHeader = topMarginWithHeader;
TopMarginWithNoHeader = topMarginWithNoHeader;
BottomMarginWithFooter = bottomMarginWithFooter;
BottomMarginWithNoFooter = bottomMarginWithNoFooter;
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
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)
{
//handle exception here
}
catch (System.IO.IOException ioe)
{
//handle exception here
}
}
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
float[] docMargins = SetDocumentMargins(writer.CurrentPageNumber);
document.SetMargins(docMargins[0], docMargins[1], docMargins[2], docMargins[3]);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
// Adds the footer if the user didn't specify the page number
if (!PagesWithNoFooter.Contains(document.PageNumber))
{
//Add paging to footer
{
string paging = "Página " + writer.PageNumber + " de ";
float len = bf.GetWidthPoint(paging, 12);
float posX = (document.PageSize.Width / 2) - (len / 2);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(posX, document.PageSize.GetBottom(30));
cb.ShowText(paging);
cb.EndText();
cb.AddTemplate(footerTemplate, posX + len, document.PageSize.GetBottom(30));
}
}
// Adds the header if the user didn't specify the page number
if (!PagesWithNoHeader.Contains(document.PageNumber))
{
Phrase p1Header = new Phrase("Sample Header Here", FontRegular);
//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 ";
//Row 2
PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", FontRegular));
//Row 3
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:", FontRegular));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), FontRegular));
//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;
//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);
//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();
}
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText(writer.PageNumber.ToString());
footerTemplate.EndText();
}
private float[] SetDocumentMargins(int pageNumber)
{
float topMargin = 0, bottomMargin = 0;
// Sets the bottom margin depending on wether the page has a footer
if (PagesWithNoFooter.Contains(pageNumber))
bottomMargin = BottomMarginWithNoFooter;
else
bottomMargin = BottomMarginWithFooter;
// Sets the top margin depending on wether the page has a header
if (PagesWithNoHeader.Contains(pageNumber))
topMargin = TopMarginWithNoHeader;
else
topMargin = TopMarginWithHeader;
return new float[] { LeftMargin, RightMargin, topMargin, bottomMargin };
}
}
}
这是PdfPageEventHelper的代码:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApplication4.Models
{
public class ITextEvents : PdfPageEventHelper
{
Font FontRegular = new Font(Font.FontFamily.HELVETICA, 12);
// 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;
List<int> PagesWithNoFooter, PagesWithNoHeader;
float LeftMargin, RightMargin, TopMarginWithHeader, TopMarginWithNoHeader, BottomMarginWithFooter, BottomMarginWithNoFooter;
/// <summary>
/// The constructor for getting some presets
/// </summary>
/// <param name="pagesWithNoHeader">List of pages in which the user doesn't want a header.</param>
/// <param name="pagesWithNoFooter">List of pages in which the user doesn't want a footer.</param>
/// <param name="leftMargin">The page's default left margin.</param>
/// <param name="rightMargin">The page's default right margin.</param>
/// <param name="topMarginWithNoHeader">The page's top margin for a page with no header.</param>
/// <param name="topMarginWithHeader">The page's top margin for a page with header.</param>
/// <param name="bottomMarginWithNoFooter">The page's bottom margin for a page with no footer.</param>
/// <param name="bottomMarginWithFooter">The page's bottom margin for a page with footer.</param>
public ITextEvents(List<int> pagesWithNoHeader, List<int> pagesWithNoFooter, float leftMargin, float rightMargin, float topMarginWithNoHeader, float topMarginWithHeader, float bottomMarginWithNoFooter, float bottomMarginWithFooter)
{
PagesWithNoFooter = pagesWithNoFooter.OrderBy(i => i).ToList();
PagesWithNoHeader = pagesWithNoHeader.OrderBy(i => i).ToList();
LeftMargin = leftMargin;
RightMargin = rightMargin;
TopMarginWithHeader = topMarginWithHeader;
TopMarginWithNoHeader = topMarginWithNoHeader;
BottomMarginWithFooter = bottomMarginWithFooter;
BottomMarginWithNoFooter = bottomMarginWithNoFooter;
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
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)
{
//handle exception here
}
catch (System.IO.IOException ioe)
{
//handle exception here
}
}
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
float[] docMargins = SetDocumentMargins(writer.CurrentPageNumber);
document.SetMargins(docMargins[0], docMargins[1], docMargins[2], docMargins[3]);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
// Adds the footer if the user didn't specify the page number
if (!PagesWithNoFooter.Contains(document.PageNumber))
{
//Add paging to footer
{
string paging = "Página " + writer.PageNumber + " de ";
float len = bf.GetWidthPoint(paging, 12);
float posX = (document.PageSize.Width / 2) - (len / 2);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(posX, document.PageSize.GetBottom(30));
cb.ShowText(paging);
cb.EndText();
cb.AddTemplate(footerTemplate, posX + len, document.PageSize.GetBottom(30));
}
}
// Adds the header if the user didn't specify the page number
if (!PagesWithNoHeader.Contains(document.PageNumber))
{
Phrase p1Header = new Phrase("Sample Header Here", FontRegular);
//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 ";
//Row 2
PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", FontRegular));
//Row 3
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:", FontRegular));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), FontRegular));
//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;
//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);
//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();
}
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText(writer.PageNumber.ToString());
footerTemplate.EndText();
}
private float[] SetDocumentMargins(int pageNumber)
{
float topMargin = 0, bottomMargin = 0;
// Sets the bottom margin depending on wether the page has a footer
if (PagesWithNoFooter.Contains(pageNumber))
bottomMargin = BottomMarginWithNoFooter;
else
bottomMargin = BottomMarginWithFooter;
// Sets the top margin depending on wether the page has a header
if (PagesWithNoHeader.Contains(pageNumber))
topMargin = TopMarginWithNoHeader;
else
topMargin = TopMarginWithHeader;
return new float[] { LeftMargin, RightMargin, topMargin, bottomMargin };
}
}
}