c# Pdf到文本与图像占位符

本文关键字:图像 占位符 文本 Pdf | 更新日期: 2023-09-27 17:52:39

我有一批想要转换为文本的pdf文件。很容易从iTextSharp:

中获取这样的文本
PdfTextExtractor.GetTextFromPage(reader, pageNumber);

使用这个答案(或线程中类似的答案)很容易获得图像。

我不能轻易弄明白的是……是如何在文本中穿插图像占位符。

给定一个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到文本与图像占位符

c# Pdf转文本,带图像占位符
https://stackoverflow.com/a/28087521/
https://stackoverflow.com/a/33697745/

虽然这没有在我的问题中提到的确切布局(因为这是我真正想要的简化版本),它确实有由第二个说明列出的起始部分(从iText Java翻译)…从第三条注释中提取了额外的信息(Java中使用的一些反射似乎在c#中不起作用,因此信息来自#3)。

从这个工作,我能够得到一个字符串表示行在PDF(所有页面,而不仅仅是第1页)的列表…在应该放图片的地方加了文字(哈!)添加了ByteArrayToFile扩展方法(虽然我没有包括其他部分/扩展,可能会破坏复制/粘贴的用法)。

我还能够极大地简化我的过程的其他部分,并消除我之前工作的一半垃圾。万岁! !由于@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;
    }
}