resources = new PDResources();
page.setResources(resources);
}
// Get the pdstream from the source page instead of creating a new one
PDStream contents = sourcePage.getContents();
boolean hasContent = contents != null;
// If request specifies the need to append to the document
if (appendContent && hasContent)
{
// Create a pdstream to append new content
PDStream contentsToAppend = new PDStream(document);
// This will be the resulting COSStreamArray after existing and new streams are merged
COSStreamArray compoundStream = null;
// If contents is already an array, a new stream is simply appended to it
if (contents.getStream() instanceof COSStreamArray)
{
compoundStream = (COSStreamArray) contents.getStream();
compoundStream.appendStream(contentsToAppend.getStream());
}
else
{
// Creates the COSStreamArray and adds the current stream plus a new one to it
COSArray newArray = new COSArray();
newArray.add(contents.getCOSObject());
newArray.add(contentsToAppend.getCOSObject());
compoundStream = new COSStreamArray(newArray);
}
if (compress)
{
List<COSName> filters = new ArrayList<COSName>();
filters.add(COSName.FLATE_DECODE);
contentsToAppend.setFilters(filters);
}
if (resetContext)
{
// create a new stream to encapsulate the existing stream
PDStream saveGraphics = new PDStream(document);
output = saveGraphics.createOutputStream();
// save the initial/unmodified graphics context
saveGraphicsState();
close();
if (compress)
{
List<COSName> filters = new ArrayList<COSName>();
filters.add(COSName.FLATE_DECODE);
saveGraphics.setFilters(filters);
}
// insert the new stream at the beginning
compoundStream.insertCOSStream(saveGraphics);
}
// Sets the compoundStream as page contents
sourcePage.setContents(new PDStream(compoundStream));
output = contentsToAppend.createOutputStream();
if (resetContext)
{
// restore the initial/unmodified graphics context
restoreGraphicsState();
}
}
else
{
if (hasContent)
{
LOG.warn("You are overwriting an existing content, you should use the append mode");
}
contents = new PDStream(document);
if (compress)
{
List<COSName> filters = new ArrayList<COSName>();
filters.add(COSName.FLATE_DECODE);
contents.setFilters(filters);