C#/VB.NET: agregar propiedades de documento a documentos de Word
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
Las propiedades del documento (también conocidas como metadatos) son un conjunto de información sobre un documento. Todos los documentos de Word vienen con un conjunto de propiedades de documento integradas, que incluyen título, nombre del autor, tema, palabras clave, etc. Además de las propiedades de documento integradas, Microsoft Word también permite a los usuarios agregar propiedades de documento personalizadas a los documentos de Word. En este artículo, explicaremos cómo agregar estas propiedades de documentos a documentos de Word en C# y VB.NET usando Spire.Doc for .NET.
- Agregar propiedades de documento integradas a un documento de Word
- Agregar propiedades de documento personalizadas a un documento de Word
Instalar Spire.Doc for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Doc 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.Doc
Agregue propiedades de documento integradas a un documento de Word en C# y VB.NET
Una propiedad de documento incorporada consta de un nombre y un valor. No puede establecer ni cambiar el nombre de una propiedad de documento incorporada tal como está predefinida por Microsoft Word, pero puede establecer o cambiar su valor. Los siguientes pasos demuestran cómo establecer valores para las propiedades integradas del documento en un documento de Word:
- Inicialice una instancia de la clase Documento.
- Cargue un documento de Word utilizando el método Document.LoadFromFile().
- Obtenga las propiedades integradas del documento a través de la propiedad Document.BuiltinDocumentProperties.
- Establezca valores para propiedades de documentos específicas, como título, asunto y autor, a través de las propiedades Título, Asunto y Autor de la clase BuiltinDocumentProperties.
- Guarde el documento resultante utilizando el método Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
namespace BuiltinDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add built-in document properties to the document
BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
standardProperties.Title = "Add Document Properties";
standardProperties.Subject = "C# Example";
standardProperties.Author = "James";
standardProperties.Company = "Eiceblue";
standardProperties.Manager = "Michael";
standardProperties.Category = "Document Manipulation";
standardProperties.Keywords = "C#, Word, Document Properties";
standardProperties.Comments = "This article shows how to add document properties";
//Save the result document
document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

Agregar propiedades de documento personalizadas a un documento de Word en C# y VB.NET
El autor o usuario del documento puede definir una propiedad de documento personalizada. Cada propiedad de documento personalizado debe contener un nombre, un valor y un tipo de datos. El tipo de datos puede ser uno de estos cuatro tipos: Texto, Fecha, Número y Sí o No. Los siguientes pasos demuestran cómo agregar propiedades de documento personalizadas con diferentes tipos de datos a un documento de Word:
- Inicialice una instancia de la clase Documento.
- Cargue un documento de Word utilizando el método Document.LoadFromFile().
- Obtenga las propiedades personalizadas del documento a través de la propiedad Document.CustomDocumentProperties.
- Agregue propiedades de documento personalizadas con diferentes tipos de datos al documento utilizando el método CustomDocumentProperties.Add(string, object).
- Guarde el documento resultante utilizando el método Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using System;
namespace CustomDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add custom document properties to the document
CustomDocumentProperties customProperties = document.CustomDocumentProperties;
customProperties.Add("Document ID", 1);
customProperties.Add("Authorized", true);
customProperties.Add("Authorized By", "John Smith");
customProperties.Add("Authorized Date", DateTime.Today);
//Save the result document
document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

Solicite 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.
C#/VB.NET: Word 문서에 문서 속성 추가
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
문서 속성(메타데이터라고도 함)은 문서에 대한 정보 집합입니다. 모든 Word 문서에는 제목, 작성자 이름, 주제, 키워드 등을 포함한 일련의 기본 제공 문서 속성이 함께 제공됩니다. Microsoft Word에서는 기본 제공 문서 속성 외에도 사용자가 Word 문서에 사용자 지정 문서 속성을 추가할 수도 있습니다. 이번 글에서는 방법을 설명하겠습니다. C# 및 VB.NET의 Word 문서에 이러한 문서 속성을 추가하세요 using Spire.Doc for .NET 사용합니다.
Spire.Doc for .NET 설치
먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
C# 및 VB.NET의 Word 문서에 기본 제공 문서 속성 추가
기본 제공 문서 속성은 이름과 값으로 구성됩니다. Microsoft Word에서 미리 정의된 내장 문서 속성의 이름은 설정하거나 변경할 수 없지만 해당 값은 설정하거나 변경할 수 있습니다. 다음 단계에서는 Word 문서에서 기본 제공 문서 속성 값을 설정하는 방법을 보여줍니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.BuiltinDocumentProperties 속성을 통해 문서의 내장 문서 속성을 가져옵니다.
- BuildinDocumentProperties 클래스의 Title, Subject, Author 속성을 통해 제목, 주제, 작성자 등 특정 문서 속성에 대한 값을 설정합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc;
namespace BuiltinDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add built-in document properties to the document
BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
standardProperties.Title = "Add Document Properties";
standardProperties.Subject = "C# Example";
standardProperties.Author = "James";
standardProperties.Company = "Eiceblue";
standardProperties.Manager = "Michael";
standardProperties.Category = "Document Manipulation";
standardProperties.Keywords = "C#, Word, Document Properties";
standardProperties.Comments = "This article shows how to add document properties";
//Save the result document
document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

