C#
[C#] PDF 읽기
Jcoder
2021. 2. 27. 17:20
위시켓을 보던 중 PDF 파일을 읽어 내어 표시하고 문자를 찾는 기능이 필요한 프로젝트가 있어 짧게나마 만들어 봄.
문자열 찾기는 [C#] 문자열에 특정 문자 개수 찾기 (tistory.com) 에서 확인하면 됨.
1. .NET 5
2. iTextSharp
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace ReadAndFindPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = @"C:\Users\SEONGHYEON\Desktop\201013_네이티브가 닷넷에게 닷넷이 네이티브에게.pdf";
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
textBox2.AppendText("파일 경로를 입력하세요.");
textBox1.Focus();
return;
}
if (!File.Exists(textBox1.Text))
{
textBox2.AppendText("파일이 존재하지 않습니다");
textBox1.Focus();
return;
}
var pdfile = new FileInfo(textBox1.Text);
if (string.Compare(".pdf", pdfile.Extension, true) != 0)
{
textBox2.AppendText("PDF 파일이 아닙니다.");
textBox1.Focus();
return;
}
// PDF 일기
using (PdfReader reader = new PdfReader(textBox1.Text))
for (int pageNo = 1; pageNo <= reader.NumberOfPages; pageNo++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string extractedText = PdfTextExtractor.GetTextFromPage(reader, pageNo, strategy);
byte[] utf8Bytes = Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(extractedText));
string pageText = Encoding.UTF8.GetString(utf8Bytes);
textBox2.AppendText(pageText);
}
}
}
}