Skip to main content
 首页 » 编程设计

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

2024年02月06日18luoye11

这是我想要的,我想将页码添加到我即时生成的每个 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 文档中,那么这里有什么选择呢?我能做什么。

请您参考如下方法:

在此处发布问题时,请仅发布尽可能少的代码。您的“创建多页样本 PDF”有 116 行长。在其中,您有复杂的 PdfPTable 和 DataTable 逻辑,它们与问题 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,但这两个部分都不应相互“了解”或相互依赖。

因为你只是borrowed一些 code那不是你想要做的事情我也会忽略它并使用一些代码 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);