Getting unwanted TextFragment

Dear All,


Here is the code for adding “Table Of Contents” as new TextFragment, where ‘finalPDF’ is the pdf Document.
Page tocPage = finalPDF.getPages().insert(1);
TocInfo tocInfo = new TocInfo();
TextFragment title = new TextFragment(“Table Of Contents”);
title.getTextState().setFontSize(20);
title.getTextState().setFontStyle(FontStyles.Bold);
tocInfo.setTitle(title);
tocPage.setTocInfo(tocInfo);

This code works fine while saving it to the local path. But it generates “Table Of Contents” twice while writing document ByteArrayOutputStream and saving from the same ByteArrayInputStream.

Please Note contents are fine in attached file, only extra “Table Of Contents” at the bottom is headache.

Regards.

Hi there,

Thanks for your inquriy. I have tested the scenario using following code with Aspose.Pdf for Java 17.2.0 and unable to notice the reported issue, duplication of TextFragment. We will appreciate it if you please share some more details, your complete code and Aspose.Pdf for Java version, so we will further investigate the issue.

// Load an existing PDF file
com.aspose.pdf.Document doc = new com.aspose.pdf.Document(myDir + "input.pdf");

// Get access to the first page of the PDF file
com.aspose.pdf.Page tocPage = doc.getPages().insert(1);

// Create an object to represent TOC information
com.aspose.pdf.TocInfo tocInfo = new com.aspose.pdf.TocInfo();

com.aspose.pdf.TextFragment title = new com.aspose.pdf.TextFragment("Table Of Contents");

title.getTextState().setFontSize(20);
title.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Bold);

// Set the title for TOC
tocInfo.setTitle(title);

tocPage.setTocInfo(tocInfo);

// Create string objects which will be used as TOC elements
String[] titles = new String[4];

titles[0] = "First page";
titles[1] = "Second page";
titles[2] = "Third page";
titles[3] = "Fourth page";

for (int i = 0; i < 4; i++) {
    // Create a Heading object
    com.aspose.pdf.Heading heading2 = new com.aspose.pdf.Heading(1);
    com.aspose.pdf.TextSegment segment2 = new com.aspose.pdf.TextSegment();

    heading2.setTocPage(tocPage);
    heading2.getSegments().add(segment2);

    // Specify the destination page for the heading object
    heading2.setDestinationPage(doc.getPages().get_Item(i + 2));

    // Destination page
    heading2.setTop(doc.getPages().get_Item(i + 2).getRect().getHeight());

    // Destination coordinate
    segment2.setText(titles[i]);

    // Add the heading to the page containing TOC
    tocPage.getParagraphs().add(heading2);
}

ByteArrayOutputStream output = new ByteArrayOutputStream();
doc.save(output);

doc = new com.aspose.pdf.Document(new ByteArrayInputStream(output.toByteArray()));

// Save the updated document
doc.save(myDir + "TOC_Output_Java.pdf");

Best Regards,

Thanks for the code and precise definition.