Installed via NuGet

PM> Install-Package Spire.PDF

Related Links

Searching for a specific text in a PDF document can sometimes be annoying, especially when the document contains hundreds of pages. Highlighting the text with a background color can help you find and locate it quickly. In this article, you will learn how to find and highlight specific text in PDF in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Find and Highlight Specific Text in PDF in C# and VB.NET

The following are the steps to find and highlight a specific text in a PDF document:

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Create a PdfTextFindOptions instance.
  • Specify the text finding parameter through PdfTextFindOptions.Parameter property.
  • Loop through the pages in the PDF document.
  • Within the loop, create a PdfTextFinder instance and set the text finding option through PdfTextFinder.Options property.
  • Find a specific text in the document using PdfTextFinder.Find() method and save the results into a PdfTextFragment list.
  • Loop through the list and call PdfTextFragment.Highlight() method to highlight all occurrences of the specific text with color.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Instalado via NuGet

PM> Install-Package Spire.PDF

Links Relacionados

Às vezes, procurar um texto específico em um documento PDF pode ser irritante, especialmente quando o documento contém centenas de páginas. Destacar o texto com uma cor de fundo pode ajudá-lo a encontrá-lo e localizá-lo rapidamente. Neste artigo, você aprenderá como localizar e destacar texto específico em PDF em C# e VB.NET usando Spire.PDF for .NET.

Instale o Spire.PDF for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLLs podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.PDF

Encontre e destaque texto específico em PDF em C# e VB.NET

A seguir estão as etapas para localizar e destacar um texto específico em um documento PDF:

  • Crie uma instância de PdfDocument.
  • Carregue um documento PDF usando o método PdfDocument.LoadFromFile().
  • Crie uma instância de PdfTextFindOptions.
  • Especifique o parâmetro de localização de texto por meio da propriedade PdfTextFindOptions.Parameter.
  • Percorra as páginas do documento PDF.
  • Dentro do loop, crie uma instância de PdfTextFinder e defina a opção de localização de texto por meio da propriedade PdfTextFinder.Options.
  • Encontre um texto específico no documento usando o método PdfTextFinder.Find() e salve os resultados em uma lista PdfTextFragment.
  • Percorra a lista e chame o método PdfTextFragment.Highlight() para destacar todas as ocorrências do texto específico com cor.
  • Salve o documento resultante usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Установлено через NuGet

PM> Install-Package Spire.PDF

Ссылки по теме

Поиск определенного текста в PDF-документе иногда может раздражать, особенно если документ содержит сотни страниц. Выделение текста цветом фона может помочь вам быстро найти его. В этой статье вы узнаете, как находите и выделяйте определенный текст в формате PDF на C# и VB.NET с помощью Spire.PDF for .NET.

Установите Spire.PDF for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.PDF for.NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.PDF

Найдите и выделите определенный текст в PDF на C# и VB.NET

Ниже приведены шаги для поиска и выделения определенного текста в PDF-документе:

  • Создайте экземпляр PDFDocument.
  • Загрузите PDF-документ с помощью метода PdfDocument.LoadFromFile().
  • Создайте экземпляр PdfTextFindOptions.
  • Укажите параметр поиска текста через свойство PdfTextFindOptions.Parameter.
  • Перелистывайте страницы PDF-документа.
  • В цикле создайте экземпляр PdfTextFinder и установите параметр поиска текста через свойство PdfTextFinder.Options.
  • Найдите определенный текст в документе с помощью метода PdfTextFinder.Find() и сохраните результаты в списке PdfTextFragment.
  • Прокрутите список и вызовите метод PdfTextFragment.Highlight(), чтобы выделить цветом все вхождения определенного текста.
  • Сохраните полученный документ с помощью метода PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Über NuGet installiert

PM> Install-Package Spire.PDF

verwandte Links

