在iText7(.NET)中为现有PDF的每一页添加页脚



我在运行时使用模板文件在itext7.pdfHTML中构建PDF。我想为生成的PDF的每一页添加一个页脚,它有两页,但由于某种原因,页脚只出现在第二页。

我正试图在iText网站的这个例子的基础上进行构建。这个例子涉及页码,但由于我只是在文档中添加静态文本,所以原理是一样的。这是我的代码:

string footer = "This is the footer".
string body = "<span>This is raw HTML</span>";
//create a temporary PDF with the raw HTML, made from my template and given data
private void createPDF()
{
destination = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/pdf_repo"), "tempFile.pdf");
ConverterProperties properties = new ConverterProperties();
properties.SetBaseUri(HttpContext.Current.Server.MapPath("~/templates/"));
HtmlConverter.ConvertToPdf(body, new FileStream(destination, FileMode.Create), properties);
addFooter(id);
}
//modify the PDF file created above by adding the footer
private void addFooter(string id)
{
string newFile = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("pdf_repo", "finalFile.pdf");
PdfDocument pdfDoc = new PdfDocument(new PdfReader(destination), new PdfWriter(newFile));
Document doc = new Document(pdfDoc);
Paragraph foot = new Paragraph(footer);
foot.SetFontSize(8);
float x = 300; //559
float y = 0; //806
int numberOfPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
doc.ShowTextAligned(foot, x, y, TextAlignment.CENTER, VerticalAlignment.BOTTOM);
}
doc.Close();
//delete temporary PDF
File.Delete(destination);
}

我尝试在addFooter((中将I设置为0;对于";循环,但这并不能解决问题。如何使页脚显示在每页上?

是的,您没有指定将页脚添加到哪个页面,所以它只将其添加到整个文档的底部。试试这个:

注意,唯一的变化是:doc.ShowTextAligned(foot, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM);

string footer = "This is the footer".
string body = "<span>This is raw HTML</span>";
//create a temporary PDF with the raw HTML, made from my template and given data
private void createPDF()
{
destination = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/pdf_repo"), "tempFile.pdf");
ConverterProperties properties = new ConverterProperties();
properties.SetBaseUri(HttpContext.Current.Server.MapPath("~/templates/"));
HtmlConverter.ConvertToPdf(body, new FileStream(destination, FileMode.Create), properties);
addFooter(id);
}
//modify the PDF file created above by adding the footer
private void addFooter(string id)
{
string newFile = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("pdf_repo", "finalFile.pdf");
PdfDocument pdfDoc = new PdfDocument(new PdfReader(destination), new PdfWriter(newFile));
Document doc = new Document(pdfDoc);
Paragraph foot = new Paragraph(footer);
foot.SetFontSize(8);
float x = 300; //559
float y = 0; //806
int numberOfPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
doc.ShowTextAligned(foot, x, y, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM);
}
doc.Close();
//delete temporary PDF
File.Delete(destination);
}

最新更新