感谢感恩javapdf替换⽂字_java代码⽤itext识别PDF中的⽂字然后替换itext替换PDF的原理就是找到要替换的⽂字,然后计算他的位置,在哪个位置上⽣成覆盖层,然后在覆盖层上写内容。
从⽹上看到的⾃动计算PDF中⽂字的位置⽅法。
public class PdfConversion {
// 定义关键字
private static String KEY_WORD = "张三";
// 定义返回值
private static float[] resu = null;
// 定义返回页码
private static int i = 0;
/*
* 返回关键字所在的坐标和页数 float[0] >> X; float[1] >> Y; float[2] >> page;
*/
古诗宿建德江public static float[] getKeyWords(String filePath)
{
try
{
PdfReader pdfReader = new PdfReader(filePath);
int pageNum = NumberOfPages();
System.out.println(pageNum);
PdfReaderContentParr pdfReaderContentParr = new PdfReaderContentParr(
pdfReader);
// 下标从1开始
for (i = 1; i <= pageNum; i++)
{
pdfReaderContentParr.processContent(i, new RenderListener()
{
@Override
public void renderText(TextRenderInfo textRenderInfo)
{
String text = Text();
if (null != text && ains(KEY_WORD))
{
Float boundingRectange = textRenderInfo
.
getBaline().getBoundingRectange();
resu = new float[3];
System.out.println("======="+text);
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 class PdfConversion1 {
// @SuppressWarnings("deprecation")
数学手抄报>土豆怎么炸public static final String SRC = "C:/Urs/tym/Desktop/template.pdf"; public static final String DEST = "C:/Urs/tym/Desktop/test1.pdf";
public static void main(String[] args) throws IOException, DocumentException {高一政治必修一
File file = new File(DEST);
new PdfConversion1().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));
float[] result = KeyWords(src); //1
PdfContentByte canvas = OverContent((int) result[2]);
// float height=595;
/
/ System.out.HorizontalScaling());
float x,y;
x= result[0];//2
y = result[1];//3
canvas.saveState();
canvas.tColorFill(BaColor.WHITE);
canvas.fill();
//开始写⼊⽂本
canvas.beginText();
/
/BaFont bf = ateFont(URLDecoder.decode(Resource("/f").getFile()), BaFont.IDENTITY_H, BaFont.EMBEDDED);
BaFont bf = ateFont("STSong-Light", "UniGB-UCS2-H", BaFont.EMBEDDED);
Font font = new Font(bf,10,Font.BOLD);
//设置字体和⼤⼩
canvas.BaFont(), 15);
//设置字体的输出位置
canvas.tTextMatrix(x, y-1);
//要输出的text
canvas.showText("⽥⽥⽥" );一元四次方程
//设置字体的输出位置
canvas.BaFont(), 20);