int index,
Collection<? extends Page> pages
)
{
PdfDirectObject parent;
PdfDictionary parentData;
PdfDirectObject kids;
PdfArray kidsData;
int offset;
// Append operation?
if(index == -1) // Append operation.
{
// Get the parent tree node!
parent = getBaseObject();
parentData = getBaseDataObject();
// Get the parent's page collection!
kids = parentData.get(PdfName.Kids);
kidsData = (PdfArray)File.resolve(kids);
offset = 0; // Not used.
}
else // Insert operation.
{
// Get the page currently at the specified position!
Page pivotPage = get(index);
// Get the parent tree node!
parent = pivotPage.getBaseDataObject().get(PdfName.Parent);
parentData = (PdfDictionary)File.resolve(parent);
// Get the parent's page collection!
kids = parentData.get(PdfName.Kids);
kidsData = (PdfArray)File.resolve(kids);
// Get the insertion's relative position within the parent's page collection!
offset = kidsData.indexOf(pivotPage.getBaseObject());
}
// Adding the pages...
for(Page page : pages)
{
// Append?
if(index == -1) // Append.
{
// Append the page to the collection!
kidsData.add(page.getBaseObject());
}
else // Insert.
{
// Insert the page into the collection!
kidsData.add(
offset++,
page.getBaseObject()
);
}
// Bind the page to the collection!
page.getBaseDataObject().put(PdfName.Parent,parent);
page.update();
}
boolean updateParent = !File.update(kids); // Try to update the page collection.
// Incrementing the pages counters...
do
{
// Get the page collection counter!
PdfDirectObject count = parentData.get(PdfName.Count);
PdfInteger countData = (PdfInteger)File.resolve(count);
// Increment the counter at the current level!
countData.setValue(countData.getValue()+pages.size());
updateParent |= !File.update(count); // Try to update the page counter.
// Is the parent tree node to be updated?
/*
NOTE: It avoids to update the parent tree node if its modified fields are all
indirect objects which perform independent updates.
*/
if(updateParent)
{
File.update(parent);
updateParent = false; // Reset.
}
// Iterate upward!
parent = parentData.get(PdfName.Parent);
parentData = (PdfDictionary)File.resolve(parent);
} while(parent != null);
return true;
}