使用iTextSharp从PDF中获取文本段落

6

是否有逻辑可以使用itextsharp从pdf文件中获取段落文本?我知道pdf只支持文本流,很难确定哪些文本流与哪个段落相关,而且我知道pdf中没有任何

<p>

标签或其他标签来确定段落。但是我尝试通过获取文本流的坐标来构建段落,但是没有成功 :(。我的代码片段在这里:

private StringBuilder result = new StringBuilder();
    private Vector lastBaseLine;
    //to store run of texts 
    public List<string> strings = new List<String>();
    //to store run of texts Coordinate (Y coordinate)
    public List<float> baselines = new List<float>();

    public void RenderText(iTextSharp.text.pdf.parser.TextRenderInfo renderInfo)
    {
        Vector curBaseline = renderInfo.GetBaseline().GetStartPoint();
        if ((this.lastBaseLine != null) && (curBaseline[Vector.I2] != lastBaseLine[Vector.I2]))
        {
            if ((!string.IsNullOrEmpty(this.result.ToString())))
            {
                this.baselines.Add(this.lastBaseLine[Vector.I2]);
                this.strings.Add(this.result.ToString());
            }
            result = new StringBuilder();
        }
        this.result.Append(renderInfo.GetText());
        this.lastBaseLine = curBaseline;
    }

有人针对这个问题有任何逻辑可以提供吗?

3
您的PDF文件是否为标记式PDF?如果不是,将很难确定哪些文本片段属于哪个段落(但您已经发现了这一点)。 - Bruno Lowagie
@BrunoLowagie 谢谢您的回复,PDF没有标记。有没有办法从未标记的PDF中提取段落? - Bibek Gautam
2
没有100%的证明解决方案,只有具有更小或更大失败率的启发式方法。 - mkl
@mkl +1,他说得对。 - Bruno Lowagie
1个回答

1
using (MemoryStream ms = new MemoryStream())
{
   Document document = new Document(PageSize.A4, 25, 25, 30, 30);
   PdfWriter writer = PdfWriter.GetInstance(document, ms);
   document.Open();
   document.Add(new Paragraph("Hello World"));
   document.Close();
   writer.Close();
   Response.ContentType = "pdf/application";
   Response.AddHeader("content-disposition", 
   "attachment;filename=First PDF document.pdf");
   Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}

这里有一些样例可以帮助你...

这可能不是你想要的精确答案,但它可能会对你有所帮助。


谢谢您的回答,但我的问题是如何从 PDF 中作为段落阅读文本,而不是如何编写 PDF。 - Bibek Gautam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接