【问题标题】:how to add pagenumbers to every pdf page using itextsharp如何使用 itextsharp 将页码添加到每个 pdf 页面
【发布时间】:2015-05-14 16:03:31
【问题描述】:

这是我想要的,我想为我动态生成的每个 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 文档中,那么这里有什么替代方法?我该怎么办。

【问题讨论】:

    标签: c# pdf pdf-generation itextsharp


    【解决方案1】:

    对不起,先讲课。

    在此处发布问题时,请仅发布尽可能少的代码。您的“创建包含多页的示例 PDF”是 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,但这两个部分都不应该“了解”彼此或相互依赖。

    由于您只是 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);
    

    【讨论】:

    • 嗨,@Chris Haas,当我运行上面的代码并仅创建示例 PDF 时,它运行良好,但另一方面,当我尝试运行页码代码时,pdf 没有打开。
    • 示例 pdf 中的字节数为 3250,但页码中 PDF 的字节数仅为 15。所以我的代码有问题,您可以假设它为什么会这样。
    猜你喜欢
    • 2011-05-06
    • 2015-04-02
    • 1970-01-01
    • 2015-09-15
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多