C# 및 VB.NET에서 Word 문서에 사용자 정의 문서 속성 추가
사용자 정의 문서 속성은 문서 작성자나 사용자가 정의할 수 있습니다. 각 사용자 정의 문서 속성에는 이름, 값 및 데이터 유형이 포함되어야 합니다. 데이터 유형은 텍스트, 날짜, 숫자, 예 또는 아니요의 네 가지 유형 중 하나일 수 있습니다. 다음 단계에서는 다양한 데이터 유형을 가진 사용자 정의 문서 속성을 Word 문서에 추가하는 방법을 보여줍니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.CustomDocumentProperties 속성을 통해 문서의 사용자 정의 문서 속성을 가져옵니다.
- CustomDocumentProperties.Add(string, object) 메서드를 사용하여 문서에 다양한 데이터 유형의 사용자 정의 문서 속성을 추가합니다.
- Document.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Doc;
using System;
namespace CustomDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add custom document properties to the document
CustomDocumentProperties customProperties = document.CustomDocumentProperties;
customProperties.Add("Document ID", 1);
customProperties.Add("Authorized", true);
customProperties.Add("Authorized By", "John Smith");
customProperties.Add("Authorized Date", DateTime.Today);
//Save the result document
document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET: aggiungere proprietà del documento ai documenti di Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Le proprietà del documento (note anche come metadati) sono un insieme di informazioni su un documento. Tutti i documenti di Word sono dotati di una serie di proprietà di documento integrate, tra cui titolo, nome dell'autore, oggetto, parole chiave, ecc. Oltre alle proprietà di documento integrate, Microsoft Word consente inoltre agli utenti di aggiungere proprietà di documento personalizzate ai documenti di Word. In questo articolo spiegheremo come aggiungere queste proprietà del documento ai documenti Word in C# e VB.NET utilizzando Spire.Doc for .NET.
- Aggiungi proprietà documento integrate a un documento Word
- Aggiungi proprietà documento personalizzate a un documento Word
Installa Spire.Doc for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc 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.Doc
Aggiungi proprietà documento integrate a un documento Word in C# e VB.NET
Una proprietà del documento incorporata è costituita da un nome e un valore. Non è possibile impostare o modificare il nome di una proprietà del documento incorporata poiché è predefinita da Microsoft Word, ma è possibile impostarne o modificarne il valore. I passaggi seguenti dimostrano come impostare i valori per le proprietà del documento integrate in un documento di Word:
- Inizializza un'istanza della classe Document.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Ottieni le proprietà del documento integrate del documento tramite la proprietà Document.BuiltinDocumentProperties.
- Imposta valori per proprietà specifiche del documento come titolo, oggetto e autore tramite le proprietà Titolo, Oggetto e Autore della classe BuiltinDocumentProperties.
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
namespace BuiltinDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add built-in document properties to the document
BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
standardProperties.Title = "Add Document Properties";
standardProperties.Subject = "C# Example";
standardProperties.Author = "James";
standardProperties.Company = "Eiceblue";
standardProperties.Manager = "Michael";
standardProperties.Category = "Document Manipulation";
standardProperties.Keywords = "C#, Word, Document Properties";
standardProperties.Comments = "This article shows how to add document properties";
//Save the result document
document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

