{
throw new IOException( "Error: Unknown colorspace " + destColorspace );
}
List pagesList = inputFile.getDocumentCatalog().getAllPages();
PDPage currentPage = null;
PDFStreamParser parser = null;
List pageTokens = null;
List editedPageTokens = null;
for(int pageCounter = 0; pageCounter < pagesList.size(); pageCounter++) // For each document page
{
currentPage = (PDPage)pagesList.get( pageCounter );
parser = new PDFStreamParser(currentPage.getContents().getStream());
parser.parse();
pageTokens = parser.getTokens();
editedPageTokens = new ArrayList();
for( int counter = 0; counter < pageTokens.size(); counter++) // For each page token
{
Object token = pageTokens.get( counter );
if( token instanceof PDFOperator ) // Test if PDFOperator
{
PDFOperator tokenOperator = (PDFOperator)token;
if(tokenOperator.getOperation().equals("rg")) // Test if "rg" Operator.
{
if( destColorspace.equals( "CMYK" ) )
{
replaceRGBTokensWithCMYKTokens( editedPageTokens, pageTokens, counter, colorEquivalents );
editedPageTokens.add( PDFOperator.getOperator( "k" ));
}
}
else if(tokenOperator.getOperation().equals("RG")) // Test if "rg" Operator.
{
if( destColorspace.equals( "CMYK" ) )
{
replaceRGBTokensWithCMYKTokens( editedPageTokens, pageTokens, counter, colorEquivalents );
editedPageTokens.add( PDFOperator.getOperator( "K" ));
}
}
else if(tokenOperator.getOperation().equals("g")) // Test if "rg" Operator.
{
if( destColorspace.equals( "CMYK" ) )
{
replaceGrayTokensWithCMYKTokens( editedPageTokens, pageTokens, counter, colorEquivalents );
editedPageTokens.add( PDFOperator.getOperator( "k" ));
}
}
else if(tokenOperator.getOperation().equals("G")) // Test if "rg" Operator.
{
if( destColorspace.equals( "CMYK" ) )
{
replaceGrayTokensWithCMYKTokens( editedPageTokens, pageTokens, counter, colorEquivalents );
editedPageTokens.add( PDFOperator.getOperator( "K" ));
}
}
else
{
editedPageTokens.add( token );
}
}
else // Test if PDFOperator
{
editedPageTokens.add( token );
}
} // For each page token
// We replace original page content by the edited one.
PDStream updatedPageContents = new PDStream(inputFile);
ContentStreamWriter contentWriter = new ContentStreamWriter( updatedPageContents.createOutputStream() );
contentWriter.writeTokens( editedPageTokens );
currentPage.setContents( updatedPageContents );
} // For each document page
}