如何使用 itextsharp 将页码添加到每个 pdf 页面

how to add pagenumbers to every pdf page using itextsharp

这是我想要的,我想将页码添加到我即时生成的每个 pdf 页面。

我使用了尾页方法,但即使我添加了文档底边距也没有成功。

我决定在从文件路径生成pdf后添加页码。 这是我生成 pdf 的代码:

Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);



            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("t5.pdf", FileMode.Create));

            doc.Open();//Open Document to write

          iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7);
            Paragraph paragraph = new Paragraph("Some content");
            doc.Add(paragraph);
                doc.Add(paragraph);// add paragraph to the document
                doc.Close();
                FileStream stream = File.OpenRead("t5.pdf");
                byte[] fileBytes = new byte[stream.Length];
                stream.Read(fileBytes, 0, fileBytes.Length);
                stream.Close();
                AddPageNumbers(fileBytes);
                using (Stream file = File.OpenWrite("t5.pdf")) 
                {
                    file.Write(fileBytes, 0, fileBytes.Length);
                }
            }

她是我添加页码的方法:

MemoryStream ms = new MemoryStream();
        PdfReader reader = new PdfReader(pdf);
        int n = reader.NumberOfPages;
        iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
        Document document = new Document(psize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        document.Open();
        PdfContentByte cb = writer.DirectContent;
        int p = 0;
        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            document.NewPage();
            p++;
            PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
            cb.AddTemplate(importedPage, 0, 0);
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, +p + "/" + n, 100, 450, 0);
            cb.EndText();
        }
        document.Close();
        return ms.ToArray();

它怎么没有将页码添加到 pdf 文档中,所以这里有什么替代方法?我能做什么。

抱歉,先讲课。

当post在这里提出问题时,请只post尽可能少的代码。你的 "create a sample PDF with multiple pages" 有 116 行。在它里面你有复杂的 PdfPTableDataTable 逻辑,与问题 100% 无关。相反,以下 13 行足以制作多页 PDF:

//Create a sample multiple page PDF and place it on the desktop
var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "t5.pdf");
using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();
            for (var i = 0; i < 1000; i++) {
                doc.Add(new Paragraph(String.Format("This is paragraph #{0}", i)));
            }
            doc.Close();
        }
    }
}

其次,干掉try/catch。这些对于生产(有时)非常有用,但在开发级别,这就是我们拥有 IDE 和编译器的原因,它们会具体告诉我们哪里出了问题。

现在来谈谈更大的问题,您需要将这两个进程彼此分开。第 1 部分中的每个支架和对象都必须关闭、完成并说明。然后需要为第 2 部分提供一个完全有效的 PDF,但这两个部分都不应该 "aware" 彼此或相互依赖。

因为你刚刚 borrowed some code that wasn't intended for what you're trying to do I'm going to also ignore that and use some code that I know specifically will work。此外,由于您一开始就愿意使用 MemoryStream,所以我将在需要时避免写入磁盘。下面是一个完整的工作示例,它创建了一个多页,然后在第二遍中添加了页码。

//Will hold our PDF as a byte array
Byte[] bytes;

//Create a sample multiple page PDF, nothing special here
using (var ms = new MemoryStream()) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, ms)) {
            doc.Open();
            for (var i = 0; i < 1000; i++) {
                doc.Add(new Paragraph(String.Format("This is paragraph #{0}", i)));
            }
            doc.Close();
        }
    }
    //Store our bytes before
    bytes = ms.ToArray();
}

//Read our sample PDF and apply page numbers
using (var reader = new PdfReader(bytes)) {
    using (var ms = new MemoryStream()) {
        using (var stamper = new PdfStamper(reader, ms)) {
            int PageCount = reader.NumberOfPages;
            for (int i = 1; i <= PageCount; i++) {
                ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, new Phrase(String.Format("Page {0} of {1}", i, PageCount)), 100, 10 , 0);
            }
        }
        bytes = ms.ToArray();
    }
}

var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "t5.pdf");
System.IO.File.WriteAllBytes(outputFile, bytes);