프로그래밍 방식으로 다양한 유형의 문서를 읽는 것은 오늘날 일반적인 관행입니다. 이 방법 가이드에서는 아래의 간단한 단계에 따라 C#에서 PDF 파일을 읽는 방법을 배우게 됩니다.
C#에서 PDF 파일을 읽는 단계
- Visual Studio에서 빈 C# 콘솔 애플리케이션 만들기
- NuGet.org에서 설치하여 Aspose.PDF for .NET에 대한 참조 추가
- Document 개체에 기존 PDF 파일 로드
- PDF 파일을 읽기 위해 TextAbsorber 클래스 초기화
- PDF 텍스트를 추출하여 콘솔 출력에 씁니다.
- PDF 페이지 Resources를 반복하여 이미지를 찾습니다.
- 찾은 이미지로 FileStream 객체 생성
- 이미지를 로컬 디스크에 저장
아래 코드 스니펫은 C#에서 PDF 파일을 열고 읽는 방법을 설명합니다. PDF 파일을 사용하여 텍스트를 읽고 이미지를 추출할 수 있습니다. API는 PDF 파일에서 텍스트를 읽는 데 사용되는 TextAbsorber 클래스를 제공하며 Text 개체를 통해 추출된 결과를 얻을 수 있습니다. 아래와 같이 PDF 페이지 리소스를 순환하여 이미지를 찾아 로컬 디스크에 저장하는 것도 가능합니다.
C#에서 PDF 파일을 읽는 코드
using System; | |
using System.IO; | |
// Add reference to Aspose.PDF for .NET API | |
// Use following namespace to read PDF file | |
using Aspose.Pdf; | |
namespace ReadPDFFiles | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Set license before reading PDF file | |
Aspose.Pdf.License AsposePDFLicense = new Aspose.Pdf.License(); | |
AsposePDFLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
string inFile = @"c:\ReadPDFFileInCSharp.pdf"; | |
// Load an existing PDF file in Document object to read | |
Document pdf = new Document(inFile); | |
// 1. Read text from PDF file | |
// Initialize TextAbsorber Class to read Text from PDF file | |
Aspose.Pdf.Text.TextAbsorber textAbsorber = new Aspose.Pdf.Text.TextAbsorber(); | |
// Call Page.Accept() method to let TextAbsorber find text in PDF Pages | |
pdf.Pages.Accept(textAbsorber); | |
// Write the extracted text to Console output | |
Console.WriteLine(textAbsorber.Text); | |
// 2. Extract images from PDF file | |
int imageIndex = 1; | |
// Iterate through PDF pages | |
foreach (var pdfPage in pdf.Pages) | |
{ | |
// Check available images while reading the PDF | |
foreach (XImage image in pdfPage.Resources.Images) | |
{ | |
// Create file stream for found image | |
FileStream extractedImage = new FileStream(String.Format("Page{0}_Image{1}.jpg", pdfPage.Number, imageIndex), FileMode.Create); | |
// Save output image to the disk | |
image.Save(extractedImage, System.Drawing.Imaging.ImageFormat.Jpeg); | |
// Close stream | |
extractedImage.Close(); | |
imageIndex++; | |
} | |
// Reset image index | |
imageIndex = 1; | |
} | |
} | |
} | |
} |
이전 주제에서 C#에서 대용량 PDF 파일을 처리하는 방법에 대해 배웠습니다. 위의 정보와 코드 예제를 사용하면 텍스트와 이미지를 추출하기 위해 C#에서 PDF 파일을 열고 읽을 수 있습니다.