我有一批要转换为文本的 PDF。从 iTextSharp 中获取类似这样的文本很容易:
PdfTextExtractor.GetTextFromPage(reader, pageNumber);
使用this answer 很容易获取图像(或线程中的类似答案)。
我无法轻易弄清楚...是如何在文本中插入图像占位符。
给定一个 PDF、一个页面 # 和 GetTextFromPage
我希望输出为:
line 1
line 2
line 3
当我希望它成为(其中 1.1 表示第 1 页、图像 1...第 1 页、图像 2):
line 1
[1.1]
line 2
[1.2]
line 3
有没有办法为 iTextSharp、PdfSharp 或类似的东西获取“图像占位符”?我想要一个 GetTextAndPlaceHoldersFromPage
方法(或类似方法)。
PS:嗯...它不允许我标记 iTextSHARP - 不是 iText。 C# 而非 Java。
最佳答案
C# Pdf to Text with image placeholder
https://stackoverflow.com/a/28087521/
https://stackoverflow.com/a/33697745/
虽然这没有我的问题中提到的确切布局(因为无论如何这是我真正想要的简化版本),但它确实具有第二个注释中列出的起始部分(从 iText Java 翻译而来)。 .. 从第三条注释中提取额外信息(Java 中使用的一些反射似乎在 C# 中不起作用,因此信息来自 #3)。
从这里开始,我能够得到一个字符串列表,表示 PDF 中的行(所有页面,而不仅仅是第 1 页)...在图像应该出现的地方添加文本(Huzzah!)。添加了 ByteArrayToFile 扩展方法以增加 flavor (尽管我没有包括可能破坏此代码的复制/粘贴用法的其他部分/扩展)。
我还能够极大地简化我流程的其他部分,并将我之前工作的一半垃圾处理掉。万岁!谢谢@Mkl
internal class Program
{
public static void Main(string[] args)
{
var dir = Settings.TestDirectory;
var file = Settings.TestFile;
Log.Info($"File to Process: {file.FullName}");
using (var reader = new PdfReader(file.FullName))
{
var parser = new PdfReaderContentParser(reader);
var listener = new SimpleMixedExtractionStrategy(file, dir);
parser.ProcessContent(1, listener);
var x = listener.GetResultantText().Split('\n');
}
}
}
public class SimpleMixedExtractionStrategy : LocationTextExtractionStrategy
{
public static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public DirectoryInfo OutputPath { get; }
public FileInfo OutputFile { get; }
private static readonly LineSegment UNIT_LINE = new LineSegment(new Vector(0, 0, 1), new Vector(1, 0, 1));
private int _counter;
public SimpleMixedExtractionStrategy(FileInfo outputFile, DirectoryInfo outputPath)
{
OutputPath = outputPath;
OutputFile = outputFile;
}
public override void RenderImage(ImageRenderInfo renderInfo)
{
try
{
var image = renderInfo.GetImage();
if (image == null) return;
var number = _counter++;
var imageFile = new FileInfo($"{OutputFile.FullName}-{number}.{image.GetFileType()}");
imageFile.ByteArrayToFile(image.GetImageAsBytes());
var segment = UNIT_LINE.TransformBy(renderInfo.GetImageCTM());
var location = new TextChunk("[" + imageFile + "]", segment.GetStartPoint(), segment.GetEndPoint(), 0f);
var locationalResultField = typeof(LocationTextExtractionStrategy).GetField("locationalResult", BindingFlags.NonPublic | BindingFlags.Instance);
var LocationalResults = (List<TextChunk>)locationalResultField.GetValue(this);
LocationalResults.Add(location);
}
catch (Exception ex)
{
Log.Debug($"{ex.Message}");
Log.Verbose($"{ex.StackTrace}");
}
}
}
public static class ByteArrayExtensions
{
public static bool ByteArrayToFile(this FileInfo fileName, byte[] byteArray)
{
try
{
// Open file for reading
var fileStream = new FileStream(fileName.FullName, FileMode.Create, FileAccess.Write);
// Writes a block of bytes to this stream using data from a byte array.
fileStream.Write(byteArray, 0, byteArray.Length);
// close file stream
fileStream.Close();
return true;
}
catch (Exception exception)
{
// Error
Log.Error($"Exception caught in process: {exception.Message}", exception);
}
// error occured, return false
return false;
}
}
关于C# Pdf 到带有图像占位符的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065626/