Die Suche nach einem bestimmten Text in einem PDF-Dokument kann manchmal lästig sein, insbesondere wenn das Dokument Hunderte von Seiten umfasst. Wenn Sie den Text mit einer Hintergrundfarbe hervorheben, können Sie ihn schneller finden und finden. In diesem Artikel erfahren Sie, wie das geht Finden und markieren Sie bestimmten Text in PDF in C# und VB.NET mit Spire.PDF for .NET.

Installieren Sie Spire.PDF for .NET

Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.PDF

Suchen und markieren Sie bestimmten Text in PDF in C# und VB.NET

Im Folgenden finden Sie die Schritte, um einen bestimmten Text in einem PDF-Dokument zu finden und hervorzuheben:

  • Erstellen Sie eine PdfDocument-Instanz.
  • Laden Sie ein PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
  • Erstellen Sie eine PdfTextFindOptions-Instanz.
  • Geben Sie den Textsuchparameter über die Eigenschaft PdfTextFindOptions.Parameter an.
  • Durchlaufen Sie die Seiten im PDF-Dokument.
  • Erstellen Sie innerhalb der Schleife eine PdfTextFinder-Instanz und legen Sie die Textsuchoption über die Eigenschaft PdfTextFinder.Options fest.
  • Suchen Sie mit der Methode PdfTextFinder.Find() nach einem bestimmten Text im Dokument und speichern Sie die Ergebnisse in einer PdfTextFragment-Liste.
  • Durchlaufen Sie die Liste und rufen Sie die Methode PdfTextFragment.Highlight() auf, um alle Vorkommen des spezifischen Textes farbig hervorzuheben.
  • Speichern Sie das Ergebnisdokument mit der Methode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

Buscar un texto específico en un documento PDF a veces puede resultar molesto, especialmente cuando el documento contiene cientos de páginas. Resaltar el texto con un color de fondo puede ayudarle a encontrarlo y localizarlo rápidamente. En este artículo, aprenderá cómo buscar y resaltar texto específico en PDF en C# y VB.NET usando Spire.PDF for .NET.

Instalar Spire.PDF for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.PDF

Busque y resalte texto específico en PDF en C# y VB.NET

Los siguientes son los pasos para buscar y resaltar un texto específico en un documento PDF:

  • Cree una instancia de PdfDocument.
  • Cargue un documento PDF utilizando el método PdfDocument.LoadFromFile().
  • Cree una instancia de PdfTextFindOptions.
  • Especifique el parámetro de búsqueda de texto a través de la propiedad PdfTextFindOptions.Parameter.
  • Recorra las páginas del documento PDF.
  • Dentro del bucle, cree una instancia de PdfTextFinder y configure la opción de búsqueda de texto a través de la propiedad PdfTextFinder.Options.
  • Busque un texto específico en el documento utilizando el método PdfTextFinder.Find() y guarde los resultados en una lista de PdfTextFragment.
  • Recorra la lista y llame al método PdfTextFragment.Highlight() para resaltar todas las apariciones del texto específico con color.
  • Guarde el documento resultante utilizando el método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Solicitar una licencia temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

NuGet을 통해 설치됨

PM> Install-Package Spire.PDF

관련된 링크들

PDF 문서에서 특정 텍스트를 검색하는 것은 때때로 짜증스러울 수 있습니다. 특히 문서에 수백 페이지가 포함되어 있는 경우 더욱 그렇습니다. 배경색으로 텍스트를 강조 표시하면 텍스트를 빠르게 찾고 찾는 데 도움이 됩니다. 이 기사에서는 다음 방법을 배웁니다 C# 및 VB.NET의 PDF에서 특정 텍스트를 찾아 강조 표시 Spire.PDF for .NET를 사용합니다.

Spire.PDF for .NET 설치

먼저 Spire.PDF for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.PDF

C# 및 VB.NET의 PDF에서 특정 텍스트 찾기 및 강조 표시

