如何在itextsharpHtml-to-pdf转换器中应用页眉图像
本文关键字:应用 图像 转换器 itextsharpHtml-to-pdf | 更新日期: 2023-09-27 18:29:47
请给我任何解决方案;我使用的是这个代码:
HeaderFooter header = new HeaderFooter(new Phrase("This is a header"), false);
document.Header = header;
但是出现了这个错误:
CS0246:
找不到类型或命名空间名称"HeaderFooter"(您是缺少using指令或程序集引用?
该代码在多年前就被弃用并删除了,但不幸的是,它仍然存在于源代码的注释中。
您想要做的是将iTextSharp.text.pdf.PdfPageEventHelper
类划分为子类,并处理OnEndPage
方法,该方法将对文档中的每一页调用一次:
public class MyPageEventHandler : iTextSharp.text.pdf.PdfPageEventHelper {
public override void OnEndPage(PdfWriter writer, Document document) {
//Create a simple ColumnText object
var CT = new ColumnText(writer.DirectContent);
//Bind it to the top of the document but take up the entire page width
CT.SetSimpleColumn(0, document.PageSize.Height - 20, document.PageSize.Width, document.PageSize.Height);
//Add some text
CT.AddText(new Phrase("This is a test"));
//Draw our ColumnText object
CT.Go();
}
}
要使用它,只需将它的一个新实例绑定到PdfWriter
的PageEvent
属性:
writer.PageEvent = new MyPageEventHandler();
以下是针对iTextSharp 5.1.2.0的完整的C#2010 WinForms应用程序,显示了以下内容:
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
//Test file to create
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard PDF file stream creation
using (FileStream output = new FileStream(outputFile, FileMode.Create,FileAccess.Write,FileShare.None)){
using (Document document = new Document(PageSize.LETTER)) {
using (PdfWriter writer = PdfWriter.GetInstance(document, output)) {
//Bind our custom event handler to the PdfWriter
writer.PageEvent = new MyPageEventHandler();
//Open our PDF for writing
document.Open();
//Add some text to page 1
document.Add(new Paragraph("This is page 1"));
//Add a new page
document.NewPage();
//Add some text to page 2
document.Add(new Paragraph("This is page 2"));
//Close the PDF
document.Close();
}
}
}
this.Close();
}
}
public class MyPageEventHandler : iTextSharp.text.pdf.PdfPageEventHelper {
public override void OnEndPage(PdfWriter writer, Document document) {
//Create a simple ColumnText object
var CT = new ColumnText(writer.DirectContent);
//Bind it to the top of the document but take up the entire page width
CT.SetSimpleColumn(0, document.PageSize.Height - 20, document.PageSize.Width, document.PageSize.Height);
//Add some text
CT.AddText(new Phrase("This is a test"));
//Draw our ColumnText object
CT.Go();
}
}
}