【发布时间】:2018-12-03 10:06:04
【问题描述】:
我目前正在尝试添加指向 pdf 文档页脚页眉的链接,但是库给出以下错误 System.IndexOutOfRangeException: 'Requested page number 0 is out of bounds.' 当使用 IText7 库将链接添加到标题。
将相同的对象添加到页面正文可以正常工作。 用 try catch 包围代码会导致以下结果:
我在 IText7 中找不到任何关于此问题的在线代码示例,ITextSharp 中的解决方案不再适用。
我的问题是如何将外部网站的链接添加到 pdf 的标题中?当前行为是库中的错误还是有意的?
我正在使用以下代码:
main方法,加载html,初始化文档,添加对象到页眉和主页面。
public void Convert()
{
// Initialize template
IList<IElement> templateElements = HtmlConverter.ConvertToElements(File.ReadAllText("FooterTest.html"));
// Initialize document
PdfWriter pdfWriter = new PdfWriter("Output.pdf");
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
Document document = new Document(pdfDocument);
document.SetTopMargin(100);
// Adding the header object to the header and the main body
pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new PdfHeader((IBlockElement)templateElements[0], document));
document.Add((IBlockElement)templateElements[0]);
document.Close();
}
负责将对象添加到标头的事件处理程序类。代码在try-catch中给出了上面提到的错误
public class PdfHeader : IEventHandler
{
private readonly IBlockElement footer;
private readonly Document doc;
public PdfHeader(IBlockElement footer, Document doc)
{
this.doc = doc;
this.footer = footer;
}
public void HandleEvent(Event headerEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)headerEvent;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.GetLastContentStream(), page.GetResources(), pdf);
Rectangle rectangle = new Rectangle(
pdf.GetDefaultPageSize().GetX() + doc.GetLeftMargin(),
pdf.GetDefaultPageSize().GetTop() - 80,
page.GetPageSize().GetWidth() - doc.GetLeftMargin() - doc.GetRightMargin(),
50);
//Below is the code where the error is produced.
try
{
new Canvas(pdfCanvas, pdf, rectangle).Add(footer);
}
catch { }
}
}
包含 header 对象的 html 文件(在 Convert() 方法中加载的FooterTest.html)
<html>
<body>
<table>
<tr>
<td>
This is a some text not containing a link.
</td>
</tr>
<tr>
<td>
This text contains a link to <a href="https://www.google.com">Google</a> to demonstrate the issue.
</td>
</tr>
</table>
</body>
</html>
这是我关于堆栈溢出的第一个问题,因此也感谢您对问题本身的任何反馈。
【问题讨论】: