这是一个非常非常简单的实现版本。
在实施之前,非常了解 PDF 的“单词”、“段落”、“句子”等零概念非常重要。此外, PDF 不一定从左到右和从上到下排列,这与非 LTR 语言无关。短语“Hello World”可以这样写到 PDF 中:
Draw H at (10, 10)
Draw ell at (20, 10)
Draw rld at (90, 10)
Draw o Wo at (50, 20)
也可以写成
Draw Hello World at (10,10)
您需要实现的ITextExtractionStrategy 接口有一个名为RenderText 的方法,它会为PDF 中的每个文本块调用一次。注意我说的是“chunk”而不是“word”。在上面的第一个示例中,对于这两个词,该方法将被调用四次。在第二个例子中,这两个词会被调用一次。这是理解的非常重要的部分。 PDF 没有文字,因此 iTextSharp 也没有文字。 “单词”部分100%由你来解决。
同样,正如我上面所说,PDF 没有段落。要注意这一点的原因是因为 PDF 不能将文本换行到新行。每当您看到类似于段落的内容时,您实际上会看到一个全新的文本绘图命令,该命令具有与前一行不同的y 坐标。见this for further discussion。
下面的代码是一个非常简单的实现。为此,我将LocationTextExtractionStrategy 子类化,它已经实现了ITextExtractionStrategy。在每次调用RenderText() 时,我都会找到当前块的矩形(使用Mark's code here)并将其存储起来以备后用。我正在使用这个简单的帮助类来存储这些块和矩形:
//Helper class that stores our rectangle and text
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;
}
}
这是子类:
public class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy {
//Hold each coordinate
public List<RectAndText> myPoints = new List<RectAndText>();
//Automatically called for each chunk of text in the PDF
public override void RenderText(TextRenderInfo renderInfo) {
base.RenderText(renderInfo);
//Get the bounding box for the chunk of text
var bottomLeft = renderInfo.GetDescentLine().GetStartPoint();
var topRight = renderInfo.GetAscentLine().GetEndPoint();
//Create a rectangle from it
var rect = new iTextSharp.text.Rectangle(
bottomLeft[Vector.I1],
bottomLeft[Vector.I2],
topRight[Vector.I1],
topRight[Vector.I2]
);
//Add this to our main collection
this.myPoints.Add(new RectAndText(rect, renderInfo.GetText()));
}
}
最后是上面的实现:
//Our test file
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Create our test file, nothing special
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
doc.Add(new Paragraph("This is my sample file"));
doc.Close();
}
}
}
//Create an instance of our strategy
var t = new MyLocationTextExtractionStrategy();
//Parse page 1 of the document above
using (var r = new PdfReader(testFile)) {
var ex = PdfTextExtractor.GetTextFromPage(r, 1, t);
}
//Loop through each chunk found
foreach (var p in t.myPoints) {
Console.WriteLine(string.Format("Found text {0} at {1}x{2}", p.Text, p.Rect.Left, p.Rect.Bottom));
}
我不能强调以上内容没有考虑“单词”,这取决于你。传递给RenderText 的TextRenderInfo 对象有一个名为GetCharacterRenderInfos() 的方法,您可以使用它来获取更多信息。如果您不关心字体中的下降,您可能还想使用GetBaseline() instead ofGetDescentLine()`。
编辑
(我吃了一顿丰盛的午餐,所以我感觉更有帮助。)
这是MyLocationTextExtractionStrategy 的更新版本,它执行下面我的 cmets 所说的操作,即需要一个字符串来搜索并在每个块中搜索该字符串。由于列出的所有原因,这在某些/许多/大多数/所有情况下都不起作用。如果子字符串在一个块中多次存在,它也只会返回第一个实例。连字和变音符号也可能与此混淆。
public class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy {
//Hold each coordinate
public List<RectAndText> myPoints = new List<RectAndText>();
//The string that we're searching for
public String TextToSearchFor { get; set; }
//How to compare strings
public System.Globalization.CompareOptions CompareOptions { get; set; }
public MyLocationTextExtractionStrategy(String textToSearchFor, System.Globalization.CompareOptions compareOptions = System.Globalization.CompareOptions.None) {
this.TextToSearchFor = textToSearchFor;
this.CompareOptions = compareOptions;
}
//Automatically called for each chunk of text in the PDF
public override void RenderText(TextRenderInfo renderInfo) {
base.RenderText(renderInfo);
//See if the current chunk contains the text
var startPosition = System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(renderInfo.GetText(), this.TextToSearchFor, this.CompareOptions);
//If not found bail
if (startPosition < 0) {
return;
}
//Grab the individual characters
var chars = renderInfo.GetCharacterRenderInfos().Skip(startPosition).Take(this.TextToSearchFor.Length).ToList();
//Grab the first and last character
var firstChar = chars.First();
var lastChar = chars.Last();
//Get the bounding box for the chunk of text
var bottomLeft = firstChar.GetDescentLine().GetStartPoint();
var topRight = lastChar.GetAscentLine().GetEndPoint();
//Create a rectangle from it
var rect = new iTextSharp.text.Rectangle(
bottomLeft[Vector.I1],
bottomLeft[Vector.I2],
topRight[Vector.I1],
topRight[Vector.I2]
);
//Add this to our main collection
this.myPoints.Add(new RectAndText(rect, this.TextToSearchFor));
}
您可以像以前一样使用它,但现在构造函数有一个必需的参数:
var t = new MyLocationTextExtractionStrategy("sample");