我正在尝试使用页脚创建一个pdf。 我尝试使用以下代码在我的pdf文件中设置页脚。
private void AddFooter(string filephysicalpath, string documentname)
{
byte[] bytes = System.IO.File.ReadAllBytes(filephysicalpath);
Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
string footer = Convert.ToString(Session["Footer"]);
footer += "\n";
footer += documentname;
Phrase ph = new Phrase(footer);
Rectangle rect = new Rectangle(10f, 10f, 0);
ColumnText ct = new ColumnText(stamper.GetUnderContent(i));
ct.SetSimpleColumn(rect);
ct.AddElement(new Paragraph("line 1"));
ct.AddElement(new Paragraph("line 2"));
ct.Go();
// ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_JUSTIFIED, new Phrase(ph), 8f, 5f, 0);
}
}
bytes = stream.ToArray();
}
System.IO.File.WriteAllBytes(filephysicalpath, bytes);
}
我没有使用此代码获取页脚。
答案 0 :(得分:0)
这有两个原因:
Rectangle rect = new Rectangle(10f,10f,0);
原因#1:
此代码无法工作,因为您正在创建一个左下角坐标(0, 0)
,右上角坐标(10, 10)
和旋转0的矩形。这是一个测量为0.14的矩形x 0.14英寸(或0.35 x 0.35厘米)。这绝不适合这两条线!
原因#2:
您正在使用硬编码值来定义Rectangle
。请查看文档,更具体地说,请参阅常见问题条目How to position text relative to page?
您必须获取现有页面的尺寸,并相应地定义您的坐标!
float marginLR = 36;
float marginB = 2;
float footerHeight = 34;
Rectangle pagesize = reader.GetCropBox(i);
if (pagesize == null) {
pagesize = reader.GetPageSize(i);
}
Rectangle rect = new Rectangle(
pagesize.Left + marginLR, pagesize.Bottom + margin,
pagesize.Right - marginLR, pagesize.Bottom + margin + footerheight
);
您还可以阅读Get exact cordinates of the page to add a watermark with different page rotation using iTextSharp