다음은 PDF 문서에서 특정 텍스트를 찾아 강조 표시하는 단계입니다.

  • PdfDocument 인스턴스를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 PDF 문서를 로드합니다.
  • PdfTextFindOptions 인스턴스를 만듭니다.
  • PdfTextFindOptions.Parameter 속성을 통해 텍스트 찾기 매개 변수를 지정합니다.
  • PDF 문서의 페이지를 반복합니다.
  • 루프 내에서 PdfTextFinder 인스턴스를 만들고 PdfTextFinder.Options 속성을 통해 텍스트 찾기 옵션을 설정합니다.
  • PdfTextFinder.Find() 메서드를 사용하여 문서에서 특정 텍스트를 찾고 결과를 PdfTextFragment 목록에 저장합니다.
  • 목록을 반복하고 PdfTextFragment.Highlight() 메서드를 호출하여 특정 텍스트의 모든 항목을 색상으로 강조 표시합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

La ricerca di un testo specifico in un documento PDF a volte può essere fastidiosa, soprattutto quando il documento contiene centinaia di pagine. Evidenziare il testo con un colore di sfondo può aiutarti a trovarlo e localizzarlo rapidamente. In questo articolo imparerai come trovare ed evidenziare testo specifico in PDF in C# e VB.NET utilizzando Spire.PDF for .NET.

Installa Spire.PDF for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.PDF

Trova ed evidenzia testo specifico in PDF in C# e VB.NET

Di seguito sono riportati i passaggi per trovare ed evidenziare un testo specifico in un documento PDF:

  • Crea un'istanza PdfDocument.
  • Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
  • Crea un'istanza PdfTextFindOptions.
  • Specificare il parametro di ricerca del testo tramite la proprietà PdfTextFindOptions.Parameter.
  • Scorri le pagine del documento PDF.
  • All'interno del ciclo, crea un'istanza PdfTextFinder e imposta l'opzione di ricerca del testo tramite la proprietà PdfTextFinder.Options.
  • Trova un testo specifico nel documento utilizzando il metodo PdfTextFinder.Find() e salva i risultati in un elenco PdfTextFragment.
  • Passa in rassegna l'elenco e chiama il metodo PdfTextFragment.Highlight() per evidenziare tutte le occorrenze del testo specifico con il colore.
  • Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Installé via NuGet

PM> Install-Package Spire.PDF

Rechercher un texte spécifique dans un document PDF peut parfois s'avérer fastidieux, surtout lorsque le document contient des centaines de pages. Mettre en surbrillance le texte avec une couleur d'arrière-plan peut vous aider à le trouver et à le localiser rapidement. Dans cet article, vous apprendrez comment recherchez et surlignez du texte spécifique dans un PDF en C# et VB.NET à l'aide de Spire.PDF for .NET.

Installer Spire.PDF for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for.NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.PDF

Rechercher et mettre en surbrillance du texte spécifique dans un PDF en C# et VB.NET

Voici les étapes pour rechercher et surligner un texte spécifique dans un document PDF :

  • Créez une instance PdfDocument.
  • Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
  • Créez une instance de PdfTextFindOptions.
  • Spécifiez le paramètre de recherche de texte via la propriété PdfTextFindOptions.Parameter.
  • Parcourez les pages du document PDF.
  • Dans la boucle, créez une instance de PdfTextFinder et définissez l'option de recherche de texte via la propriété PdfTextFinder.Options.
  • Recherchez un texte spécifique dans le document à l'aide de la méthode PdfTextFinder.Find() et enregistrez les résultats dans une liste PdfTextFragment.
  • Parcourez la liste et appelez la méthode PdfTextFragment.Highlight() pour mettre en évidence toutes les occurrences du texte spécifique avec de la couleur.
  • Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Texts;
    using System.Collections.Generic;
    using System.Drawing;
    
    namespace HighlightTextInPdf
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF file
                pdf.LoadFromFile("Sample.pdf");
    
                //Creare a PdfTextFindOptions instance
                PdfTextFindOptions findOptions = new PdfTextFindOptions();
                //Specify the text finding parameter
                findOptions.Parameter = TextFindParameter.WholeWord;
    
                //Loop through the pages in the PDF file
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Create a PdfTextFinder instance
                    PdfTextFinder finder = new PdfTextFinder(page);
                    //Set the text finding option
                    finder.Options = findOptions;
                    //Find a specific text
                    List<PdfTextFragment> results = finder.Find("Video");
                    //Highlight all occurrences of the specific text
                    foreach (PdfTextFragment text in results)
                    {
                        text.HighLight(Color.Green);
                    }
                }
    
                //Save the result file
                pdf.SaveToFile("HighlightText.pdf");
            }
        }
    }

