Как уже упоминалось в комментарии, это очень похоже на тему вопроса Извлечение изображений, присутствующих в абзаце , с основным отличием в том, что в контексте этого вопроса вместо этого использовался iText для JavaiTextSharp для .Net.
Порт Java SimpleMixedExtractionStrategy
из этого вопроса может выглядеть так:
public class SimpleMixedExtractionStrategy : LocationTextExtractionStrategy
{
FieldInfo field = typeof(LocationTextExtractionStrategy).GetField("locationalResult", BindingFlags.Instance | BindingFlags.NonPublic);
LineSegment UNIT_LINE = new LineSegment(new Vector(0, 0, 1), new Vector(1, 0, 1));
String outputPath;
String name;
int counter = 0;
public SimpleMixedExtractionStrategy(String outputPath, String name)
{
this.outputPath = outputPath;
this.name = name;
}
public override void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject image = renderInfo.GetImage();
if (image == null) return;
int number = counter++;
String filename = name + "-" + number + "." + image.GetFileType();
File.WriteAllBytes(outputPath + filename, image.GetImageAsBytes());
LineSegment segment = UNIT_LINE.TransformBy(renderInfo.GetImageCTM());
TextChunk location = new TextChunk("[" + filename + "]", segment.GetStartPoint(), segment.GetEndPoint(), 0f);
List<TextChunk> locationalResult = (List<TextChunk>)field.GetValue(this);
locationalResult.Add(location);
}
}
Так же, как в реализации Java, это необходимоиспользовать отражение для доступа к private List<TextChunk> locationalResult
in LocationTextExtractionStrategy
.Если использование отражения не разрешено в вашем проекте, вы можете скопировать весь источник LocationTextExtractionStrategy
в собственный класс и применить изменения к копии.
Вы можете использовать его следующим образом:
String sourceFile = @"SOURCE.pdf";
String imagePath = @"extract\";
String imageBaseName = "SOURCE-";
Directory.CreateDirectory(imagePath);
using (PdfReader pdfReader = new PdfReader(sourceFile))
{
PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader);
for (var i = 1; i <= pdfReader.NumberOfPages; i++)
{
SimpleMixedExtractionStrategy listener = new SimpleMixedExtractionStrategy(imagePath, imageBaseName + i);
parser.ProcessContent(i, listener);
String text = listener.GetResultantText();
Console.Write("Text of page {0}:\n---\n{1}\n\n", i, text);
}
}
Для файла примера из упомянутого вопроса
вывод:
Text of page 1:
---
Getting Started with Vaadin
• A version of Book of Vaadin that you can browse in the Eclipse Help system.
You can install the plugin as follows:
1. Start Eclipse.
2. Select Help Software Updates....
3. Select the Available Software tab.
4. Add the Vaadin plugin update site by clicking Add Site....
[book-of-vaadin-page14-1-0.png]
Enter the URL of the Vaadin Update Site: http://vaadin.com/eclipse and click OK. The
Vaadin site should now appear in the Software Updates window.
5. Select all the Vaadin plugins in the tree.
[book-of-vaadin-page14-1-1.png]
Finally, click Install.
Detailed and up-to-date installation instructions for the Eclipse plugin can be found at http://vaad-
in.com/eclipse.
Updating the Vaadin Plugin
If you have automatic updates enabled in Eclipse (see Window Preferences Install/Update
Automatic Updates), the Vaadin plugin will be updated automatically along with other plugins.
Otherwise, you can update the Vaadin plugin (there are actually multiple plugins) manually as
follows:
1. Select Help Software Updates..., the Software Updates and Add-ons window will
open.
2. Select the Installed Software tab.
14 Vaadin Plugin for Eclipse
Таким образом, дляВаша задача
Мне хотелось бы найти строку текста в файле и затем извлечь изображение, следующее за этой строкой текста.
просто найдите эту строку текста в выходной строке выше и найдите следующую строку, содержащую имя файла изображения в квадратных скобках.
(Если ваш PDF-файл также использует квадратные скобки, вы можетезаключите имя файла в другие разделители в SimpleMixedExtractionStrategy
, например, некоторые символы из области частного использования Unicode.)