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?
解决方案
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.
本文探讨如何使用Java将PDF文件每页背景设为黑色、文本设为白色。给出了实现该功能的代码示例,包括`invert`、`invertPage`等方法,通过在混合模式下绘制白色矩形来实现颜色反转,还提及可调整代码优化阅读体验,并给出相关参考资料。
3121

被折叠的 条评论
为什么被折叠?



