gpt4 book ai didi

c# - 将自定义页面事件分配给 PdfCopy 时抛出异常

转载 作者:行者123 更新时间:2023-11-30 20:30:01 25 4
gpt4 key购买 nike

我目前正在尝试迭代现有的 PDF 并使用 OnPageEnd 事件在每个页面上标记一些页脚文本,如 iText 文档中所述,Chapter 5: Table, cell, and page events .

当我将新的自定义事件类分配给 PdfCopy 实例时,我收到此异常:

"Operation is not valid due to the current state of the object" at iTextSharp.text.pdf.PdfCopy.set_PageEvent(IPdfPageEvent value)

下面是我为执行操作而编写的代码:

PdfReader pdf = new PdfReader(file.Value);
int pages = pdf.NumberOfPages;

pdf.SelectPages(string.Format("0 - {0}", pages));
using (MemoryStream stream = new MemoryStream())
{
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, stream) { PageEvent = new PdfFooterStamp() };

doc.Open();
for (int x = 0, y = pages; x < y; x++)
{
copy.AddPage(copy.GetImportedPage(pdf, x + 1));
}

doc.Close();
copy.Flush();
copy.Close();

collection[file.Key] = stream.ToArray();
}

这是我的自定义事件类定义:

public class PdfFooterStamp : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
Rectangle rect = writer.PageSize;
ColumnText.ShowTextAligned(writer.DirectContent,
Element.ALIGN_CENTER, new Phrase("PERSONALISED DOCUMENT"),
(rect.Left + rect.Right) / 2, rect.Bottom - 18, 0);
base.OnEndPage(writer, document);
}
}

有没有人知道可能出了什么问题?

最佳答案

按照@BrunoLowagie 的建议,我选择了前一个选项,从导入的页面创建一个 PageStamp,并在迭代导入的 PDF 集合时更改它的内容。

You can keep on using PdfCopy and use PageStamp to add the text to each page that is added. Or you can create the PDF in two passes: first create the concatenated PDF in memory with PdfCopy; then add the footer with PdfStamper in a second pass.

我之前的尝试没有奏效的原因是,

PdfPageEventHelper and PdfCopy are mutually exclusive. You can't define a page event when using PdfCopy - @BrunoLowagie

以下代码是首选解决方案的示例,测试证明它可以按预期工作。

Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, stream);
doc.Open();
for (int x = 0, y = pages; x < y; x++)
{
PdfImportedPage import = copy.GetImportedPage(pdf, x + 1);
PageStamp stamp = copy.CreatePageStamp(import);
Rectangle rect = stamp.GetUnderContent().PdfWriter.PageSize;
ColumnText.ShowTextAligned(stamp.GetUnderContent(),
Element.ALIGN_CENTER, new Phrase(User.Identity.Name, font),
(rect.Bottom + rect.Top) / 2, rect.Bottom + 8, 0);

stamp.AlterContents();
copy.AddPage(import);
}

关于c# - 将自定义页面事件分配给 PdfCopy 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com