I have used an open source .Net PDF class library called iTextSharp for the purpose.
Here I will mention the steps of generating the TOC.
1. First add 2 string Report parameters to your report. (I have named them as TopicsForTOC and PagesForTOC)
2. Then add two Html text boxes to the report where you need to put TOC and set the vlaue of those Html text boxes as the above added 2 report parameters subsequently.
See the figure below.

3. Don't forget to add book marks to the report headings or sub report headings which you need to add to the TOC.
4. Then using a familiar method to you generate your report once by passing null for the TopicsForTOC and PagesForTOC and get the report as byte array. (If you need to know how to generate a Telerik Report from C# code in Form base or Console application by passing parameters manually there are plenty of resources available on web. If you can't find drop a comment I will give some sample source codes)
5. Pass that byte array to the following methods to generate TOC. Don't forget to add a reference to iTextSharp.dll in your class where you add following methods. You can download the latest version of iTextSharp at sourceforge.net. I have used the itextsharp-5.0.1.1-dll for development.
public static string[] BuildToc(byte[] pdfData)
{
using (MemoryStream ms = new MemoryStream())
{
SimpleBookmark.ExportToXML(SimpleBookmark.GetBookmark(new PdfReader(new RandomAccessFileOrArray(pdfData), null)), ms, "UTF-8", false);
ms.Position = 0;
SortedList
using (XmlReader xr = XmlReader.Create(ms))
{
xr.MoveToContent();
string page = null;
string text = null;
Regex re = new Regex(@"^\d+");
while (xr.Read())
{
//Filter by the nodes with depth 1 to remove the report name from toc
if (xr.NodeType == XmlNodeType.Element && xr.Name == "Title" && xr.IsStartElement() && xr.Depth != 1)
{
// extract page number from 'Page' attribute
if (xr.GetAttribute("Page") != null)
page = re.Match(xr.GetAttribute("Page")).Captures[0].Value;
xr.Read();
if (xr.NodeType == XmlNodeType.Text)
{
text = xr.Value.Trim();
if (text != null && page != null)
sl.Add(Convert.ToInt32(page), text);
}
}
}
return createHTMLTOC(sl);
}
}
}
public static string[] createHTMLTOC(SortedList
{
StringBuilder sbTopics = new StringBuilder();
StringBuilder sbPages = new StringBuilder();
string[] tocArray = new string[2];
int index = 1;
foreach (KeyValuePair
{
sbTopics.Append(index + ". "+key.Value.ToString() + "
");
sbPages.Append(key.Key.ToString() + "
");
index++;
}
tocArray[0] = sbTopics.ToString();
tocArray[1] = sbPages.ToString();
return tocArray;
}
The TOC is returned as string array with two elements. First Element contains the Topics of TOC and second element contains the adjacent page numbers of those topics in Html format.
6. Regenerate your Telerik Report by passing the values of tocArray[0] for TopicsForTOC and tocArray[1] for PagesForTOC parameters.
7.You can see the TOC displayed in the Html Text boxes nicely.
0 comments:
Post a Comment