Reputation: 1387
I'm looking to take a pdf file, set the background colour for every page to black, and all the text to white.
What's the easiest way for me to do this? Is there an api call to select every page's background and all the text in the file? Or do I have to iterate through each page somehow?
Upvotes: 0
Views: 2851
Reputation: 95898
As mentioned in my last comment to your question, painting a white rectangle in blend mode Difference should do the job as long as inverting all colors is a sufficient solution for your task:
void invert(File source, File target) throws IOException, DocumentException
{
PdfReader reader = new PdfReader(source.getPath());
OutputStream os = new FileOutputStream(target);
PdfStamper stamper = new PdfStamper(reader, os);
invert(stamper);
stamper.close();
os.close();
}
void invert(PdfStamper stamper)
{
for (int i = stamper.getReader().getNumberOfPages(); i>0; i--)
{
invertPage(stamper, i);
}
}
void invertPage(PdfStamper stamper, int page)
{
Rectangle rect = stamper.getReader().getPageSize(page);
PdfContentByte cb = stamper.getOverContent(page);
PdfGState gs = new PdfGState();
gs.setBlendMode(PdfGState.BM_DIFFERENCE);
cb.setGState(gs);
cb.setColorFill(new GrayColor(1.0f));
cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
cb.fill();
cb = stamper.getUnderContent(page);
cb.setColorFill(new GrayColor(1.0f));
cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth(), rect.getHeight());
cb.fill();
}
invertPage
does draw the afore mentioned white reactangle in blend mode Difference over the page. Furthermore it paints a white rectangle normally under the page; that turned out to be necessary at least for the Acrobat Reader version I have at hands here.
You might want to tweak the code somewhat to make the result better to read. Maybe the blend mode Exclusion (BM_EXCLUSION
) is more appropriate, or maybe some other graphic state tweaks improve your reading experience. Just be creative! ;)
For some backgrounds on the PDF blending mode you might want to read section 11.3.5 Blend Mode in the PDF specification ISO 32000-1 and study the transparency related examples of iText in Action — 2nd Edition.
PS: This code only inverts the page content. Annotations are not affected. If that turns out to be necessary, you might do something similar to their appearance streams.
Upvotes: 2