我有一个问题,我想在我的pdf文档中添加页眉和页脚。为此,我习惯了PdfPageEventHelper。
我创建了一个课程:
public class PDFFooter : PdfPageEventHelper
{
// write on top of document
public override void OnOpenDocument(PdfWriter writer, Document document)
{
base.OnOpenDocument(writer, document);
}
// write on start of each page
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
EnTeteDePage(document);
}
// write on end of each page
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
PiedDePage(document);
}
//write on close of document
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
}
private void EnTeteDePage(Document document)
{
Controleur.ControleurParametre CP = new ControleurParametre();
T_PARAMETRE _param = CP.Charger();
T_ADRESSE _adresseParam = CP.ChargerAdresse(_param.ID_ADRESSE_SOCIETE);
iTextSharp.text.Image img = (_param.PATH_LOGO_SOCIETE != "" && _param.PATH_LOGO_SOCIETE != null) ? iTextSharp.text.Image.GetInstance(_param.PATH_LOGO_SOCIETE) : null;
if (img != null)
{
if (img.Width / 150 > img.Height / 150) img.ScalePercent((img.Width / 150) * 100);
else img.ScalePercent((img.Height / 150) * 100);
document.Add(img);
}
PdfPTable head = new PdfPTable(6);
PdfPCell cell1 = new PdfPCell(img);
PdfPCell cell2 = new PdfPCell(new Phrase("Rapport de réception de chantier \n" + _param.NOM_SOCIETE + " - " +
_adresseParam.ADDR_VOIE + " - " +
_adresseParam.ADDR_VOIE_BIS + "\n" +
_adresseParam.ADDR_CP + " - " +
_adresseParam.ADDR_VILLE + "\n"));
float[] wid = new float[] { 0.1f, 0.9f };
head.SetWidths(wid);
cell1.HorizontalAlignment = 1;
cell2.HorizontalAlignment = 1;
head.AddCell(cell1);
head.AddCell(cell2);
document.Add(head);
}
private void PiedDePage(Document document)
{
Paragraph Footer = new Paragraph();
document.Add(Footer);
}
}
我使用方法打开我的文档:
private async Task<bool> ouvrirPDF(iTextSharp.text.Rectangle re)
{
str = await f.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
st = str.AsStreamForWrite();
using (myDocument = new Document(re)) //Création du PDF
{
using (writer = PdfWriter.GetInstance(myDocument, st))
{
PDFFooter foot = new PDFFooter();
writer.PageEvent = foot;
myDocument.Open(); //Ouverture du PDF
cb = writer.DirectContent;
}
}
return true;
}
但是当我尝试做myDocument.Open()时,我有一个例外“文档没有页面”
你能帮我解决一下吗?
答案 0 :(得分:0)
您的代码中存在两个严重错误:
OnStartPage()
方法中添加内容。document
应该用作 READ-ONLY 对象。如果禁止执行document.Add()
。相反,您应该在绝对位置添加页眉和页脚(使用作者的直接内容)。请丢弃您的代码,不要重新开始,直到之后您已阅读文档。有关示例,请参阅http://tinyurl.com/itextsharpIIA2C05