0%

itextpdf-5.5.13相关使用

一、简介

iText是著名的开源的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

二、maven依赖导入

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!--支持中文水印-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>

三、获取关键字所在坐标位置

PDFHelperUtils.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
package com.mro.finance.util.itextpdf;

import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

public class PDFHelper {

/**
* @param filepath 文件路径
* @param keyWords 关键字
* @return float[]
* @Description 用于供外部类调用获取关键字所在PDF文件坐标
*/
public static MatchItem getKeyWordsByPath(String filepath, String keyWords) {
MatchItem matchItem = null;
try {
PdfReader pdfReader = new PdfReader(filepath);
matchItem = getKeyWords(pdfReader, keyWords);
} catch (IOException e) {
e.printStackTrace();
}
return matchItem;
}


public static MatchItem getKeyWordsByPath(InputStream inputStream, String keyWords) {
MatchItem matchItem = null;
try {
PdfReader pdfReader = new PdfReader(inputStream);
matchItem = getKeyWords(pdfReader, keyWords);
} catch (IOException e) {
e.printStackTrace();
}
return matchItem;
}

/**
* @param pdfReader pdfReader
* @param keyWords 关键字
* @return 坐标包装对象
* @Description 获取关键字所在PDF坐标
*/
private static MatchItem getKeyWords(PdfReader pdfReader, String keyWords) {
int page = 0;
try {
int pageNum = pdfReader.getNumberOfPages();
PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
CustomRenderListener renderListener = new CustomRenderListener();
renderListener.setKeyWord(keyWords);
StringBuilder allText = null;
for (page = 1; page <= pageNum; page++) {
renderListener.setPage(page);
pdfReaderContentParser.processContent(page, renderListener);

List<MatchItem> matchItems = renderListener.getMatchItems();
if (matchItems != null && matchItems.size() > 0) {
// 完全匹配返回首个匹配项
return matchItems.get(0);
}
List<MatchItem> allItems = renderListener.getAllItems();
allText = new StringBuilder();
for (MatchItem item : allItems) {
allText.append(item.getContent());
// 关键字存在连续多个块中
if (allText.indexOf(keyWords) != -1) {
return item;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


// 添加图片
public static void andImage(String filePath, String imgPath, int pageNum, float x, float y) {
String fileName = filePath.substring(0, filePath.lastIndexOf("."));
String outputPath = fileName + (int) ((Math.random() * 9 + 1) * 100000L) + ".pdf";
try {
PdfReader reader = new PdfReader(filePath);
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outputPath));
final float width = 128, height = 128;

Image img = Image.getInstance(imgPath);
img.scaleAbsolute(width, height); // 图片大小
img.setAbsolutePosition(x, y - height / 2); // 设置图片的绝对位置,根据左顶角为原坐标
img.setAlignment(Image.TEXTWRAP);
PdfContentByte under = stamp.getUnderContent(pageNum);
under.addImage(img);
stamp.close();
reader.close();
/*
* Image类方法:
* scaleAbsolute(float newWidth, float newHeight); // 将图像缩放到绝对宽度和绝对高度。
* scaleAbsoluteHeight(float newHeight); // 将图像缩放到绝对高度。
* scaleAbsoluteWidth(float newWidth); //将图像缩放到绝对宽度。
* scalePercent(float percent); // 将图像缩放到一定百分比。
* scalePercent(float percentX, float percentY); //将图像的宽度和高度缩放到一定百分比。
* scaleToFit(float fitWidth, float fitHeight); //缩放图像,使其适合特定的宽度和高度。
*/

} catch (Exception e) {
e.printStackTrace();
}

}

// 添加水印
public static void andWatermark(String filePath, String markStr, int pageNum, float x, float y) {
String fileName = filePath.substring(0, filePath.lastIndexOf("."));
String outputPath = fileName + "(水印).pdf";
try {
PdfReader reader = new PdfReader(filePath);
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outputPath));

// 文字水印
PdfContentByte over = stamp.getOverContent(pageNum);
// 设置透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.1f);
over.beginText();
//under.setColorFill(BaseColor.PINK); // 文字颜色
// BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
over.setGState(gs);
over.setFontAndSize(bf, 18); // 水印字体大小
over.setTextMatrix(1, 1);
over.showTextAligned(Element.ALIGN_CENTER, String.join("", Collections.nCopies(10, markStr + " ")), x, y, 45);
over.endText(); //添加水印文字
stamp.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}

}


public static void main(String[] args) throws Exception {
String filePath = "D:\\合同模板.pdf";
String imgPath = "D:\\印章.png";
String keyWord = "代表人:";
String markStr = "WDNMD";

MatchItem matchItem = getKeyWordsByPath(filePath, keyWord);
System.out.println("x:" + matchItem.getX() + "y:" + matchItem.getY() + "页数:" + matchItem.getPageNum());
// andImage(filePath, imgPath, matchItem.getPageNum(), matchItem.getX(), matchItem.getY());
andWatermark(filePath, markStr, matchItem.getPageNum(), matchItem.getX(), matchItem.getY());
}
}

返回体包装MatchItem.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.mro.finance.util.itextpdf;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MatchItem {

private String content;
private int pageNum;
private float x;
private float y;

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public int getPageNum() {
return pageNum;
}

public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}

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;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.mro.finance.util.itextpdf;

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;

import java.util.ArrayList;
import java.util.List;

public class CustomRenderListener implements RenderListener {

/**
* 定位坐标的关键字
*/
private String keyWord;
/**
* 关键字所在的页数
*/
private int page;
// 所有匹配的项
private List<MatchItem> matchItems = new ArrayList<>();
// 所有项
private List<MatchItem> allItems = new ArrayList<>();

public String getKeyWord() {
return keyWord;
}

public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}

public int getPage() {
return page;
}

public void setPage(int page) {
this.page = page;
}

public List<MatchItem> getMatchItems() {
return matchItems;
}

public void setMatchItems(List<MatchItem> matchItems) {
this.matchItems = matchItems;
}

public List<MatchItem> getAllItems() {
return allItems;
}

public void setAllItems(List<MatchItem> allItems) {
this.allItems = allItems;
}

@Override
public void beginTextBlock() {

}

@Override
public void renderText(TextRenderInfo textRenderInfo) {
String text = textRenderInfo.getText();
Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();
MatchItem matchItem = new MatchItem();
matchItem.setContent(text);
matchItem.setPageNum(page);
matchItem.setX(boundingRectange.x);
matchItem.setY(boundingRectange.y);
if (null != text && !" ".equals(text)) {
if (text.equalsIgnoreCase(keyWord)) {
matchItems.add(matchItem); // 匹配的项
}
}
allItems.add(matchItem);
}

@Override
public void endTextBlock() {

}

@Override
public void renderImage(ImageRenderInfo imageRenderInfo) {

}
}