이 빠른 가이드는 자세한 단계와 실행 가능한 코드를 사용하여 C#을 사용하여 PDF에서 텍스트를 찾고 바꾸는 방법을 설명합니다. 환경 구성을 지원한 다음 C#을 사용하여 PDF의 텍스트를 교체하는 단계별 프로세스를 제공합니다. 파일이 업데이트되면 원래 형식(예: PDF 또는 DOCX, Excel, HTML 등)으로 디스크에 다시 저장할 수 있습니다.
C#을 사용하여 PDF에서 텍스트를 찾고 바꾸는 단계
- NuGet 패키지 관리자를 사용하여 Aspose.PDF for .NET을(를) 사용하도록 프로젝트 구성
- Document 클래스 개체를 사용하여 샘플 텍스트가 포함된 PDF 파일 생성 또는 로드
- TextFragmentAbsorber 클래스 개체를 사용하여 검색할 텍스트 설정
- 입력 PDF 파일의 모든 페이지에 대해 텍스트 흡수기를 허용합니다.
- 로드된 PDF 파일에서 텍스트가 추출되는 조각 모음 가져오기
- 모든 조각을 구문 분석하고 새 텍스트 설정
- 업데이트된 PDF 파일 저장
이 단계에서는 *PDF에서 C#*을 사용하여 텍스트를 검색하고 바꾸는 방법을 설명합니다. 일부 샘플 텍스트가 포함된 새 파일이 생성되지만 텍스트가 대체될 기존 PDF 파일을 로드할 수 있습니다. 그림자 텍스트 무시, 페이지 경계로 검색 제한 등과 같이 PDF에서 텍스트를 검색하는 데 사용할 수 있는 다양한 옵션이 있습니다.
C#을 사용하여 PDF의 텍스트를 바꾸는 코드
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"); | |
} | |
} | |
} |
이 코드는 텍스트에 TextFragmentAbsorber 및 TextFragment를 사용하여 C#*을 사용하여 PDF에서 *찾고 대체합니다. 결과 PDF 파일에서 텍스트를 바꿀 수 있을 뿐만 아니라 글꼴 패밀리, 크기, 전경색 및 배경색도 변경할 수 있습니다. 전체 PDF의 텍스트를 한 번에 바꾸거나 정규식을 기반으로 텍스트를 바꾸는 옵션도 사용할 수 있습니다.
이 주제에서는 PDF에서 텍스트를 찾고 바꾸는 방법을 배웠지만 PDF 파일을 페이지별로 분할하는 방법을 배우려면 C#에서 페이지별로 PDF 파일을 분할하는 방법에 대한 문서를 참조하세요.