Aggiungi proprietà documento personalizzate a un documento Word in C# e VB.NET
Una proprietà del documento personalizzata può essere definita dall'autore o dall'utente del documento. Ciascuna proprietà del documento personalizzato deve contenere un nome, un valore e un tipo di dati. Il tipo di dati può essere uno di questi quattro tipi: Testo, Data, Numero e Sì o No. I passaggi seguenti mostrano come aggiungere proprietà di documento personalizzate con diversi tipi di dati a un documento di Word:
- Inizializza un'istanza della classe Document.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Ottieni le proprietà personalizzate del documento tramite la proprietà Document.CustomDocumentProperties.
- Aggiungi proprietà di documento personalizzate con diversi tipi di dati al documento utilizzando il metodo CustomDocumentProperties.Add(string, object).
- Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using System;
namespace CustomDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add custom document properties to the document
CustomDocumentProperties customProperties = document.CustomDocumentProperties;
customProperties.Add("Document ID", 1);
customProperties.Add("Authorized", true);
customProperties.Add("Authorized By", "John Smith");
customProperties.Add("Authorized Date", DateTime.Today);
//Save the result document
document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

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.
C#/VB.NET : ajouter des propriétés de document aux documents Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
Les propriétés du document (également appelées métadonnées) sont un ensemble d'informations sur un document. Tous les documents Word sont livrés avec un ensemble de propriétés de document intégrées, notamment le titre, le nom de l'auteur, le sujet, les mots-clés, etc. En plus des propriétés de document intégrées, Microsoft Word permet également aux utilisateurs d'ajouter des propriétés de document personnalisées aux documents Word. Dans cet article, nous expliquerons comment ajouter ces propriétés de document aux documents Word en C# et VB.NET en utilisant Spire.Doc for .NET.
- Ajouter des propriétés de document intégrées à un document Word
- Ajouter des propriétés de document personnalisées à un document Word
Installer Spire.Doc for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc 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.Doc
Ajouter des propriétés de document intégrées à un document Word en C# et VB.NET
Une propriété de document intégrée se compose d'un nom et d'une valeur. Vous ne pouvez pas définir ou modifier le nom d'une propriété de document intégrée car elle est prédéfinie par Microsoft Word, mais vous pouvez définir ou modifier sa valeur. Les étapes suivantes montrent comment définir les valeurs des propriétés de document intégrées dans un document Word :
- Initialisez une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Obtenez les propriétés de document intégrées du document via la propriété Document.BuiltinDocumentProperties.
- Définissez des valeurs pour des propriétés de document spécifiques telles que le titre, le sujet et l'auteur via les propriétés Titre, Sujet et Auteur de la classe BuiltinDocumentProperties.
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
namespace BuiltinDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add built-in document properties to the document
BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
standardProperties.Title = "Add Document Properties";
standardProperties.Subject = "C# Example";
standardProperties.Author = "James";
standardProperties.Company = "Eiceblue";
standardProperties.Manager = "Michael";
standardProperties.Category = "Document Manipulation";
standardProperties.Keywords = "C#, Word, Document Properties";
standardProperties.Comments = "This article shows how to add document properties";
//Save the result document
document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

Ajouter des propriétés de document personnalisées à un document Word en C# et VB.NET
Une propriété de document personnalisée peut être définie par un auteur ou un utilisateur de document. Chaque propriété de document personnalisée doit contenir un nom, une valeur et un type de données. Le type de données peut être l'un des quatre types suivants : Texte, Date, Nombre et Oui ou Non. Les étapes suivantes montrent comment ajouter des propriétés de document personnalisées avec différents types de données à un document Word :
- Initialisez une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Obtenez les propriétés personnalisées du document via la propriété Document.CustomDocumentProperties.
- Ajoutez des propriétés de document personnalisées avec différents types de données au document à l'aide de la méthode CustomDocumentProperties.Add(string, object).
- Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using System;
namespace CustomDocumentProperties
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document document = new Document();
//Load a Word document
document.LoadFromFile("Sample.docx");
//Add custom document properties to the document
CustomDocumentProperties customProperties = document.CustomDocumentProperties;
customProperties.Add("Document ID", 1);
customProperties.Add("Authorized", true);
customProperties.Add("Authorized By", "John Smith");
customProperties.Add("Authorized Date", DateTime.Today);
//Save the result document
document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
}
}
}

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.
- C#/VB.NET : insérer des listes dans un document Word
- C#/VB.NET : détecter et supprimer les macros VBA des documents Word
- C#/VB.NET : insérer des équations mathématiques dans des documents Word
- C#/VB.NET : comparer deux documents Word
- C#/VB.NET : accepter ou rejeter les modifications suivies dans Word
C#/VB.NET: Find and Highlight Specific Text in PDF
Table of Contents
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");
}
}
}

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.
C#/VB.NET: Encontre e destaque texto específico em PDF
Índice
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");
}
}
}

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.
C#/VB.NET: поиск и выделение определенного текста в PDF
Оглавление
Установлено через 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");
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: Bestimmten Text in PDF suchen und hervorheben
Inhaltsverzeichnis
Ü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");
}
}
}

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.
C#/VB.NET: busque y resalte texto específico en PDF
Tabla de contenido
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");
}
}
}

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.
C#/VB.NET: PDF에서 특정 텍스트 찾기 및 강조 표시
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");
}
}
}

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