L'extraction de texte est l'une des tâches les plus courantes dans le traitement des fichiers PDF. Que vous construisiez un moteur de recherche de documents, une application de data mining ou un système de gestion de contenu, la capacité d'extraire du texte des fichiers PDF est essentielle. Ce tutoriel couvre la Démonstration "Extract Text" (Extraction de texte). Démonstration, qui montre comment extraire le contenu textuel des documents PDF à l'aide de PDFium VCL.
Aperçu
La démonstration "Extract Text" montre comment extraire tout le contenu textuel d'un document PDF et le sauvegarder dans un fichier texte. Elle prend en charge la sélection de plages de pages, la conservation des paragraphes et gère correctement les caractères spéciaux.
Principales fonctionnalités
- Extraction complète du document. – Extraire le texte de toutes les pages en une seule fois.
- Sélection de la plage de pages – Extraire le texte de pages spécifiques uniquement.
- Détection des paragraphes. – Conserver la structure des paragraphes en fonction des positions des caractères.
- Gestion des caractères spéciaux. – Option pour supprimer les caractères NUL de la sortie.
- Séparateurs de page. – Lignes vides facultatives entre les pages.
- Suivi de la progression. – Barre de progression visuelle et journalisation détaillée.
- Sortie UTF-8. – Texte de sortie correctement encodé pour les documents internationaux.
- Accès au niveau des caractères – Accédez aux caractères individuels pour un traitement avancé.
Exigences des DLL PDFium
Avant d'exécuter toute application PDFium VCL, assurez-vous que les fichiers DLL PDFium sont installés :
pdfium32.dll/pdfium64.dll– Versions standard (environ 5-6 Mo)pdfium32v8.dll/pdfium64v8.dll– Avec le moteur JavaScript V8 (environ 23-27 Mo)
Installation : Exécuter PDFiumVCL\DLLs\CopyDlls.bat en tant qu'administrateur pour copier automatiquement les DLL dans les répertoires système Windows.
Extraction de texte de base.
La méthode la plus simple pour extraire du texte d'une page PDF :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
procedure ExtractSimpleText; var Pdf: TPdf; PageText: string; begin Pdf := TPdf.Create(nil); try Pdf.FileName := 'document.pdf'; Pdf.Active := True; // Extract text from page 1 Pdf.PageNumber := 1; PageText := Pdf.Text; // Use the extracted text Memo1.Lines.Text := PageText; finally Pdf.Active := False; Pdf.Free; end; end; |
Extraction de toutes les pages.
Parcourez toutes les pages pour extraire le texte complet du document :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
procedure TFormMain.ButtonExtractClick(Sender: TObject); var I, StartPage, EndPage: Integer; PageText: string; FileStream: TFileStream; Text: UTF8String; begin Pdf.FileName := EditPdfFile.Text; Pdf.PageNumber := 0; Pdf.Active := True; try // Determine page range if RadioButtonAllPages.Checked then begin StartPage := 1; EndPage := Pdf.PageCount; end else begin StartPage := StrToInt(EditFromPage.Text); EndPage := StrToInt(EditToPage.Text); end; // Create output file FileStream := TFileStream.Create(EditOutputFile.Text, fmCreate); try for I := StartPage to EndPage do begin Pdf.PageNumber := I; PageText := Pdf.Text; // Convert to UTF-8 and write Text := UTF8Encode(PageText); if Length(Text) > 0 then FileStream.WriteBuffer(Text[1], Length(Text)); // Add page separator if enabled if CheckBoxPageSeparator.Checked and (I < EndPage) then begin Text := UTF8Encode(#13#10#13#10#13#10); FileStream.WriteBuffer(Text[1], Length(Text)); end; ProgressBar.Position := I - StartPage + 1; Application.ProcessMessages; end; finally FileStream.Free; end; finally Pdf.Active := False; end; end; |
Extraction de texte avec préservation des paragraphes.
Pour les documents où la structure des paragraphes est importante, utilisez l'analyse de la position des caractères :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
function ExtractTextWithParagraphs(Pdf: TPdf): string; var CharIndex: Integer; CurrentChar: WideChar; CurrentY, PrevY: Double; LineHeight, YGap: Double; ResultText, LineBuffer: string; MinLineHeight: Double; begin ResultText := ''; LineBuffer := ''; PrevY := -1; MinLineHeight := 999999; // First pass: determine typical line height for CharIndex := 0 to Pdf.CharacterCount - 1 do begin CurrentY := Pdf.CharacterOrigin[CharIndex].Y; if PrevY >= 0 then begin YGap := Abs(CurrentY - PrevY); if (YGap > 0) and (YGap < MinLineHeight) then MinLineHeight := YGap; end; PrevY := CurrentY; end; LineHeight := MinLineHeight; if LineHeight <= 0 then LineHeight := 12; // Default fallback // Second pass: build text with paragraph detection PrevY := -1; for CharIndex := 0 to Pdf.CharacterCount - 1 do begin CurrentChar := Pdf.Character[CharIndex]; CurrentY := Pdf.CharacterOrigin[CharIndex].Y; // Skip NUL characters if Ord(CurrentChar) = 0 then Continue; // Check for line break based on Y position change if PrevY >= 0 then begin YGap := Abs(CurrentY - PrevY); if YGap > LineHeight * 1.2 then begin // Add current line to result if LineBuffer <> '' then begin ResultText := ResultText + LineBuffer + #13#10; LineBuffer := ''; end; // Check if this is a paragraph break (larger gap) if YGap > LineHeight * 2.5 then ResultText := ResultText + #13#10; // Extra line for paragraph end; end; LineBuffer := LineBuffer + CurrentChar; PrevY := CurrentY; end; // Add final line if LineBuffer <> '' then ResultText := ResultText + LineBuffer; Result := ResultText; end; |
Nettoyage du texte extrait.
Supprimez les caractères NUL et normalisez le texte :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function CleanAndFormatText(const RawText: string): UTF8String; var I: Integer; CleanText: string; begin CleanText := ''; for I := 1 to Length(RawText) do begin // Skip NUL characters but keep all other characters if Ord(RawText[I]) <> 0 then CleanText := CleanText + RawText[I]; end; Result := UTF8Encode(CleanText); end; |
Extraction de texte d'une région spécifique.
Extrayez le texte d'une zone rectangulaire de la page :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
procedure ExtractTextFromRegion; var Pdf: TPdf; RegionText: string; begin Pdf := TPdf.Create(nil); try Pdf.FileName := 'document.pdf'; Pdf.Active := True; Pdf.PageNumber := 1; // Extract text from specific rectangle // Parameters: Left, Top, Right, Bottom (in PDF coordinates) RegionText := Pdf.TextInRectangle(100, 700, 500, 600); ShowMessage('Text in region: ' + RegionText); finally Pdf.Active := False; Pdf.Free; end; end; |
Accès au niveau des caractères
Pour une analyse textuelle précise, accédez aux caractères individuels :
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
procedure AnalyzeCharacters; var Pdf: TPdf; I: Integer; Char: WideChar; Origin: TPdfPoint; Rect: TPdfRectangle; FontSize: Double; begin Pdf := TPdf.Create(nil); try Pdf.FileName := 'document.pdf'; Pdf.Active := True; Pdf.PageNumber := 1; // Access each character for I := 0 to Pdf.CharacterCount - 1 do begin Char := Pdf.Character[I]; Origin := Pdf.CharacterOrigin[I]; Rect := Pdf.CharacterRectangle[I]; FontSize := Pdf.FontSize[I]; // Check character properties if Pdf.CharacterGenerated[I] then // Character was generated (e.g., hyphenation) Continue; if Pdf.CharacterMapError[I] then // Character couldn't be mapped to Unicode Continue; // Process character with position and size info Memo1.Lines.Add(Format('Char: %s at (%.2f, %.2f) size: %.2f', [Char, Origin.X, Origin.Y, FontSize])); end; finally Pdf.Active := False; Pdf.Free; end; end; |
Recherche du caractère à une position donnée à l'écran
Utile pour la sélection et l'interaction avec le texte :
|
1 2 3 4 5 |
function GetCharacterAtPosition(Pdf: TPdf; X, Y: Double): Integer; begin // Get character index at position with tolerance Result := Pdf.CharacterIndexAtPos(X, Y, 5.0, 5.0); end; |
Gestion des erreurs et des cas limites
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
procedure TFormMain.SafeExtractText; begin try Pdf.FileName := EditPdfFile.Text; Pdf.PageNumber := 0; Pdf.Active := True; except on E: Exception do begin LogMessage('Failed to load PDF: ' + E.Message); Exit; end; end; try for I := StartPage to EndPage do begin try Pdf.PageNumber := I; PageText := Pdf.Text; // Process text... except on E: Exception do begin // Log error but continue with next page LogMessage('Error on page ' + IntToStr(I) + ': ' + E.Message); end; end; end; finally Pdf.Active := False; end; end; |
Considérations de performance
- Extrayez le texte page par page plutôt que de tout charger en mémoire.
- Utilisez une sortie de fichier en streaming pour les documents volumineux.
- Appelez
Application.ProcessMessagesdans des boucles pour une meilleure réactivité de l'interface utilisateur. - Envisagez le traitement par lots pour plusieurs documents.
Conclusion.
La démo d'extraction de texte montre comment PDFium VCL rend l'extraction de texte simple et fiable. Que vous ayez besoin d'une extraction de texte basique ou d'un traitement avancé sensible aux paragraphes, ce composant fournit tous les outils nécessaires.
L'accès au niveau des caractères permet une analyse de texte sophistiquée, tandis que la simplicité Text Cette fonctionnalité gère la plupart des cas d'utilisation courants avec une seule ligne de code.
Commencez à créer votre solution d'extraction de texte avec. Composant PDFium VCL today.