Search code examples
c#asp.net-mvcitextpdf-generationitext7

iText7- bookmark is not jumping to a page


In ASP.NET application I'm using iText7 to create a new pdf with bookmarks. With the following code, I'm able to create a pdf with a number of pages and bookmarks but when I click on the bookmark nothing happens. How do I make reader navigate to related page when one clicks a bookmark.

public ActionResult CreatePdf()
{
    byte[] pdfBytes;
    using (var stream = new MemoryStream())
    using (var wri = new PdfWriter(stream))
    using (var pdf = new PdfDocument(wri))
    using (var doc = new Document(pdf))
    {   

        doc.Add(new Paragraph("Working with iText7"));

        doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        PdfOutline root = pdf.GetOutlines(false);

        foreach (var item in col1)
        {
                        
            doc.Add(new Paragraph(item.Name));
            root.AddOutline(item.Name);
            doc.Add(new AreaBreak());
        }

        doc.Close();
        doc.Flush();
        pdfBytes = stream.ToArray();
    }

    return File(pdfBytes, "application/pdf", "test.pdf");
}

Solution

  • public ActionResult CreatePdf()
    {
        byte[] pdfBytes;
        using (var stream = new MemoryStream())
        using (var wri = new PdfWriter(stream))
        using (var pdf = new PdfDocument(wri))
        using (var doc = new Document(pdf))
        {
            List<Destination> destinations = new List<Destination>();
    
            doc.Add(new Paragraph("Working with iText7"));
    
            // Iterate through your collection (col1) and add content and destinations
            for (int i = 0; i < col1.Count; i++)
            {
                var item = col1[i];
    
                Destination destination = PdfExplicitDestination.CreateFitH(i + 1, doc.GetPdfDocument().GetPage(i + 1));
                destinations.Add(destination);
    
                doc.Add(new Paragraph(item.Name));
                doc.Add(new AreaBreak());
            }
    
            PdfOutline root = pdf.GetOutlines(false);
    
            for (int i = 0; i < col1.Count; i++)
            {
                var item = col1[i];
                root.AddOutline(item.Name).AddDestination(destinations[i]);
            }
    
            doc.Close();
            doc.Flush();
            pdfBytes = stream.ToArray();
        }
    
        return File(pdfBytes, "application/pdf", "test.pdf");
    }
    

    Check this code. Good luck!