Esta guía rápida describe cómo buscar y reemplazar texto en PDF usando C# con la ayuda de pasos detallados y un código ejecutable. Ayuda a configurar el entorno y luego proporciona un proceso paso a paso para reemplazar texto en un PDF usando C#. Una vez que se actualice el archivo, puede volver a guardarlo en el disco en el formato original, es decir, PDF o como DOCX, Excel, HTML, etc., por nombrar algunos.
Pasos para buscar y reemplazar texto en PDF usando C#
- Configure el proyecto para usar Aspose.PDF for .NET usando el administrador de paquetes NuGet
- Cree o cargue un archivo PDF que contenga texto de muestra usando el objeto de clase Document
- Usando el objeto de clase TextFragmentAbsorber, configure el texto que se buscará
- Para todas las páginas del archivo PDF de entrada, acepte el absorbente de texto
- Obtenga la colección de fragmentos donde se extrae el texto del archivo PDF cargado
- Analice todos los fragmentos y establezca un nuevo texto
- Guarde el archivo PDF actualizado
Estos pasos describen cómo en un PDF buscar y reemplazar texto usando C#. Se crea un nuevo archivo con texto de muestra; sin embargo, puede cargar un archivo PDF existente cuyo texto se va a reemplazar. Hay una variedad de opciones disponibles para buscar texto en el PDF, como ignorar el texto sombreado, limitar la búsqueda a la página encuadernada, etc.
Código para reemplazar texto en un PDF usando C#
using Aspose.Pdf; | |
using Aspose.Pdf.Text; | |
namespace FindAndReplaceTextInPdfUsingCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to create 7z archive in CSharp | |
{ | |
// Instantiate a license to avoid watermark in output PDF | |
Aspose.Pdf.License licForPdf= new Aspose.Pdf.License(); | |
licForPdf.SetLicense("Aspose.Pdf.lic"); | |
// Create an empty PDF document | |
Document newPDFFile = new Document(); | |
// Add an empty page in the newly created PDF | |
Page page = newPDFFile.Pages.Add(); | |
// Add sample text in the PDF file | |
for(int iTxtCounter = 0 ; iTxtCounter < 15; iTxtCounter++) | |
page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment($"my_data\nanother data")); | |
// Save the newly created PDF file containing the test data in it | |
newPDFFile.Save("InputPDFToReplaceText.pdf"); | |
// Open PDF document to replace text in it | |
Document inputPDFFile = new Document("InputPDFToReplaceText.pdf"); | |
// Set the text that is to be searched in the TextAbsorber object | |
TextFragmentAbsorber txtAbsorber = new TextFragmentAbsorber("my_data"); | |
// Apply the text absorber for all the pages in the input PDF file | |
inputPDFFile.Pages.Accept(txtAbsorber); | |
// Get the collection of fragments containing extracted text from the PDF | |
TextFragmentCollection textFragmentCollection = txtAbsorber.TextFragments; | |
// Parse all the fragments and replace text using particular font, size and foreground/background color | |
foreach (TextFragment txtFragment in textFragmentCollection) | |
txtFragment.Text = "MY_DATA"; | |
// Save resulting PDF document. | |
inputPDFFile.Save("OutputPDFAfterReplacingText.pdf"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
Este código usa TextFragmentAbsorber y TextFragment para que el texto busque y reemplace en PDF usando C#. No solo puede reemplazar el texto, sino también cambiar su familia de fuentes, tamaño, color de primer plano y color de fondo en el archivo PDF resultante. También hay opciones disponibles para reemplazar el texto en todo el PDF a la vez o reemplazar el texto en función de la expresión regular.
En este tema, hemos aprendido a buscar y reemplazar texto en PDF; sin embargo, si desea aprender a dividir archivos PDF por páginas, consulte el artículo sobre cómo dividir un archivo PDF por páginas en C#.