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

时间:2013-10-22 06:39:40

标签: c# pdfsharp migradoc

我正在使用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);

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

 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格式)?

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

2 个答案:

答案 0 :(得分:1)

请求帮助。我像这样计算它(即要在代码中得到计数......):

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

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 :(得分:0)

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

另见:
https://stackoverflow.com/a/19499231/162529

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

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

相关问题