itextpdf查找关键字坐标,以及在特定位置添加文字

使用itextpdf达到在PDF指定位置进行批注的效果

之前有遇到一个需求,这PDF的指定位置上添加一个文字或者图片(思路一致),当时在网上找了一波,总结一下。

  1. 在PDF指定位置添加文字有两种情况,一是已知指定位置的坐标(可在前台使用PDF.js计算得多,本文暂时不多介绍),二是使用工具类在PDF上查找关键字来得知坐标,本次使用的itextpdf工具类能够达到这一效果。
  2. 第一步就不用多说了,先通过pom文件引入jar包
<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.5.12</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-pdfa</artifactId>
			<version>5.5.12</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-xtra</artifactId>
			<version>5.5.12</version>
			<exclusions>
				<exclusion>
					<groupId
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
这个问题需要用到 iTextSharp 库来解决。首先,你需要安装该库并导入它。然后,你可以使用以下代码获取指定关键字坐标位置信息: ```c# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace PdfKeywordCoordinates { class Program { static void Main(string[] args) { string filename = @"C:\example.pdf"; // pdf 文件路径 string keyword = "example keyword"; // 指定关键字 using (PdfReader reader = new PdfReader(filename)) { for (int page = 1; page <= reader.NumberOfPages; page++) { ITextExtractionStrategy strategy = new LocationTextExtractionStrategy(); string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy); if (currentText.Contains(keyword)) { var kwLocation = new List<RectAndText>(); var renderFilter = new RenderFilter[1]; renderFilter[0] = new RegionTextRenderFilter(new Rectangle(0, 0, 1000, 1000)); var textExtractionStrategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(textExtractionStrategy); processor.ProcessContent(reader.GetPageContent(page)); kwLocation = ((LocationTextExtractionStrategy)textExtractionStrategy).GetLocations(); foreach (RectAndText rectAndText in kwLocation) { if (rectAndText.text.Contains(keyword)) { Console.WriteLine("Page: " + page + " X: " + rectAndText.rect.Left + " Y: " + rectAndText.rect.Bottom); } } } } } Console.ReadLine(); } } public class RectAndText { public iTextSharp.text.Rectangle rect; public String text; public RectAndText(iTextSharp.text.Rectangle rect, String text) { this.rect = rect; this.text = text; } } } ``` 这个代码将在指定PDF 文件中查找指定关键字,并输出该关键字在每一页中的坐标位置信息。注意,这个代码是使用 C# 编写的,如果你使用的是 Python,你需要使用 Python 版本的 iTextSharp 库,并使用相应的语法来实现相同的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值