我正在尝试使用 PDFsharp 和 MigraDoc 从许多其他文件创建 PDF 报告文件。
基本上工作流程如下:
- 用户上传 2 个或更多文档以连接
- 用户选择他们想要包含在目录中的页面
- 这些文档连接在一起并生成目录
现在我可以轻松地连接文档并在 PDFsharp 中添加书签/大纲。我遇到问题的地方是使用 MigraDoc 创建目录,引用 PDFsharp 创建的书签/大纲作为超链接的目标。
在PDFsharp中添加书签/大纲的代码(成功添加书签):
// Current document is a PdfDocument and Title is the name of the bookmark
CurrentDocument.Outlines.Add(title, page, true, PdfOutlineStyle.Bold);
用于创建 TOC 页面并将其呈现到当前 PDFsharp 文档的 MigraDoc 代码:
// Create blank page
PdfPage page = (!hasTitlePage)
? AddPage(null, 0, TOC_BOOKMARK_TITLE) // Add to start
: AddPage(null, 1, TOC_BOOKMARK_TITLE); // Add after title page
// Get Graphics obj
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.MUH = PdfFontEncoding.Unicode;
// Create MigraDoc document + Setup styles
Document document = new Document();
DefineStyles(document);
// Add header
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph("Table of Contents");
paragraph.Format.Font.Size = 14;
paragraph.Format.Font.Bold = true;
paragraph.Format.SpaceAfter = 24;
paragraph.Format.OutlineLevel = OutlineLevel.Level1;
// Add links - these are the PdfSharp outlines/bookmarks added previously when concatinating the pages
foreach (var bookmark in CurrentDocument.Outlines)
{
paragraph = section.AddParagraph();
paragraph.Style = "TOC";
Hyperlink hyperlink = paragraph.AddHyperlink(bookmark.Title);
hyperlink.AddText($"{bookmark.Title}\t");
hyperlink.AddPageRefField(bookmark.Title);
}
// Render document
DocumentRenderer docRenderer = new DocumentRenderer(document);
docRenderer.PrepareDocument();
docRenderer.RenderPage(gfx, 1);
return page;
注意 - MigraDoc 代码添加了 TOC 页面,但无法识别 PDFsharp 书签。
Screenshot of the TOC:
The TOC page is added at the start (although the TOC bookmark is listed at the end) but I cannot link to PDFsharp bookmarks
我确信问题出在我对 MigraDoc 和/或 PDFsharp 的理解上。
一等奖是仅使用 PDFsharp 添加目录。我将不胜感激任何帮助指出正确的方向。