Я пытаюсь найти текст в pdf-файле и возвращать координаты, если текст существует. Я изучал сеть и выяснил, что это можно сделать с помощью библиотеки itextsharp.Искать текст в pdf-файле и возвращать координаты, если существует текст
Я нашел этот код, и я пытаюсь его модифицировать в соответствии с моими требованиями. Как передать файл в этот класс.
class Program
{
static void Main(string[] args)
{
var testFile = @"test.pdf";
//Create an instance of our strategy
var t = new MyLocationTextExtractionStrategy("test");
//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));
}
Console.Read();
}
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>();
//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));
}
}
Проблема, скорее всего, связана с тем, как структурирован ваш входной документ. Поэтому, если вы можете поделиться файлом, я могу указать на проблему и помочь вам найти решение. – blagae
Очень краткое объяснение: в файле PDF можно записать любое слово с одной инструкцией рендеринга на каждую букву, включая все возможные перестановки, такие как «te», «s» и «t», не обязательно в этом порядке. В то время, когда вызывается «RenderText», эти отдельные текстовые шрифты еще не объединены в одно слово. Поэтому в любое время слово «тест» не записывается вместе в одной команде рендеринга, ваш код будет терпеть неудачу. – blagae