使用itextsharp将页码添加到pdf [英] adding page number to pdf using itextsharp

查看:387
本文介绍了使用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[^]


这篇关于使用itextsharp将页码添加到pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