Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#

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);
                
            }
            
           
        }

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.
Posted

try as below
C#
AddPageNumber("bill3.pdf","sunil1.pdf");


C#
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);
}
 
Share this answer
 
Comments
Ken Haynes 21-Feb-19 16:24pm    
Worked perfectly. Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900