【问题标题】:C# Pdf to Text with image placeholderC# Pdf 到带有图像占位符的文本
【发布时间】:2016-06-28 01:21:14
【问题描述】:

我有一批要转换为文本的 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。

【问题讨论】:

  • 您是否正在寻找类似this answer 中提出的 iText/Java 解决方案?它应该很容易翻译成 iTextSharp/C#。
  • @mkl 更新了解释以更接近该问题。昨天晚上想扩大一点。这个问题基本上是一样的,除了我正在使用 iTextSharp 在 C# 中工作(尽管如果需要,我并不反对转移到其他库,如 PdfSharp)。
  • 因此,可以通过将 iText/Java 解决方案从那个旧问题移植到 iTextSharp/C# 来创建您想要的内容。这应该不会太难......
  • @mkl 是的,如果有人不打败我,我会尝试...以前从未移植过 Java,但看起来并不太难,因为这两种语言很接近(但不同)
  • @mkl 我搞定了 :) 感谢这个问题和另一个问题。

标签: c# parsing pdf itext pdfsharp


【解决方案1】:

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 扩展方法(尽管我没有包含可能破坏此代码的复制/粘贴用法的其他部分/扩展)。

我还能够大大简化我的流程的其他部分,并消除我之前工作的一半垃圾。嘘!!!谢谢@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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2021-01-30
    相关资源
    最近更新 更多