java pdf背景,使用iText java为整个pdf文档选择文本和背景

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值