|
Hi people, lately, i've been working on a script to replace RGB colors by CMYK ones "manually". With this code, you can specify by witch CMYK color you want to replace the RGB one. This code is based on PDFBox (www.pdfbox.org). I hope it will help people that need to do exact RGB -> CMYK conversion ;) Pierre-Yves Landuré Dorigo Consultants |
/** * Copyright (c) 2003-2004, www.pdfbox.org * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of pdfbox; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://www.pdfbox.org * */ package org.pdfbox;
import java.util.List;
import org.pdfbox.exceptions.InvalidPasswordException;
import org.pdfbox.cos.COSFloat;
import org.pdfbox.cos.COSNumber;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.PDPage;
import org.pdfbox.pdmodel.common.PDStream;
import org.pdfbox.pdfparser.PDFStreamParser;
import org.pdfbox.pdfwriter.ContentStreamWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import org.pdfbox.util.PDFOperator;
import java.awt.Color;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.apache.log4j.Logger;
/**
* This is the main program that simply parses the pdf document and replace RGB
* colors by CMYK ones.
*
* @author Ben Litchfield ([EMAIL PROTECTED])
* @author Pierre-Yves Landuré ([EMAIL PROTECTED])
* @version $Revision: 0.1 $
*/
public class RgbToCmyk
{
private static final Logger LOG = Logger.getLogger( RgbToCmyk.class );
private static final String PASSWORD = "-password";
private static final String CONVERSION = "-equiv";
/**
* private constructor.
*/
private RgbToCmyk()
{
//static class
}
/**
* The method that replace RGB colors by CMYK ones.
*
* @param inputFile input file name.
* @param outputFile output file name.
* @param colorEquivalents a dictionnary for the color equivalents.
* @param password the password to use if document is encrypted.
*
* @throws Exception If there is an error parsing the document.
*/
public static void replaceColors( String inputFile, String outputFile,
Hashtable<Color, Color> colorEquivalents,
String password) throws Exception
{
PDDocument document = null;
try
{
document = PDDocument.load( inputFile );
//document.print();
if( document.isEncrypted() )
{
try
{
document.decrypt( password );
}
catch( InvalidPasswordException e )
{
if( password == "" )//they supplied the wrong password
{
System.err.println( "Error: The supplied password is incorrect." );
System.exit( 2 );
}
else
{
//they didn't suppply a password and the default of "" was wrong.
System.err.println( "Error: The document is encrypted." );
usage();
}
}
}
List pagesList = document.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.
{
// Get current RGB color.
COSNumber cosRed = (COSNumber)pageTokens.get( counter - 3 );
COSNumber cosGreen = (COSNumber)pageTokens.get( counter - 2 );
COSNumber cosBlue = (COSNumber)pageTokens.get( counter - 1 );
int red = Math.round(cosRed.floatValue() * 255.0f);
int green = Math.round(cosGreen.floatValue() * 255.0f);
int blue = Math.round(cosBlue.floatValue() * 255.0f);
Color rgbColor = new Color(red, green, blue);
Color cmykColor = colorEquivalents.get(rgbColor);
if ( cmykColor == null )
{
// We put the error in red.
cmykColor = new Color(0, 100, 100, 0);
}
//remove the RGB components that are already part of the editedPageTokens list
editedPageTokens.remove( editedPageTokens.size() -1 );
editedPageTokens.remove( editedPageTokens.size() -1 );
editedPageTokens.remove( editedPageTokens.size() -1 );
float cyan = cmykColor.getRed() / 100;
float magenta = cmykColor.getGreen() / 100;
float yellow = cmykColor.getBlue() / 100;
float black = cmykColor.getAlpha() / 100;
// Add the new CMYK color
editedPageTokens.add( new COSFloat( cyan ) );
editedPageTokens.add( new COSFloat( magenta ) );
editedPageTokens.add( new COSFloat( yellow ) );
editedPageTokens.add( new COSFloat( black ) );
editedPageTokens.add( PDFOperator.getOperator( "k" ));
}
else // Test if "rg" Operator.
{
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(document);
ContentStreamWriter contentWriter = new ContentStreamWriter( updatedPageContents.createOutputStream() );
contentWriter.writeTokens( editedPageTokens );
currentPage.setContents( updatedPageContents );
} // For each document page
document.save(outputFile);
}
finally
{
if( document != null )
{
document.close();
}
}
}
/**
* Infamous main method.
*
* @param args Command line arguments, should be one and a reference to a file.
*
* @throws Exception If there is an error parsing the document.
*/
public static void main( String[] args ) throws Exception
{
String password = "";
String inputFile = null;
String outputFile = null;
Pattern colorEquivalentPattern = Pattern.compile("^\\((\\d+),(\\d+),(\\d+)\\)"
+ "=\\((\\d+),(\\d+),(\\d+),(\\d+)\\)$");
Matcher colorEquivalentMatcher = null;
Hashtable<Color, Color> colorEquivalents = new Hashtable<Color, Color>();
int startPage = 1;
int endPage = Integer.MAX_VALUE;
for( int i=0; i<args.length; i++ )
{
if( args[i].equals( PASSWORD ) )
{
i++;
if( i >= args.length )
{
usage();
}
password = args[i];
}
if(args[i].equals( CONVERSION ) )
{
i++;
if( i >= args.length )
{
usage();
}
colorEquivalentMatcher = colorEquivalentPattern.matcher(args[i]);
if(! colorEquivalentMatcher.matches())
{
usage();
}
int red = Integer.valueOf(colorEquivalentMatcher.group(1)).intValue();
int green = Integer.valueOf(colorEquivalentMatcher.group(2)).intValue();
int blue = Integer.valueOf(colorEquivalentMatcher.group(3)).intValue();
Color rgbValue = new Color(red, green, blue);
int cyan = Integer.valueOf(colorEquivalentMatcher.group(4)).intValue();
int magenta = Integer.valueOf(colorEquivalentMatcher.group(5)).intValue();
int yellow = Integer.valueOf(colorEquivalentMatcher.group(6)).intValue();
int black = Integer.valueOf(colorEquivalentMatcher.group(7)).intValue();
Color cmykValue = new Color(cyan, magenta, yellow, black);
colorEquivalents.put(rgbValue, cmykValue);
}
else
{
if( inputFile == null )
{
inputFile = args[i];
}
else
{
outputFile = args[i];
}
}
}
if( inputFile == null )
{
usage();
}
if( outputFile == null || outputFile.equals(inputFile))
{
usage();
}
RgbToCmyk.replaceColors(inputFile, outputFile, colorEquivalents, password);
}
/**
* This will print the usage requirements and exit.
*/
private static void usage()
{
System.err.println( "Usage: java org.pdfbox.RgbToCmyk [OPTIONS] <PDF Input file> <PDF Output File>\n" +
" -password <password> Password to decrypt document\n" +
" -equiv <color equivalent> Color equivalent to use for conversion." +
" The format is : (R,G,B)=(C,M,Y,K) where R,G,B are integer between 0 and 255" +
" and C,M,Y,K are integer between 0 and 100. This option can be used as many times as necessary\n" +
" <PDF Input file> The PDF document to use\n" +
" <PDF Output file> The PDF file to write the result to. Must be different of input file\n"
);
System.exit( 1 );
}
}
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
