提问者:小点点

将MigraDoc目录添加到PDFsharp PDF


我试图使用PDFsharp和MigraDoc从许多其他文件创建一个PDF报告文件。

基本上工作流程如下:

  1. 用户上载2个或多个文档进行连接
  2. 用户选择他们想要在TOC中包含的页面
  3. 将文档连接在一起并生成目录
// Current document is a PdfDocument and Title is the name of the bookmark
CurrentDocument.Outlines.Add(title, page, true, PdfOutlineStyle.Bold);
// 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和/或PDFSharp的理解上。

一等奖将是只使用PDFsharp添加TOC。我将感谢任何帮助被指向正确的方向。


共1个答案

匿名用户

MigraDoc是一个独立的世界--它使用PDFsharp创建PDF文件,但不能访问使用PDFsharp创建的PDF文件的内部(就像您的例子中的书签一样)。

一种方法是:使用PDFsharp创建TOC(正如您已经建议的那样)。

其他方法:使用MigraDoc将现有PDF文件中的页面添加到MigraDoc文档中,以创建最终的PDF(您可以像添加图像一样从PDF文件中添加页面)。

更新:对于只使用PDFsharp的方法,您将添加带有如下代码的链接:

PdfRectangle prect = new PdfRectangle(gfx.Transformer.WorldToDefaultPage(rect));
page.AddDocumentLink(prect, 1);

AddDocumentLink的第二个参数是目标页。