c# - 将页码添加到 pdf 文档 (itextsharp)

标签 c# asp.net itext

我想将页码添加到 itextsharp pdf 文件的页脚。我从 html(asp.net 转发器)生成 pdf。我使用 XMLWorkerHelper 来解析 html 内容。我搜索了很多但找不到任何有用的东西实现这一目标。

最佳答案

您必须使用 iTextSharp 打开 PDF 并自行添加页码。我前段时间做了类似的事情,这是我的功能,可能会让你开始。 该函数将当前页面添加到左下角,因此您可能必须将其放置在适合您需要的其他位置。

public static byte[] AddPageNumbers(byte[] pdf)
{
MemoryStream ms = new MemoryStream();
// we create a reader for a certain document
PdfReader reader = new PdfReader(pdf);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// we retrieve the size of the first page
Rectangle psize = reader.GetPageSize(1);

// step 1: creation of a document-object
Document document = new Document(psize, 50, 50, 50, 50);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3: we open the document

document.Open();
// step 4: we add content
PdfContentByte cb = writer.DirectContent;

int p = 0;
Console.WriteLine("There are " + n + " pages in the document.");
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_LEFT, +p + "/" + n, 7, 44, 0);
    cb.EndText();
}
// step 5: we close the document
document.Close();
return ms.ToArray();
}

关于c# - 将页码添加到 pdf 文档 (itextsharp),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485728/

相关文章:

c# - 在 IIS 上运行时,Web 应用程序无法与 Web 服务通信

c# - 我下面的代码给了我一个问题,图像出现在文本之后

c# 如何使用 iTextsharp 从 pdf 返回字节数组

javascript - PDF 动态内容 - 这可能吗?

pdf - 删除表格标题单元格 itext7 pdf 的边框

c# - 所有枚举的枚举扩展

c# - 当属性之一可以为 null 时 GetHashCode

c# - 在 C# 或 VB.Net 中创建内存泄漏

c# - c#中的异常处理

c# - 获取动态添加的子控件以显示在 UI 中