C#을 사용하여 Word 파일을 PDF로 변환하는 방법
Word 문서를 생성, 편집 및 관리하는 것은 많은 응용 프로그램에서 자주 요구됩니다. C#에서 Word 문서를 생성하고 편집하는 여러 가지 방법이 있지만, 가장 강력한 방법 중 하나는 Microsoft Interop 서비스를 사용하는 것입니다. 이 도구를 사용하면 Word 문서를 프로그래밍 방식으로 쉽게 다룰 수 있습니다.
Word 및 DOCX 문서 편집
- Word 및 DOCX 문서를 편집하려면 C# 라이브러리를 다운로드하세요.
- 코드로 빈 Word 문서를 생성합니다.
- 워드 문서에 새로운 텍스트 추가
- 새 문서 또는 기존 문서의 텍스트를 편집합니다.
- 원하는 위치에 DOCX 파일 내보내기
필수 조건
환경 설정 및 코드를 시작하기 전에, 다음 전제 조건을 충족하는지 확인하세요:
- Visual Studio: 컴퓨터에 Visual Studio가 설치되어 있는지 확인하세요. 설치되어 있지 않다면, Microsoft 공식 웹사이트에서 다운로드 및 설치하세요.
- Microsoft Word: Microsoft Interop를 사용하고 있으므로 컴퓨터에 MS Word가 설치되어 있어야 합니다. Interop 서비스는 컴퓨터에 설치된 Microsoft Word 응용 프로그램과 인터페이스를 구성합니다.
- 기본 C# 지식: 기본적인 C# 개념을 이해하는 것이 중요합니다.
- .NET Framework: 응용 프로그램이 이를 기반으로 할 것이므로 Visual Studio가 .NET Framework를 지원하는지 확인하세요.
환경 설정
Visual Studio 응용 프로그램을 열고 시작합니다. 열리면 환영 화면이 표시됩니다.
1. 새 .NET Framework 콘솔 응용 프로그램 생성
- "새 프로젝트 생성"을 클릭합니다.
- 검색 상자에 "콘솔 앱 (.NET Framework)"를 입력합니다.
- 결과에서 "콘솔 앱 (.NET Framework)"를 선택하고 "다음" 버튼을 클릭합니다.
- 프로젝트의 이름을 설정한 다음 "생성" 버튼을 클릭합니다.
이 단계들을 수행하면 Visual Studio가 새 .NET Framework 콘솔 애플리케이션을 생성합니다. In the Program.cs 파일에서, 콘솔 애플리케이션의 진입점이 되는 Main 메서드가 포함된 기본 템플릿을 찾을 수 있습니다.
2. NuGet 패키지 관리자를 사용하여 Microsoft.Office.Interop.Word 설치하기
NuGet은 .NET의 패키지 관리자이며 Visual Studio에 통합되어 있습니다. 다음은 Microsoft.Office.Interop.Word 패키지를 설치하는 방법입니다:
- Visual Studio에서 "도구" 메뉴로 이동하세요.
- "NuGet 패키지 관리자"를 선택한 다음 "해결책용 NuGet 패키지 관리..."를 선택합니다.
- NuGet 창에서 "찾아보기" 탭을 클릭합니다.
- 검색 상자에
Microsoft.Office.Interop.Word을 입력하고 엔터를 누르십시오. - 검색 결과에서
Microsoft.Office.Interop.Word패키지를 선택하십시오. - 오른쪽에서 콘솔 응용 프로그램 프로젝트가 선택되었는지 확인한 후 "설치" 버튼을 클릭합니다.

