Programing

VB.NET 또는 C #에서 itextsharp dll로 PDF 콘텐츠 읽기

lottogame 2020. 10. 18. 08:21
반응형

VB.NET 또는 C #에서 itextsharp dll로 PDF 콘텐츠 읽기


Pdfreader 클래스를 사용하여 itextsharp로 PDF 콘텐츠를 어떻게 읽을 수 있습니까? 내 PDF에는 일반 텍스트 또는 텍스트 이미지가 포함될 수 있습니다.


using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;

public string ReadPdfFile(string fileName)
{
    StringBuilder text = new StringBuilder();

    if (File.Exists(fileName))
    {
        PdfReader pdfReader = new PdfReader(fileName);

        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }
        pdfReader.Close();
    }
    return text.ToString();
}

iTextSharp를 사용하여 원하는대로 PDF의 내용을 읽고 구문 분석 할 수 없습니다.

iTextSharp의 SourceForge 튜토리얼에서 :

iText를 사용하여 기존 PDF 파일을 '분석'할 수 없으며 페이지 당 페이지 만 '읽을'수 있습니다.

이것은 무엇을 의미 하는가?

pdf 형식은 구조 정보없이 텍스트와 그래픽이 배치 된 캔버스 일뿐입니다. 따라서 PDF 파일에는 'iText-objects'가 없습니다. 각 페이지에는 많은 '문자열'이있을 수 있지만 이러한 문자열을 사용하여 구문이나 단락을 재구성 할 수는 없습니다. 여러 선이 그려져있을 수 있지만 이러한 선을 기반으로 테이블 개체를 검색 할 수 없습니다. 요컨대, PDF 파일의 내용을 파싱하는 것은 iText로 불가능합니다. 뉴스 그룹 news : //comp.text.pdf에 질문을 게시하면 PDF를 구문 분석하고 일부 내용을 추출 할 수있는 도구를 구축 한 사람들로부터 답변을 얻을 수 있지만 총알을 수행 할 도구를 기대하지는 않습니다. -구조화 된 텍스트로의 변환을 방지합니다.


LGPL / FOSS iTextSharp 4.x

var pdfReader = new PdfReader(path); //other filestream etc
byte[] pageContent = _pdfReader .GetPageContent(pageNum); //not zero based
byte[] utf8 = Encoding.Convert(Encoding.Default, Encoding.UTF8, pageContent);
string textFromPage = Encoding.UTF8.GetString(utf8);

다른 답변은 나에게 유용하지 않았으며 모두 iTextSharp의 AGPL v5를 대상으로 한 것 같습니다. 나는에 대한 참조 찾을 수 없을 수 SimpleTextExtractionStrategy또는 LocationTextExtractionStrategyFOSS의 버전을.

이와 관련하여 매우 유용 할 수있는 다른 것 :

const string PdfTableFormat = @"\(.*\)Tj";
Regex PdfTableRegex = new Regex(PdfTableFormat, RegexOptions.Compiled);

List<string> ExtractPdfContent(string rawPdfContent)
{
    var matches = PdfTableRegex.Matches(rawPdfContent);

    var list = matches.Cast<Match>()
        .Select(m => m.Value
            .Substring(1) //remove leading (
            .Remove(m.Value.Length - 4) //remove trailing )Tj
            .Replace(@"\)", ")") //unencode parens
            .Replace(@"\(", "(")
            .Trim()
        )
        .ToList();
    return list;
}

이렇게하면 PDF에서 텍스트 전용 데이터가 추출됩니다. 표시된 텍스트가 Foo(bar)PDF에서로 인코딩되는 (Foo\(bar\))Tj경우이 메서드는 Foo(bar)예상대로 반환 됩니다. 이 방법은 원시 pdf 콘텐츠에서 위치 좌표와 같은 많은 추가 정보를 제거합니다.


다음은 ShravankumarKumar의 솔루션을 기반으로하는 VB.NET 솔루션입니다.

이것은 당신에게 텍스트만을 줄 것입니다. 이미지는 다른 이야기입니다.

Public Shared Function GetTextFromPDF(PdfFileName As String) As String
    Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)

    Dim sOut = ""

    For i = 1 To oReader.NumberOfPages
        Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy

        sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
    Next

    Return sOut
End Function

In my case I just wanted the text from a specific area of the PDF document so I used a rectangle around the area and extracted the text from it. In the sample below the coordinates are for the entire page. I don't have PDF authoring tools so when it came time to narrow down the rectangle to the specific location I took a few guesses at the coordinates until the area was found.

Rectangle _pdfRect = new Rectangle(0f, 0f, 612f, 792f); // Entire page - PDF coordinate system 0,0 is bottom left corner.  72 points / inch
RenderFilter _renderfilter = new RegionTextRenderFilter(_pdfRect);
ITextExtractionStrategy _strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), _filter);
string _text = PdfTextExtractor.GetTextFromPage(_pdfReader, 1, _strategy);

As noted by the above comments the resulting text doesn't maintain any of the formatting found in the PDF document, however I was happy that it did preserve the carriage returns. In my case there were enough constants in the text that I was able to extract the values that I required.


Public Sub PDFTxtToPdf(ByVal sTxtfile As String, ByVal sPDFSourcefile As String)
        Dim sr As StreamReader = New StreamReader(sTxtfile)
    Dim doc As New Document()
    PdfWriter.GetInstance(doc, New FileStream(sPDFSourcefile, FileMode.Create))
    doc.Open()
    doc.Add(New Paragraph(sr.ReadToEnd()))
    doc.Close()
End Sub

참고URL : https://stackoverflow.com/questions/2550796/reading-pdf-content-with-itextsharp-dll-in-vb-net-or-c-sharp

반응형