在内容列表中创建缩进和数字(itextsharp)

时间:2016-10-04 10:41:17

标签: c# pdf text itext tableofcontents

我对TOC有疑问。如何使用缩进和数字创建TOC?

现在我没有它的TOC(只是列表)。我使用ChunkParagraph创建了它。我应该用它来创建TOC吗?也许我应该使用List并添加到文档?

我在这里创建TOC:

private int CreateTOC(XmlNode xmlNode, Document doc, PdfWriter writer, int number)
    {
        var toc = ev.GetTOC();
        KeyValuePair<string, int> value;

        Chunk dottedLine = new Chunk(new iTextSharp.text.pdf.draw.DottedLineSeparator());

        for (int i = 0; i < xmlNode.ChildNodes.Count; i++)
        {
            var text = xmlNode.ChildNodes[i].Attributes["text"].Value;
            value = toc[text];
            var dest = value.Key;
            var page = value.Value;

            var c = new Chunk((i+1).ToString()+ ". " + text, font);
            c.SetAction(PdfAction.GotoLocalPage(dest, false));

            var p = new Paragraph(c);
            p.Add(dottedLine);

            c = new Chunk(page.ToString(), font);
            c.SetAction(PdfAction.GotoLocalPage(dest, false));
            p.Add(c);
            doc.Add(p);


            CreateTOC(xmlNode.ChildNodes[i], doc, writer, i+1);
        }
        return writer.PageNumber;
    }

我参考内容章节获取列表。 但我需要以下内容:

1. chapter1-------------------1page
  1.1 subchupter1-------------2page
  1.2 subchupter2-------------2page
  1.3 subchupter3-------------3page
2. chupter2-------------------4page
  2.1 subchupter4-------------4page
  2.3 subchupter4-------------4page
     2.3.1 subsubchupter------5page
     ...
     ...
     ...

我该如何解决?

谢谢!

1 个答案:

答案 0 :(得分:2)

引入一个级别并将该级别与缩进值相乘。将该值用作IndentationLeft的值:

private int CreateTOC(XmlNode xmlNode, Document doc, PdfWriter writer, int number, int level) {
    var toc = ev.GetTOC();
    KeyValuePair<string, int> value;

    Chunk dottedLine = new Chunk(new iTextSharp.text.pdf.draw.DottedLineSeparator());

    for (int i = 0; i < xmlNode.ChildNodes.Count; i++)
    {
        var text = xmlNode.ChildNodes[i].Attributes["text"].Value;
        value = toc[text];
        var dest = value.Key;
        var page = value.Value;

        var c = new Chunk((i+1).ToString()+ ". " + text, font);
        c.SetAction(PdfAction.GotoLocalPage(dest, false));

        var p = new Paragraph(c);
        p.IndentationLeft = 10 * level;
        p.Add(dottedLine);

        c = new Chunk(page.ToString(), font);
        c.SetAction(PdfAction.GotoLocalPage(dest, false));
        p.Add(c);
        doc.Add(p);


        CreateTOC(xmlNode.ChildNodes[i], doc, writer, i+1, level + 1);
    }
    return writer.PageNumber;
}

首次致电0时,level使用CreateToc()