82 votes

Lire le contenu d'un PDF avec la dll itextsharp en VB.NET ou C#

Comment lire le contenu d'un PDF avec la classe Pdfreader d'itextsharp. Mon PDF peut contenir du texte brut ou des images du texte.

0 votes

ITextSharp s'appelle désormais " iText 7 pour .NET " ou " itext7-dotnet " sur github : enlace . Il est recommandé d'ajouter itext7 avec Nuget à votre solution.

1voto

VDWWD Points 22118

Voici une réponse améliorée de ShravankumarKumar. J'ai créé des classes spéciales pour les pages afin que vous puissiez accéder aux mots dans le pdf en fonction des lignes de texte et du mot dans cette ligne.

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;

//create a list of pdf pages
var pages = new List<PdfPage>();

//load the pdf into the reader. NOTE: path can also be replaced with a byte array
using (PdfReader reader = new PdfReader(path))
{
    //loop all the pages and extract the text
    for (int i = 1; i <= reader.NumberOfPages; i++)
    {
        pages.Add(new PdfPage()
        {
           content = PdfTextExtractor.GetTextFromPage(reader, i)
        });
    }
}

//use linq to create the rows and words by splitting on newline and space
pages.ForEach(x => x.rows = x.content.Split('\n').Select(y => 
    new PdfRow() { 
       content = y,
       words = y.Split(' ').ToList()
    }
).ToList());

Les classes personnalisées

class PdfPage
{
    public string content { get; set; }
    public List<PdfRow> rows { get; set; }
}

class PdfRow
{
    public string content { get; set; }
    public List<string> words { get; set; }
}

Maintenant vous pouvez obtenir un mot par ligne et par index de mot.

string myWord = pages[0].rows[12].words[4];

Ou utilisez Linq pour trouver les lignes contenant un mot spécifique.

//find the rows in a specific page containing a word
var myRows = pages[0].rows.Where(x => x.words.Any(y => y == "myWord1")).ToList();

//find the rows in all pages containing a word
var myRows = pages.SelectMany(r => r.rows).Where(x => x.words.Any(y => y == "myWord2")).ToList();

-2voto

Raja Points 1
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

1 votes

La question demande de lire un fichier PDF, votre réponse consiste à en créer un !

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X