首页 文章

如何在PDF中获取每个部分的页数

提问于
浏览
0

我正在使用MigraDoc呈现PDF文档 . 每个部分都有一个或多个段落文本 .

目前这是我创建文档的方式;

var document = new Document();
var pdfRenderer = new PdfDocumentRenderer(true);
pdfRenderer.Document = document; 

for(int i=0;i<10;i++){
    Section section = document.AddSection();
    section.PageSetup.PageFormat = PageFormat.A4;

    for(int j=0;j<5;j++) {
    var paragraphText = GetParaText(i,j); // some large text can span multiple pages
    section.AddParagraph(paragraphText);
    //Want page count per section? 
     // Section 1 -> 5 , Section 2 ->3 etc.
    // int count = CalculateCurrentPageCount(); //*EDIT*
   }
}
// Create the PDF document
pdfRenderer.RenderDocument();
pdfRenderer.Save(filename);

Edit :目前我使用以下代码来获取页数 .
但它需要花费很多时间,可能每个页面都会呈现两次 .

public int CalculateCurrentPageCount()
        {
            var tempDocument = document.Clone();
            tempDocument.BindToRenderer(null);     
            var pdfRenderer = new PdfDocumentRenderer(true);
            pdfRenderer.Document = tempDocument;
            pdfRenderer.RenderDocument();
            int count = pdfRenderer.PdfDocument.PageCount;
            Console.WriteLine("-- Count :" + count);
            return count;
        }

根据添加的内容,某些部分可以跨越多个页面 .

是否可以获取/查找部分渲染所需的页数(以PDF格式)?

Edit 2 :是否可以标记一个部分并找到它开始的页面?

2 回答

  • 0

    谢谢你的帮助 . 我像这样计算它(即要获得代码中的计数......):

    首先,我用该部分的创建计数标记该部分

    newsection.Tag = num_sections_in_doc; //count changes every time i add a section
    

    然后我使用GetDocumentObjectsFromPage:

    var x = new Dictionary<int, int>();
                    int numpages = pdfRenderer.PdfDocument.PageCount;
                    for (int idx = 0; idx < numpages; idx++)
                    {
                        DocumentObject[] docObjects = pdfRenderer.DocumentRenderer.GetDocumentObjectsFromPage(idx + 1);
                        if (docObjects != null && docObjects.Length > 0)
                        {
                            Section section = docObjects[0].Section;
                            int sectionTag = -1;
                            if (section != null)
                                sectionTag = (int)section.Tag;
                            if (sectionTag >= 0)
                            {
                                // count a section only once
                                if (!x.ContainsKey(sectionTag))
                                    x.Add(sectionTag, idx + 1);
                            }
                        }
                    }
    

    x.Keys是这些部分 .
    和x.values是每个部分的开头 .

  • 1

    如果要在PDF中显示页数,请使用 paragraph.AddSectionPagesField() .

    也可以看看:
    https://stackoverflow.com/a/19499231/162529

    要获取代码中的计数:您可以将标记添加到任何文档对象(例如,添加到任何段落),然后使用 docRenderer.GetDocumentObjectsFromPage(...) 查询特定页面的对象 . 这允许您找出此页面上的对象属于哪个部分 .

    或者在单独的文档中创建每个部分,然后使用 docRenderer.RenderPage(...) 将它们组合成一个PDF,如下所示:
    http://www.pdfsharp.net/wiki/MixMigraDocAndPdfSharp-sample.ashx
    该示例将页面缩小到缩略图大小 - 您将在新页面上以1:1的比例绘制它们 .

相关问题