直接說問題,itext沒有直接提供替換PDF中文本的接口(查看資料得到的結論是PDF不支持這種操作),不過存在解決思路:在需要替換的文本上覆蓋新的文本。按照這個思路我們需要解決以下幾個問題:
- itext怎樣增加白色底的覆蓋層
- 找到覆蓋層的位置(左頂點的位置)和高度與寬帶
這樣做的目的是什么了?也告訴下大家,比如:現在要你將業務數據導出成PDF存檔,且PDF的模板有現成的。對我們寫程序的來說,變化的只是部分數據,假如我們可以直接替換里面的數據,是不是可以節省我們的開發時間。
1、itext怎樣增加覆蓋層?
itext在自己的Demo中提供了很多案例代碼,從中我們可以看到高亮的案例
查看itext代碼
這里可以在任意位置產生一個層,符合我們的“遮蓋層”的要求,不過,通過測試發現此段代碼存在一個問題點,它無法遮擋住文字,只是添加了一個背景層。為了達到我們的要求,我們只需要修改一處地方:
- /*
- * This example was written in answer to the question:
- * http://stackoverflow.com/questions/33952183
- */
- package sandbox.stamper;
- import com.itextpdf.text.BaseColor;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.pdf.PdfContentByte;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.PdfStamper;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- /**
- *
- * @author Bruno Lowagie (iText Software)
- */
- public class HighLightByAddingContent {
- public static final String SRC = "resources/pdfs/hello.pdf";
- public static final String DEST = "results/stamper/hello_highlighted.pdf";
- public static void main(String[] args) throws IOException, DocumentException {
- File file = new File(DEST);
- file.getParentFile().mkdirs();
- new HighLightByAddingContent().manipulatePdf(SRC, DEST);
- }
- public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
- PdfReader reader = new PdfReader(src);
- PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
- PdfContentByte canvas = stamper.getUnderContent(1);
- canvas.saveState();
- canvas.setColorFill(BaseColor.YELLOW);
- canvas.rectangle(36, 786, 66, 16);
- canvas.fill();
- canvas.restoreState();
- stamper.close();
- reader.close();
- }
- }
- PdfContentByte canvas = stamper.getUnderContent(1); //變成 PdfContentByte canvas = stamper.getOverContent(1);
- /**********************************************************************
- * <pre>
- * FILE : HighLightByAddingContent.java
- * CLASS : HighLightByAddingContent
- *
- *
- * FUNCTION : TODO
- *
- *
- *======================================================================
- * CHANGE HISTORY LOG
- *----------------------------------------------------------------------
- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ.
- *----------------------------------------------------------------------
- *
- * DESCRIPTION:
- * </pre>
- ***********************************************************************/
- package com.cx.itext;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.URLDecoder;
- import com.itextpdf.text.BaseColor;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Font;
- import com.itextpdf.text.pdf.BaseFont;
- import com.itextpdf.text.pdf.PdfContentByte;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.PdfStamper;
- public class HighLightByAddingContent {
- @SuppressWarnings("deprecation")
- public static final String SRC = URLDecoder.decode(HighLightByAddingContent.class.getResource("ticket.pdf").getFile());
- public static final String DEST = "I://ticket.pdf";
- public static void main(String[] args) throws IOException, DocumentException {
- File file = new File(DEST);
- file.getParentFile().mkdirs();
- new HighLightByAddingContent().manipulatePdf(SRC, DEST);
- }
- public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
- PdfReader reader = new PdfReader(src);
- PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
- PdfContentByte canvas = stamper.getOverContent(1);
- float height=595;
- System.out.println(canvas.getHorizontalScaling());
- float x,y;
- x= 216;
- y = height -49.09F;
- canvas.saveState();
- canvas.setColorFill(BaseColor.WHITE);
- canvas.rectangle(x, y-5, 43, 15);
- canvas.fill();
- canvas.restoreState();
- //開始寫入文本
- canvas.beginText();
- //BaseFont bf = BaseFont.createFont(URLDecoder.decode(CutAndPaste.class.getResource("/AdobeSongStd-Light.otf").getFile()), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
- BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
- Font font = new Font(bf,10,Font.BOLD);
- //設置字體和大小
- canvas.setFontAndSize(font.getBaseFont(), 10);
- //設置字體的輸出位置
- canvas.setTextMatrix(x, y);
- //要輸出的text
- canvas.showText("多退少補" );
- //設置字體的輸出位置
- canvas.setFontAndSize(font.getBaseFont(), 20);
- canvas.setTextMatrix(x, y-90);
- //要輸出的text
- canvas.showText("多退少補" );
- canvas.endText();
- stamper.close();
- reader.close();
- System.out.println("complete");
- }
- }
2、找到覆蓋層的位置(左頂點的位置)和高度與寬帶
我的第一個想法是通過工具得到替換文本的具體位置,雖然這個方法不怎么好,不過確實可行。使用到的工具是常用的Adobe Reader,以下是正常頁面(PDF是網上搜的,百度key:“申請 filetype:pdf”):


