你要分配HeaderText
到objHeaderFooter
在
if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
//Here i need to assign the string HeaderText to Header. I dont know how to do it.
}
假設HeaderText
是你可以這樣做使用Header
方法setHeader
的字符串:
objHeaderFooter.setHeader(new Phrase(HeaderText));
此外,您必須分配objHeaderFooter
到您的PdfWriter
示例:
pdfWriter.PageEvent = objHeaderFooter;
因此:
if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
objHeaderFooter.setHeader(new Phrase(HeaderText));
pdfWriter.PageEvent = objHeaderFooter;
}
此外,每當重寫在C#的方法,相應地將其標記爲override
。尤其是在你的頁面事件監聽器,使用
public override void onEndPage(PdfWriter writer, Document document)
這很容易忘記,尤其是因爲在Java的Java移植時的例子相應的標記@Override
是可選的。
下面是op提供的示例代碼。
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=abc.pdf");
Response.Charset = "";
Response.BinaryWrite(getbinary());
Response.End();
public byte[] getbinary()
{
Document pdfReport = null;
pdfReport = new Document(PageSize.A4, 25, 25, 40, 25);
MemoryStream msReport = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfReport, msReport);
pdfReport.Open();
if (!string.IsNullOrEmpty("Header Text"))
{
Header objHeaderFooter = new Header();
objHeaderFooter.SetHeader(new Phrase("Header Text"));
pdfWriter.PageEvent = objHeaderFooter;
}
PdfPTable ptData1 = new PdfPTable(1);
ptData1.SpacingBefore = 8;
ptData1.DefaultCell.Padding = 1;
ptData1.WidthPercentage = 100;
ptData1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
ptData1.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
PdfPCell cell1 = new PdfPCell();
cell1.BorderWidth = 0.001F;
cell1.BackgroundColor = new BaseColor(250, 250, 250);
cell1.BorderColor = new BaseColor(100, 100, 100);
cell1.Phrase = new Phrase("Sample text");
ptData1.AddCell(cell1);
PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001F;
cell.BackgroundColor = new BaseColor(200, 200, 200);
cell.BorderColor = new BaseColor(100, 100, 100);
cell.Phrase = new Phrase("test value");
ptData1.AddCell(cell);
pdfReport.Add(ptData1);
pdfReport.Close();
return msReport.ToArray();
}
public class Header : PdfPageEventHelper
{
protected Phrase header;
public void SetHeader(Phrase header)
{
this.header = header;
}
public void onEndPage(PdfWriter writer, Document document)
{
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, header, 559, 806, 0);
}
}
重複? https://stackoverflow.com/questions/18996323/add-header-and-footer-for-pdf-using-itextsharp – Ben
解決方案看起來很複雜。我正在尋找一種更簡單的方法來添加頁眉和頁腳到PDF文件使用c# –
「解決方案很複雜」不是拒絕它的參數 – mihail