使用itextsharp将页码添加到pdf
问题描述:
void addnumber()
{
PdfReader rd = new PdfReader("bill3.pdf");
PdfStamper ps = new PdfStamper(rd, new FileStream("sunil1.pdf", FileMode.Create));
PdfImportedPage page;
for (int i = 1; i <= rd.NumberOfPages; i++)
{
PdfContentByte canvas = ps.GetOverContent(i);
page = ps.GetImportedPage(rd, i);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA,BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
canvas.SetColorFill(BaseColor.DARK_GRAY);
canvas.BeginText();
canvas.SetFontAndSize(bf, 6);
canvas.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "page number "+i, 300.7f, 60.7f, 0);
canvas.EndText();
canvas.AddTemplate(page, 0, 0);
}
}
当我打开创建的sunf1的pdf文件时。 pdf然后我收到一条错误信息,说文件已损坏且无法修复。
While i open the pdf file which is created that is sunil1.pdf then i got an error message that the file is damaged and could not repaired.
答
尝试如下
try as below
AddPageNumber("bill3.pdf","sunil1.pdf");
void AddPageNumber(string fileIn, string fileOut)
{
byte[] bytes = File.ReadAllBytes(fileIn);
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++)
{
ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(fileOut, bytes);
}
首先尝试这些链接 -
iTextSharp:使用C#和VB.Net将页码添加到现有PDF [ ^ ]
iTextSharp - 将页眉/页脚添加到PDF [ ^ ]
Try these links first -
iTextSharp: Add Page numbers to existing PDF using C# and VB.Net [^]
iTextSharp–Add header/footer to PDF[^]