Itext 7 IPdfTextLocation.GetPageNumber постоянно поднимается до 0 - PullRequest
1 голос
/ 12 марта 2020

Я пишу (VB /Net) процедуру, которая ищет в документе PDF шаблон Regex и записывает текстовый файл с соответствующими местоположениями:

    Public Sub ReadAndMatch(ByVal InputFileName As String, OutputFileName As String, RegexPattern As String)
        Dim pdfIn As New iText.Kernel.Pdf.PdfReader(InputFileName) ' A Pdfreader object associated with the input file name
        Dim pdfDoc As New iText.Kernel.Pdf.PdfDocument(pdfIn) 'This object holds the actual document being analyzed
        Dim strategy As New iText.Kernel.Pdf.Canvas.Parser.Listener.RegexBasedLocationExtractionStrategy(RegexPattern) 'extraction strategy
        Dim Parser As iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor = New Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor(strategy)
        Dim Loclist As System.Collections.ICollection 'all the matches
        Dim Location As iText.Kernel.Pdf.Canvas.Parser.Listener.IPdfTextLocation 'one match
        Dim CoordFile As New System.IO.StreamWriter(OutputFileName) 'initiate output stream
        Dim TextString As String
        Dim L, B, W, H As Single ' Left, bottom, width & height of the rectangle containing the extracted text
        Dim pg As Integer = 0 'number of current page, number of matches in page, total number of matches
        Do While pg < pdfDoc.GetNumberOfPages 'loop thru document pages 
            pg += 1
            Parser.ProcessPageContent(pdfDoc.GetPage(pg)) 'parse page
        Loop
        Loclist = strategy.GetResultantLocations
        If Loclist.Count = 0 Then Exit Sub
        For Each Location In Loclist
            L = Location.GetRectangle.GetLeft
            B = Location.GetRectangle.GetBottom
            W = Location.GetRectangle.GetWidth
            H = Location.GetRectangle.GetHeight
            TextString = Location.GetText
            pg = Location.GetPageNumber
            CoordFile.WriteLine(TextString & Chr(9) & L & Chr(9) & B & Chr(9) & W & Chr(9) & H & Chr(9) & pg & Chr(9) & InputFileName)
        Next Location
        'Finished processing
        pdfDoc.Close() 'close pdf
        CoordFile.Close() 'close output file
    End Sub

Я получаю координаты прямоугольника ОК и соответствующая текстовая строка, но location.GetPageNumber всегда 0

Что я делаю не так?

1 Ответ

1 голос
/ 14 марта 2020

Вот обходной путь, который я использовал. Я заново инициирую объект стратегии и объект синтаксического анализа на каждой странице, а также выводю местоположения, соответствующие шаблону Regex на страницу. Таким образом, я могу использовать собственный счетчик pg, хотя l oop вместо того, который [не] задан методом .PageNumber:

    Private Sub Main() 'the main processing routine
        'Sub assumes that the PDF document (pdfDoc) and the output file (CoordFile) --both module level object-- are open and available
        Dim Location As iText.Kernel.Pdf.Canvas.Parser.Listener.IPdfTextLocation
        Dim TextString As String
        Dim L, B, W, H As Single ' Left, bottom, width & height of the rectangle containing the extracted text
        Dim pg As Integer = 0 'number of current page, number of matches
        Dim N As Integer = 0
        Do While pg < pdfDoc.GetNumberOfPages 'loop thru document pages 
            pg += 1
            Dim strategy As New iText.Kernel.Pdf.Canvas.Parser.Listener.RegexBasedLocationExtractionStrategy(RegexPattern) 'extraction strategy (RegexPattern is a module variable)
            Dim Parser As iText.Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor = New Kernel.Pdf.Canvas.Parser.PdfCanvasProcessor(strategy)
            Parser.ProcessPageContent(pdfDoc.GetPage(pg)) 'parse page
            If strategy.GetResultantLocations.Count > 0 Then
                For Each Location In strategy.GetResultantLocations
                    TextString = Location.GetText
                    L = Location.GetRectangle.GetLeft
                    B = Location.GetRectangle.GetBottom
                    W = Location.GetRectangle.GetWidth
                    H = Location.GetRectangle.GetHeight
                    CoordFile.WriteLine(TextString & Chr(9) & L & Chr(9) & B & Chr(9) & W & Chr(9) & H & Chr(9) & pg)
                    N += 1
                Next Location
            End If
            strategy.GetResultantLocations.Clear() 'dispose loclist
        Loop

        'Finished processing
        pdfDoc.Close()
        CoordFile.Close() 'close output file
    End Sub

... не элегантно, но работает ...

...