Visual Studio가 이제 패키지를 설치하고 프로젝트에 참조를 추가할 것입니다. 이 패키지는 C# 응용 프로그램에서 MS Word와 상호작용하기 위한 필요한 어셈블리 및 도구를 포함합니다.
IronWord 소개: Interop을 대체하는 우수한 대안
Interop은 Word 및 Excel 작업에 대한 강력한 기능을 제공하지만 한계가 있습니다. IronWord를 시작하세요: .NET 개발자를 위해 최적화된 다재다능한 라이브러리입니다. IronWord는 특히 Word 문서 편집 작업에서 Interop보다 더 원활한 경험을 제공합니다. IronWord는 호환성과 성능을 보장할 뿐만 아니라 직관적인 방법으로 복잡한 작업을 단순화합니다. 비교의 용이함을 위해 MS Word 이후 각 사용 사례에 대한 IronWord 코드 스니펫을 IronWord 버전 2024.1.2를 사용하여 제공합니다.
기존 Word 문서 열기
종종 기존 Word 문서를 편집해야 할 필요가 있으며, 다음 예제는 C#에서 이를 수행하는 방법을 보여줍니다:
// Create an instance of the Word Application
var WordApp = new Microsoft.Office.Interop.Word.Application();
// Open a Word document with the specified file path
var WordDoc = WordApp.Documents.Open(@"path_to_your_document.docx");' Create an instance of the Word Application
Dim WordApp = New Microsoft.Office.Interop.Word.Application()
' Open a Word document with the specified file path
Dim WordDoc = WordApp.Documents.Open("path_to_your_document.docx")위 코드에서, path_to_your_document.docx을 docx 파일 경로로 대체하십시오.
IronWord 사용하기
IronWord를 사용하여 Word 문서를 엽니다.
// Open a Word document with the specified file path using IronWord
WordDocument doc = new WordDocument(@"path_to_your_document.docx");' Open a Word document with the specified file path using IronWord
Dim doc As New WordDocument("path_to_your_document.docx")새로운 Word 문서 생성
처음부터 Word 문서를 생성하려면:
// Initialize a new instance of the Word Application
var WordApp = new Microsoft.Office.Interop.Word.Application();
// Add a new Word document
var WordDoc = WordApp.Documents.Add();' Initialize a new instance of the Word Application
Dim WordApp = New Microsoft.Office.Interop.Word.Application()
' Add a new Word document
Dim WordDoc = WordApp.Documents.Add()이 코드 스니펫은 C#을 사용하여 작성하고 편집할 수 있는 새로운 Word 문서를 생성합니다.
IronWord 사용하기
// Create a new, empty Word document using IronWord
WordDocument doc = new WordDocument();' Create a new, empty Word document using IronWord
Dim doc As New WordDocument()Word 문서에 텍스트 추가
새 텍스트 단락을 추가하려면:
// Add a new paragraph to the document
WordDoc.Paragraphs.Add();
// Assign text to the newly added paragraph
WordDoc.Paragraphs[1].Range.Text = "This is the first paragraph.";' Add a new paragraph to the document
WordDoc.Paragraphs.Add()
' Assign text to the newly added paragraph
WordDoc.Paragraphs(1).Range.Text = "This is the first paragraph."Paragraphs.Add() 메서드는 Word 문서에 새 단락을 추가하고 Range.Text 속성은 새 텍스트를 할당합니다.
IronWord 사용하기
// Add a new text to the document using IronWord
doc.AddText("Add text using IronWord");' Add a new text to the document using IronWord
doc.AddText("Add text using IronWord")기존 텍스트 편집하기
이번 튜토리얼에서는 **첫 번째 단락:**을 변경합시다.
// Edit the text of the first paragraph
WordDoc.Paragraphs[1].Range.Text = "This is the edited first paragraph.";' Edit the text of the first paragraph
WordDoc.Paragraphs(1).Range.Text = "This is the edited first paragraph."유사한 방법으로 Word 문서의 다른 요소를 추가하고 편집할 수도 있습니다.
IronWord 사용하기
// Edit the text of the first paragraph using IronWord
doc.Paragraphs[0].TextRuns[0].Text = "This is the edited first paragraph.";' Edit the text of the first paragraph using IronWord
doc.Paragraphs(0).TextRuns(0).Text = "This is the edited first paragraph."문서 저장 및 닫기
원하는 편집을 완료한 후:
// Save the document to a specified path
WordDoc.SaveAs(@"path_where_you_want_to_save.docx");
// Close the document and quit the application
WordDoc.Close();
WordApp.Quit();' Save the document to a specified path
WordDoc.SaveAs("path_where_you_want_to_save.docx")
' Close the document and quit the application
WordDoc.Close()
WordApp.Quit()path_where_you_want_to_save.docx을 원하는 경로로 교체하십시오.
IronWord 사용하기
// Save the document to the desired path using IronWord
doc.SaveAs(@"path_where_you_want_to_save.docx");' Save the document to the desired path using IronWord
doc.SaveAs("path_where_you_want_to_save.docx")전체 코드 및 예제
이제 모두 함께 조합해봅시다. 다음은 기존 Word 문서를 열고, 편집한 다음 변경사항을 저장하는 방법을 보여주는 전체 코드 예제입니다:
var WordApp = new Microsoft.Office.Interop.Word.Application();
// Create a new Word document
var WordDoc = WordApp.Documents.Add();
// Add new text
WordDoc.Paragraphs.Add();
WordDoc.Paragraphs[1].Range.Text = "This is the first paragraph.";
// Edit the first paragraph
WordDoc.Paragraphs[1].Range.Text = "This is the edited first paragraph.";
// Save and close
WordDoc.SaveAs(@"path_where_you_want_to_save.docx");
WordDoc.Close();
WordApp.Quit();Dim WordApp = New Microsoft.Office.Interop.Word.Application()
' Create a new Word document
Dim WordDoc = WordApp.Documents.Add()
' Add new text
WordDoc.Paragraphs.Add()
WordDoc.Paragraphs(1).Range.Text = "This is the first paragraph."
' Edit the first paragraph
WordDoc.Paragraphs(1).Range.Text = "This is the edited first paragraph."
' Save and close
WordDoc.SaveAs("path_where_you_want_to_save.docx")
WordDoc.Close()
WordApp.Quit()IronWord 사용하기
IronWord를 사용하는 전체 코드 예제는 간결합니다. IronWord는 간결한 코드 스니펫을 활용하여 DOCX 파일을 편집합니다.
// Create an empty Word document
WordDocument doc = new WordDocument();
// Add new text
doc.AddText("This is the first paragraph.");
// Edit the text
doc.Paragraphs[0].TextRuns[0].Text = "This is the edited first paragraph.";
// Export DOCX
doc.SaveAs(@"path_where_you_want_to_save.docx");' Create an empty Word document
Dim doc As New WordDocument()
' Add new text
doc.AddText("This is the first paragraph.")
' Edit the text
doc.Paragraphs(0).TextRuns(0).Text = "This is the edited first paragraph."
' Export DOCX
doc.SaveAs("path_where_you_want_to_save.docx")결론
.NET 애플리케이션 내에서 Word 및 Excel 문서를 조작하는 영역에서는 선택지가 풍부합니다. Microsoft의 Interop 서비스가 많은 사람들에게 기본 선택이었지만, IronWord 같은 솔루션의 등장은 더 효율적이고 사용자 친화적인 도구로의 이동을 의미합니다.

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.
관련 기사

