mihir patel
mihir patel

Reputation: 191

Add file with bookmark

I want to add a PDF file using iTextSharp but if PDF file contains bookmarks then they should also be added.

Currently I'm using following code

Document document = new Document();
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));
writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
//Step 3: Open the document
document.Open();

PdfContentByte cb = writer.DirectContent;

//The current file path
string filename = "D:\\rtf\\2.pdf";

// we create a reader for the document
PdfReader reader = new PdfReader(filename);

//Chapter ch = new Chapter("", 1);

for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
    document.SetPageSize(reader.GetPageSizeWithRotation(1));
    document.NewPage();

    // Insert to Destination on the first page
    if (pageNumber == 1)
    {
        Chunk fileRef = new Chunk(" ");
        fileRef.SetLocalDestination(filename);
        document.Add(fileRef);
    }

    PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
    int rotation = reader.GetPageRotation(pageNumber);
    if (rotation == 90 || rotation == 270)
    {
        cb.Add(page);
    }
    else
    {
        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
}

document.Close();

Upvotes: 1

Views: 1971

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

Please read Chapter 6 of my book. In table 6.1, you'll read:

Can import pages from other PDF documents. The major downside is that all interactive features of the imported page (annotations, bookmarks, fields, and so forth) are lost in the process.

This is exactly what you experience. However, if you look at the other classes listed in that table, you'll discover PdfStamper, PdfCopy, etc... which are classes that do preserve interactive features.

PdfStamper will keep the bookmarks. If you want to use PdfCopy (or PdfSmartCopy), you need to read chapter 7 to find out how to keep them. Chapter 7 isn't available for free, but you can consult the examples here: Java / C#. You need the ConcatenateBookmarks example.

Note that you're code currently looks convoluted because you're not using the correct classes. Using PdfStamper should significantly reduce the number of lines of code.

Upvotes: 1

Related Questions