C#/VB.NET: Find and Highlight Specific Text in PDF

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Wednesday, 30 August 2023 06:53

C#/VB.NET: Extract Images from PDF

Installed via NuGet

PM> Install-Package Spire.PDF

Related Links

Images are often used in PDF documents to present information in an easily understandable manner. In certain cases, you may need to extract images from PDF documents. For example, when you want to use a chart image from a PDF report in a presentation or another document. This article will demonstrate how to extract images from PDF in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Extract Images from PDF in C# and VB.NET

The following are the main steps to extract images from a PDF document using Spire.PDF for .NET:

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Loop through all the pages in the document.
  • Extract images from each page using PdfPageBase.ExtractImages() method and save them to a specified file path.
  • C#
  • VB.NET
using Spire.Pdf;
    using System.Drawing;
    
    namespace ExtractImages
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF document
                pdf.LoadFromFile("Input.pdf");
    
                int i = 1;
                //Loop through all pages in the document
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Extract images from each page and save them to a specified file path
                    foreach (Image image in page.ExtractImages())
                    {
                        image.Save(@"C:/Users/Administrator/Desktop/Images/" + "image" + i + ".png", System.Drawing.Imaging.ImageFormat.Png);
                        i++;
                    }
                }
            }
        }
    }

C#/VB.NET: Extract Images from PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Wednesday, 30 August 2023 06:52

C#/VB.NET: Extraia imagens de PDF

Instalado via NuGet

PM> Install-Package Spire.PDF

Links Relacionados

As imagens são frequentemente usadas em documentos PDF para apresentar informações de maneira facilmente compreensível. Em certos casos, pode ser necessário extrair imagens de documentos PDF. Por exemplo, quando você deseja usar uma imagem gráfica de um relatório PDF em uma apresentação ou outro documento. Este artigo demonstrará como extrair imagens de PDF em C# e VB.NET usando Spire.PDF for .NET.

Instale o Spire.PDF for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.PDF

Extraia imagens de PDF em C# e VB.NET

A seguir estão as etapas principais para extrair imagens de um documento PDF usando Spire.PDF for .NET:

  • Crie um objeto PdfDocument.
  • Carregue um documento PDF usando o método PdfDocument.LoadFromFile().
  • Percorra todas as páginas do documento.
  • Extraia imagens de cada página usando o método PdfPageBase.ExtractImages() e salve-as em um caminho de arquivo especificado.
  • C#
  • VB.NET
using Spire.Pdf;
    using System.Drawing;
    
    namespace ExtractImages
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
                //Load a PDF document
                pdf.LoadFromFile("Input.pdf");
    
                int i = 1;
                //Loop through all pages in the document
                foreach (PdfPageBase page in pdf.Pages)
                {
                    //Extract images from each page and save them to a specified file path
                    foreach (Image image in page.ExtractImages())
                    {
                        image.Save(@"C:/Users/Administrator/Desktop/Images/" + "image" + i + ".png", System.Drawing.Imaging.ImageFormat.Png);
                        i++;
                    }
                }
            }
        }
    }

C#/VB.NET: Extract Images from PDF

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também