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

时间:2012-05-07 16:33:58

标签: c# asp.net itextsharp

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

2 个答案:

答案 0 :(得分:12)

您必须使用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();
}

答案 1 :(得分:1)

这样的事情应该有效:

var sourceFileList = new List<string>();

//add files to merge

int sourceIndex = 0;
PdfReader reader = new PdfReader(sourceFileList[sourceIndex]);
int sourceFilePageCount = reader.NumberOfPages;

Document doc = new Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(destinationFileName, FileMode.Create));
doc.Open();

PdfImportedPage page;
PdfContentByte contentByte = writer.DirectContent;                

int rotation;
while (sourceIndex < sourceFileList.Count)
{
    int pageIndex = 0;
    while (pageIndex < sourceFilePageCount)
    {
        pageIndex++;

        doc.SetPageSize(reader.GetPageSizeWithRotation(pageIndex));
        doc.NewPage();

        page = writer.GetImportedPage(reader, pageIndex);
        rotation = reader.GetPageRotation(pageIndex);

        if (rotation.Equals(90 | 270))
            contentByte.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height);
        else
            contentByte.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }

    sourceIndex++;
    if (sourceIndex < sourceFileList.Count)
    {
        reader = new PdfReader(sourceFileList[sourceIndex]);
        sourceFilePageCount = reader.NumberOfPages;
    }
}

doc.Close();