使用Spire PDF实现PDF文本替换后,如何记录修改文本的行与列位置
在Spire.PDF中替换文本并记录页、行、列位置
要实现替换PDF文本同时记录页、行、列位置,Spire.PDF的PdfTextFind没有直接提供行号和列号属性,但可以通过提取页面文本行布局,结合坐标匹配+文本索引的方式来获取。以下是修改后的完整代码,包含位置记录逻辑:
import com.spire.pdf.*; import com.spire.pdf.graphics.*; import com.spire.pdf.text.PdfTextExtractor; import com.spire.pdf.text.PdfTextLine; import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.List; public class PdfTextReplaceWithPosition { public static void main(String[] args) { //加载示例PDF文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("D:\\Spire\\Input\\test05.pdf"); //遍历文档 for (int i = 0; i < pdf.getPages().getCount(); i++) { //获取当前页面 PdfPageBase page = pdf.getPages().get(i); int pageNum = i + 1; // 页码从1开始计数 //查找指定文本 PdfTextFindCollection textFindCollection = page.findText("内容提要"); //创建画刷、字体 PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.red)); PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 12), true); //提取当前页面的所有文本行,用于判断行号和列号 PdfTextExtractor extractor = new PdfTextExtractor(page); List<PdfTextLine> textLines = extractor.getLines(); //遍历找到的文本并替换 for (PdfTextFind find : textFindCollection.getFinds()) { Rectangle2D rec = find.getBounds(); String originalText = find.getText(); // 1. 确定所在行号 int lineNum = -1; PdfTextLine targetLine = null; for (int j = 0; j < textLines.size(); j++) { PdfTextLine line = textLines.get(j); Rectangle2D lineBounds = line.getBounds(); // 通过Y坐标匹配行(加入微小误差兼容排版偏移) if (rec.getY() >= lineBounds.getY() - 2 && rec.getY() <= lineBounds.getY() + lineBounds.getHeight() + 2) { lineNum = j + 1; // 行号从1开始 targetLine = line; break; } } // 2. 确定所在列号 int colNum = -1; if (targetLine != null) { String lineContent = targetLine.getText(); // 查找文本在该行的起始索引,列号从1开始 int startIndex = lineContent.indexOf(originalText); if (startIndex != -1) { colNum = startIndex + 1; } } // 3. 输出记录信息 System.out.printf("修改记录:页码=%d,行号=%d,列号=%d,原文本=%s,替换为=Coffee%n", pageNum, lineNum, colNum, originalText); // 执行文本替换操作 page.getCanvas().drawRectangle(PdfBrushes.getWhite(), rec); page.getCanvas().drawString("Coffee", font, brush, rec); } } //保存文档 pdf.saveToFile("D:\\Spire\\OutPut\\Replace.pdf"); pdf.close(); } }
关键逻辑说明
- 行号获取:通过
PdfTextExtractor提取页面所有文本行,对比目标文本的Y坐标与每行文本的Y边界范围,匹配所属行(加入±2的误差值,避免因PDF排版的微小偏移导致匹配失败)。 - 列号获取:找到目标文本所在行后,通过字符串索引定位原文本在该行的起始位置,将索引+1作为列号(符合日常从1开始计数的习惯)。
- 位置记录:在替换操作前,将页码、行号、列号及替换前后的文本信息输出,可根据需求改为写入日志文件或数据库。
内容的提问来源于stack exchange,提问作者曹盟杰
相关产品推荐
相关产品推荐