Adobe提供了測量工具,我們可以通過“編輯-->分析-->測量工具”看到如下頁面:


此時,我們雖然可以直接測量,但是測量默認顯示的厘米,與itext需要設置的單位不一致,我們需要手工換算下(1英寸=72點)。不過,adobe可以幫我們省掉換算的工作,右鍵點擊,出現以下選項(需要在測量功能下右鍵):


“更改比例”可以幫助我們完成換算工作。(ps:“顯示標尺”是一個不錯的選項)。最后的畫面如下:


最后,需要提醒下,itext的Y是從下往上算的。
這樣得到位置是不是太不方便了。那我們是否可以通過itext自動計算出我們需要的位置?代碼如下(從網上COPY,不記得具體來源,支持作者)
- /**********************************************************************
- * <pre>
- * FILE : Demo.java
- * CLASS : Demo
- *
- * AUTHOR : caoxu-yiyang@qq.com
- *
- * FUNCTION : TODO
- *
- *
- *======================================================================
- * CHANGE HISTORY LOG
- *----------------------------------------------------------------------
- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ.
- *----------------------------------------------------------------------
- * |2016年11月9日|caoxu-yiyang@qq.com| Created |
- * DESCRIPTION:
- * </pre>
- ***********************************************************************/
- package com.cx.itext;
- import java.io.IOException;
- import com.itextpdf.awt.geom.Rectangle2D.Float;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.parser.ImageRenderInfo;
- import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
- import com.itextpdf.text.pdf.parser.RenderListener;
- import com.itextpdf.text.pdf.parser.TextRenderInfo;
- public class Demo
- {
- // 定義關鍵字
- private static String KEY_WORD = "結算區分";
- // 定義返回值
- private static float[] resu = null;
- // 定義返回頁碼
- private static int i = 0;
- public static void main(String[] args) {
- float[] point = getKeyWords("I://ticket_in.pdf");
- }
- /*
- * 返回關鍵字所在的坐標和頁數 float[0] >> X float[1] >> Y float[2] >> page
- */
- private static float[] getKeyWords(String filePath)
- {
- try
- {
- PdfReader pdfReader = new PdfReader(filePath);
- int pageNum = pdfReader.getNumberOfPages();
- PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(
- pdfReader);
- // 下標從1開始
- for (i = 1; i <= pageNum; i++)
- {
- pdfReaderContentParser.processContent(i, new RenderListener()
- {
- @Override
- public void renderText(TextRenderInfo textRenderInfo)
- {
- String text = textRenderInfo.getText();
- if (null != text && text.contains(KEY_WORD))
- {
- Float boundingRectange = textRenderInfo
- .getBaseline().getBoundingRectange();
- resu = new float[3];
- System.out.println("======="+text);
- System.out.println("h:"+boundingRectange.getHeight());
- System.out.println("w:"+boundingRectange.width);
- System.out.println("centerX:"+boundingRectange.getCenterX());
- System.out.println("centerY:"+boundingRectange.getCenterY());
- System.out.println("x:"+boundingRectange.getX());
- System.out.println("y:"+boundingRectange.getY());
- System.out.println("maxX:"+boundingRectange.getMaxX());
- System.out.println("maxY:"+boundingRectange.getMaxY());
- System.out.println("minX:"+boundingRectange.getMinX());
- System.out.println("minY:"+boundingRectange.getMinY());
- resu[0] = boundingRectange.x;
- resu[1] = boundingRectange.y;
- resu[2] = i;
- }
- }
- @Override
- public void renderImage(ImageRenderInfo arg0)
- {
- }
- @Override
- public void endTextBlock()
- {
- }
- @Override
- public void beginTextBlock()
- {
- }
- });
- }
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- return resu;
- }
- }
- public static void main(String[] args) throws IOException, DocumentException {
- PdfReplacer textReplacer = new PdfReplacer("I://test.pdf");
- textReplacer.replaceText("陳坤", "小白");
- textReplacer.replaceText("本科", "社會大學");
- textReplacer.replaceText("0755-29493863", "15112345678");
- textReplacer.toPdf("I://ticket_out.pdf");
- }
原始PDF:


替換之后的(紅色背景只是方便大家看到差別):

(第一次認真寫博客,感覺感覺好花時間了,佩服那些堅持寫博客的人~~)
補上相關代碼(還在完善中),總共4個類
代碼中有幾個地方要說明下:
1、由於自動計算得到的高度都是0,所有我這邊默認的都是12,大家要根據實際情況來設
2、除了可以讓代碼自己計算位置之外,也可以通過replaceText的重載方法強制指定替換區域。
- /**********************************************************************
- * <pre>
- * FILE : PdfTextReplacer.java
- * CLASS : PdfTextReplacer
- *
- * AUTHOR : caoxu-yiyang@qq.com
- *
- * FUNCTION : TODO
- *
- *
- *======================================================================
- * CHANGE HISTORY LOG
- *----------------------------------------------------------------------
- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ.
- *----------------------------------------------------------------------
- * |2016年11月8日|caoxu-yiyang@qq.com| Created |
- * DESCRIPTION:
- * </pre>
- ***********************************************************************/
- package com.cx.itext;
- import java.io.ByteArrayOutputStream;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- import com.itextpdf.text.BaseColor;
- import com.itextpdf.text.DocumentException;
- import com.itextpdf.text.Font;
- import com.itextpdf.text.log.Logger;
- import com.itextpdf.text.log.LoggerFactory;
- import com.itextpdf.text.pdf.BaseFont;
- import com.itextpdf.text.pdf.PdfContentByte;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.PdfStamper;
- /**
- * 替換PDF文件某個區域內的文本
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月8日
- */
- public class PdfReplacer {
- private static final Logger logger = LoggerFactory.getLogger(PdfReplacer.class);
- private int fontSize;
- private Map<String, ReplaceRegion> replaceRegionMap = new HashMap<String, ReplaceRegion>();
- private Map<String, Object> replaceTextMap =new HashMap<String, Object>();
- private ByteArrayOutputStream output;
- private PdfReader reader;
- private PdfStamper stamper;
- private PdfContentByte canvas;
- private Font font;
- public PdfReplacer(byte[] pdfBytes) throws DocumentException, IOException{
- init(pdfBytes);
- }
- public PdfReplacer(String fileName) throws IOException, DocumentException{
- FileInputStream in = null;
- try{
- in =new FileInputStream(fileName);
- byte[] pdfBytes = new byte[in.available()];
- in.read(pdfBytes);
- init(pdfBytes);
- }finally{
- in.close();
- }
- }
- private void init(byte[] pdfBytes) throws DocumentException, IOException{
- logger.info("初始化開始");
- reader = new PdfReader(pdfBytes);
- output = new ByteArrayOutputStream();
- stamper = new PdfStamper(reader, output);
- canvas = stamper.getOverContent(1);
- setFont(10);
- logger.info("初始化成功");
- }
- private void close() throws DocumentException, IOException{
- if(reader != null){
- reader.close();
- }
- if(output != null){
- output.close();
- }
- output=null;
- replaceRegionMap=null;
- replaceTextMap=null;
- }
- public void replaceText(float x, float y, float w,float h, String text){
- ReplaceRegion region = new ReplaceRegion(text); //用文本作為別名
- region.setH(h);
- region.setW(w);
- region.setX(x);
- region.setY(y);
- addReplaceRegion(region);
- this.replaceText(text, text);
- }
- public void replaceText(String name, String text){
- this.replaceTextMap.put(name, text);
- }
- /**
- * 替換文本
- * @throws IOException
- * @throws DocumentException
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- */
- private void process() throws DocumentException, IOException{
- try{
- parseReplaceText();
- canvas.saveState();
- Set<Entry<String, ReplaceRegion>> entrys = replaceRegionMap.entrySet();
- for (Entry<String, ReplaceRegion> entry : entrys) {
- ReplaceRegion value = entry.getValue();
- canvas.setColorFill(BaseColor.RED);
- canvas.rectangle(value.getX(),value.getY(),value.getW(),value.getH());
- }
- canvas.fill();
- canvas.restoreState();
- //開始寫入文本
- canvas.beginText();
- for (Entry<String, ReplaceRegion> entry : entrys) {
- ReplaceRegion value = entry.getValue();
- //設置字體
- canvas.setFontAndSize(font.getBaseFont(), getFontSize());
- canvas.setTextMatrix(value.getX(),value.getY()+2/*修正背景與文本的相對位置*/);
- canvas.showText((String) replaceTextMap.get(value.getAliasName()));
- }
- canvas.endText();
- }finally{
- if(stamper != null){
- stamper.close();
- }
- }
- }
- /**
- * 未指定具體的替換位置時,系統自動查找位置
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- */
- private void parseReplaceText() {
- PdfPositionParse parse = new PdfPositionParse(reader);
- Set<Entry<String, Object>> entrys = this.replaceTextMap.entrySet();
- for (Entry<String, Object> entry : entrys) {
- if(this.replaceRegionMap.get(entry.getKey()) == null){
- parse.addFindText(entry.getKey());
- }
- }
- try {
- Map<String, ReplaceRegion> parseResult = parse.parse();
- Set<Entry<String, ReplaceRegion>> parseEntrys = parseResult.entrySet();
- for (Entry<String, ReplaceRegion> entry : parseEntrys) {
- if(entry.getValue() != null){
- this.replaceRegionMap.put(entry.getKey(), entry.getValue());
- }
- }
- } catch (IOException e) {
- logger.error(e.getMessage(), e);
- }
- }
- /**
- * 生成新的PDF文件
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @param fileName
- * @throws DocumentException
- * @throws IOException
- */
- public void toPdf(String fileName) throws DocumentException, IOException{
- FileOutputStream fileOutputStream = null;
- try{
- process();
- fileOutputStream = new FileOutputStream(fileName);
- fileOutputStream.write(output.toByteArray());
- fileOutputStream.flush();
- }catch(IOException e){
- logger.error(e.getMessage(), e);
- throw e;
- }finally{
- if(fileOutputStream != null){
- fileOutputStream.close();
- }
- close();
- }
- logger.info("文件生成成功");
- }
- /**
- * 將生成的PDF文件轉換成二進制數組
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @return
- * @throws DocumentException
- * @throws IOException
- */
- public byte[] toBytes() throws DocumentException, IOException{
- try{
- process();
- logger.info("二進制數據生成成功");
- return output.toByteArray();
- }finally{
- close();
- }
- }
- /**
- * 添加替換區域
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @param replaceRegion
- */
- public void addReplaceRegion(ReplaceRegion replaceRegion){
- this.replaceRegionMap.put(replaceRegion.getAliasName(), replaceRegion);
- }
- /**
- * 通過別名得到替換區域
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @param aliasName
- * @return
- */
- public ReplaceRegion getReplaceRegion(String aliasName){
- return this.replaceRegionMap.get(aliasName);
- }
- public int getFontSize() {
- return fontSize;
- }
- /**
- * 設置字體大小
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @param fontSize
- * @throws DocumentException
- * @throws IOException
- */
- public void setFont(int fontSize) throws DocumentException, IOException{
- if(fontSize != this.fontSize){
- this.fontSize = fontSize;
- BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
- font = new Font(bf,this.fontSize,Font.BOLD);
- }
- }
- public void setFont(Font font){
- if(font == null){
- throw new NullPointerException("font is null");
- }
- this.font = font;
- }
- public static void main(String[] args) throws IOException, DocumentException {
- PdfReplacer textReplacer = new PdfReplacer("I://test.pdf");
- textReplacer.replaceText("陳坤", "小白");
- textReplacer.replaceText("本科", "社會大學");
- textReplacer.replaceText("0755-29493863", "15112345678");
- textReplacer.toPdf("I://ticket_out.pdf");
- }
- }
- /**********************************************************************
- * <pre>
- * FILE : ReplaceRegion.java
- * CLASS : ReplaceRegion
- *
- * AUTHOR : caoxu-yiyang@qq.com
- *
- * FUNCTION : TODO
- *
- *
- *======================================================================
- * CHANGE HISTORY LOG
- *----------------------------------------------------------------------
- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ.
- *----------------------------------------------------------------------
- * |2016年11月9日|caoxu-yiyang@qq.com| Created |
- * DESCRIPTION:
- * </pre>
- ***********************************************************************/
- package com.cx.itext;
- /**
- * 需要替換的區域
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- */
- public class ReplaceRegion {
- private String aliasName;
- private Float x;
- private Float y;
- private Float w;
- private Float h;
- public ReplaceRegion(String aliasName){
- this.aliasName = aliasName;
- }
- /**
- * 替換區域的別名
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @return
- */
- public String getAliasName() {
- return aliasName;
- }
- public void setAliasName(String aliasName) {
- this.aliasName = aliasName;
- }
- public Float getX() {
- return x;
- }
- public void setX(Float x) {
- this.x = x;
- }
- public Float getY() {
- return y;
- }
- public void setY(Float y) {
- this.y = y;
- }
- public Float getW() {
- return w;
- }
- public void setW(Float w) {
- this.w = w;
- }
- public Float getH() {
- return h;
- }
- public void setH(Float h) {
- this.h = h;
- }
- }
- /**********************************************************************
- * <pre>
- * FILE : PdfPositionParse.java
- * CLASS : PdfPositionParse
- *
- * AUTHOR : caoxu-yiyang@qq.com
- *
- * FUNCTION : TODO
- *
- *
- *======================================================================
- * CHANGE HISTORY LOG
- *----------------------------------------------------------------------
- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ.
- *----------------------------------------------------------------------
- * |2016年11月9日|caoxu-yiyang@qq.com| Created |
- * DESCRIPTION:
- * </pre>
- ***********************************************************************/
- package com.cx.itext;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import com.cx.itext.listener.PositionRenderListener;
- import com.itextpdf.text.pdf.PdfReader;
- import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
- /**
- * 解析PDF中文本的x,y位置
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- */
- public class PdfPositionParse {
- private PdfReader reader;
- private List<String> findText = new ArrayList<String>(); //需要查找的文本
- private PdfReaderContentParser parser;
- public PdfPositionParse(String fileName) throws IOException{
- FileInputStream in = null;
- try{
- in =new FileInputStream(fileName);
- byte[] bytes = new byte[in.available()];
- in.read(bytes);
- init(bytes);
- }finally{
- in.close();
- }
- }
- public PdfPositionParse(byte[] bytes) throws IOException{
- init(bytes);
- }
- private boolean needClose = true;
- /**
- * 傳遞進來的reader不會在PdfPositionParse結束時關閉
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @param reader
- */
- public PdfPositionParse(PdfReader reader){
- this.reader = reader;
- parser = new PdfReaderContentParser(reader);
- needClose = false;
- }
- public void addFindText(String text){
- this.findText.add(text);
- }
- private void init(byte[] bytes) throws IOException {
- reader = new PdfReader(bytes);
- parser = new PdfReaderContentParser(reader);
- }
- /**
- * 解析文本
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- * @throws IOException
- */
- public Map<String, ReplaceRegion> parse() throws IOException{
- try{
- if(this.findText.size() == 0){
- throw new NullPointerException("沒有需要查找的文本");
- }
- PositionRenderListener listener = new PositionRenderListener(this.findText);
- parser.processContent(1, listener);
- return listener.getResult();
- }finally{
- if(reader != null && needClose){
- reader.close();
- }
- }
- }
- }
- /**********************************************************************
- * <pre>
- * FILE : PositionRenderListener.java
- * CLASS : PositionRenderListener
- *
- * AUTHOR : caoxu-yiyang@qq.com
- *
- * FUNCTION : TODO
- *
- *
- *======================================================================
- * CHANGE HISTORY LOG
- *----------------------------------------------------------------------
- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ.
- *----------------------------------------------------------------------
- * |2016年11月9日|caoxu-yiyang@qq.com| Created |
- * DESCRIPTION:
- * </pre>
- ***********************************************************************/
- package com.cx.itext.listener;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import com.cx.itext.ReplaceRegion;
- import com.itextpdf.awt.geom.Rectangle2D.Float;
- import com.itextpdf.text.pdf.parser.ImageRenderInfo;
- import com.itextpdf.text.pdf.parser.RenderListener;
- import com.itextpdf.text.pdf.parser.TextRenderInfo;
- /**
- * pdf渲染監聽,當找到渲染的文本時,得到文本的坐標x,y,w,h
- * @user : caoxu-yiyang@qq.com
- * @date : 2016年11月9日
- */
- public class PositionRenderListener implements RenderListener{
- private List<String> findText;
- private float defaultH; ///出現無法取到值的情況,默認為12
- private float fixHeight; //可能出現無法完全覆蓋的情況,提供修正的參數,默認為2
- public PositionRenderListener(List<String> findText, float defaultH,float fixHeight) {
- this.findText = findText;
- this.defaultH = defaultH;
- this.fixHeight = fixHeight;
- }
- public PositionRenderListener(List<String> findText) {
- this.findText = findText;
- this.defaultH = 12;
- this.fixHeight = 2;
- }
- @Override
- public void beginTextBlock() {
- }
- @Override
- public void endTextBlock() {
- }
- @Override
- public void renderImage(ImageRenderInfo imageInfo) {
- }
- private Map<String, ReplaceRegion> result = new HashMap<String, ReplaceRegion>();
- @Override
- public void renderText(TextRenderInfo textInfo) {
- String text = textInfo.getText();
- for (String keyWord : findText) {
- if (null != text && text.equals(keyWord)){
- Float bound = textInfo.getBaseline().getBoundingRectange();
- ReplaceRegion region = new ReplaceRegion(keyWord);
- region.setH(bound.height == 0 ? defaultH : bound.height);
- region.setW(bound.width);
- region.setX(bound.x);
- region.setY(bound.y-this.fixHeight);
- result.put(keyWord, region);
- }
- }
- }
- public Map<String, ReplaceRegion> getResult() {
- for (String key : findText) { //補充沒有找到的數據
- if(this.result.get(key) == null){
- this.result.put(key, null);
- }
- }
- return this.result;
- }
- }
我用到的jar包如下:
大家可以從官網下載,可以構建maven項目省去自己找包的麻煩。如果沒有用maven又想下載具體的jar包,可以直接訪問maven倉庫下載:http://mvnrepository.com/