[C#] PDF 파일 만들기

이 문서에서는 C# .NET 및 iText 라이브러리를 사용하여 PDF 문서를 생성하는 방법에 대해 설명합니다. iText 7을 사용하면 PDF 문서를 생성하고 수정하며 다양한 기능을 추가할 수 있습니다. 이를 통해 PDF 문서를 프로그래밍 방식으로 생성하거나 변경할 수 있으므로, 문서 자동화 및 데이터 보고서 생성 등 다양한 응용 프로그램에 활용됩니다. 개발자들은 iText7을 활용하여 PDF 문서를 만들고 관리하는데 유용하게 활용할 수 있습니다.

프로젝트 설정

1. 프로젝트 시작

예제 프로젝트로 하나 생성하도록 하겠습니다. 제가 사용할 이름은 iText7Sample , Console App 이며 .netframe work 4.6.1 구형버전이긴 하지만 이것으로 시작하도록 하겠습니다.
이렇게 새로운 C# 프로젝트를 만들고, iText7 라이브러리를 참조로 추가하세요.

[C#] PDF 파일 만들기
그림1. 프로젝트 셋팅

2. iText7 설치

iText7을 사용하기 위해 NuGet 패키지 관리자를 통해 쉽게 설치할 수 있습니다.
NuGet 패키지로 다음을 설치 합니다.

[C#] PDF 파일 만들기
[C#] PDF 파일 만들기
그림2. itext7, itext7.bouncy-castle-adapter Nuget 추가

2. iText7 으로 개발 시작하기

다음은 PDF 문서를 생성하는 데 유용한 클래스와 메서드입니다.

  • PdfWriter: 파일 이름을 전달하고 문서에 내용을 씁니다.
  • PdfDocument: PDF 문서의 메모리 내 표현입니다. 쓰기 모드에서 PDF 문서가 열립니다.
  • Document: 메모리 내 PdfDocument에서 문서를 만듭니다.
  • Paragraph: 일부 텍스트로 초기화된 단락을 만듭니다.
  • SetFont : 폰트를 설정합니다. 만약 한글을 사용한다면 반드시 한글 폰트를 설정해 주어야 합니다.
  • SetFontSize: 텍스트의 글꼴 크기를 설정합니다.
  • SetTextAlignment: 왼쪽, 오른쪽, 가운데 등과 같은 텍스트 맞춤을 설정합니다.

1. 제목 추가

PDF 문서에 머리글을 추가합니다. 머리글 내용은 문서의 중앙에 정렬되고 글꼴 크기를 20으로 설정했습니다. Paragraph 개체로 이를 만들 수 있습니다.
다음은 Paragraph 개체를 만들어 문서 개체에 추가하는 코드 조각입니다.
마지막으로 Close() 메서드를 호출하여 문서 개체를 닫아야 합니다.

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iText7Sample
{
  internal class Program
  {
    static void Main(string[] args)
    {
      string DEST_PATH = 
        AppDomain.CurrentDomain.BaseDirectory + "output.pdf";

      PdfWriter writer = new PdfWriter(DEST_PATH);
      PdfDocument pdf = new PdfDocument(writer);
      Document document = new Document(pdf);
      Paragraph header = new Paragraph("HEADER")
        .SetTextAlignment(TextAlignment.CENTER)
        .SetFontSize(20);

      document.Add(header);
      document.Close();
    }
  }
}
[C#] PDF 파일 만들기
그림3. 영문 제목 출력

2. 한글 폰트 추가

일단 폰트 파일을 c://windows/fonts 에서 프로젝트로 복사했습니다.
PdfFont 개체로 폰트를 만들고 이를 Paragraph 에 셋팅해 줍니다.
저는 폰트 파일을 프로젝트에 추가 하였습니다.

[C#] PDF 파일 만들기
그림4. 프로젝트에 폰트 추가
static void Main(string[] args)
{
  string DEST_PATH = 
        AppDomain.CurrentDomain.BaseDirectory + "output.pdf";
  string HG_FONT_PATH = 
        AppDomain.CurrentDomain.BaseDirectory + "malgun.ttf";

  FontProgram fontProgram = 
        FontProgramFactory.CreateFont(HG_FONT_PATH);
  PdfFont font = 
        PdfFontFactory.CreateFont(fontProgram);

  PdfWriter writer = new PdfWriter(DEST_PATH);
  PdfDocument pdf = new PdfDocument(writer);
  Document document = new Document(pdf);
  Paragraph header = new Paragraph("제 목")
    .SetTextAlignment(TextAlignment.CENTER)
    .SetFont(font)
    .SetFontSize(20);

  document.Add(header);
  document.Close();
}

출력은 다음과 같습니다.

[C#] PDF 파일 만들기
그림5. 한글 제목 출력

3. 소제목 만들기

텍스트 정렬 중심이 있는 소제목을 만들고 글꼴 크기를 15로 설정합니다. 소제목를 문서 개체에 추가합니다.

Paragraph subheader = new Paragraph("소 제 목")
   .SetTextAlignment(TextAlignment.CENTER)
   .SetFontSize(15);
document.Add(subheader);
[C#] PDF 파일 만들기
그림6. 한글 소제목 출력

4. 수평 구분선 추가

선 구분 기호를 사용하여 수평선을 추가합니다.

LineSeparator ls = new LineSeparator(new SolidLine());
document.Add(ls);
[C#] PDF 파일 만들기
그림7. 수평 구분선 출력

5. 이미지 추가

Image 인스턴스를 사용하여 PDF 문서에 Image를 추가합니다

Image img = new Image(ImageDataFactory
    .Create(IMAGE_PATH))
    .SetHorizontalAlignment(HorizontalAlignment.CENTER);
document.Add(img);
[C#] PDF 파일 만들기
그림8. 이미지 출력

6. 테이블 만들기

Table 인스턴스를 사용하여 PDF 문서에 Table을 추가합니다

Table table = new Table(2, false);
Cell cell11 = new Cell()
   .SetBackgroundColor(ColorConstants.GRAY)
   .SetTextAlignment(TextAlignment.CENTER)
   .SetFont(font)
   .Add(new Paragraph("학번"));
Cell cell12 = new Cell()
   .SetBackgroundColor(ColorConstants.GRAY)
   .SetTextAlignment(TextAlignment.CENTER)
   .SetFont(font)
   .Add(new Paragraph("이름"));

Cell cell21 = new Cell()
   .SetTextAlignment(TextAlignment.CENTER)
   .Add(new Paragraph("1"));
Cell cell22 = new Cell()
   .SetTextAlignment(TextAlignment.CENTER)
   .SetFont(font)
   .Add(new Paragraph("개똥이"));

Cell cell31 = new Cell()
   .SetTextAlignment(TextAlignment.CENTER)
   .Add(new Paragraph("2"));
Cell cell32 = new Cell()
   .SetTextAlignment(TextAlignment.CENTER)
   .SetFont(font)
   .Add(new Paragraph("영희"));


table.AddCell(cell11);
table.AddCell(cell12);
table.AddCell(cell21);
table.AddCell(cell22);
table.AddCell(cell31);
table.AddCell(cell32);
document.Add(table);
[C#] PDF 파일 만들기
그림9. 테이블 출력

7. 하이퍼링크 만들기

하이퍼링크를 만들어 문서에 추가합니다

Link link = new Link("click here",
	PdfAction.CreateURI("https://harostudio.co.kr"));
	Paragraph hyperLink = new Paragraph("Please ")
	.Add(link.SetBold().SetUnderline()
	.SetItalic().SetFontColor(ColorConstants.BLUE))
	.Add(" to go harostudio Blog");

document.Add(hyperLink);
[C#] PDF 파일 만들기
그림10. 링크 출력

8. 페이지 번호 추가

페이지의 오른쪽 위 모서리에 페이지 번호를 추가합니다.

int n = pdf.GetNumberOfPages();
for (int i = 1; i <= n; i++)
{
	document.ShowTextAligned(new Paragraph(String
	   .Format("page" + i + " of " + n)),
		559, 806, i, TextAlignment.RIGHT,
		VerticalAlignment.TOP, 0);
}
[C#] PDF 파일 만들기
그림11. 페이지 번호 출력

9. 배경이미지 추가

배경 이미지를 추가 할 수 있습니다.

string BACK_PATH = 
    AppDomain.CurrentDomain.BaseDirectory + "back.png";
PdfCanvas canvas = 
    new PdfCanvas(pdf.AddNewPage());
var pageSize = PageSize.A4.Clone();
canvas.AddImageFittedIntoRectangle(
    ImageDataFactory.Create(BACK_PATH), pageSize, false);
[C#] PDF 파일 만들기
그림12. 배경 이미지 출력

10. 전체 코드 블럭

using iText.IO.Font;
using iText.IO.Image;
using iText.Kernel.Colors;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Canvas.Draw;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace iText7Sample
{
  internal class Program
  {
    static void Main(string[] args)
    {
      string DEST_PATH = 
	    AppDomain.CurrentDomain.BaseDirectory
		+ "output.pdf";
      string HG_FONT_PATH = 
	    AppDomain.CurrentDomain.BaseDirectory
		+ "malgun.ttf";
      string IMAGE_PATH = 
	    AppDomain.CurrentDomain.BaseDirectory
		+ "HaroStudio.png";
      string BACK_PATH = 
	    AppDomain.CurrentDomain.BaseDirectory
		+ "back.png";


      Paragraph newline = new Paragraph(new Text("\n"));

      FontProgram fontProgram = 
	    FontProgramFactory.CreateFont(HG_FONT_PATH);
      PdfFont font = 
	    PdfFontFactory.CreateFont(fontProgram);

      PdfWriter writer = new PdfWriter(DEST_PATH);
      PdfDocument pdf = new PdfDocument(writer);
      Document document = new Document(pdf);

      PdfCanvas canvas = 
	    new PdfCanvas(pdf.AddNewPage());
      var pageSize = PageSize.A4.Clone();
      canvas.AddImageFittedIntoRectangle(
	    ImageDataFactory.Create(BACK_PATH),
		pageSize,
		false);

      Paragraph header = new Paragraph("제 목")
         .SetTextAlignment(TextAlignment.CENTER)
         .SetFont(font)
         .SetFontSize(20);

      document.Add(header);

      document.Add(newline);

      Paragraph subheader = new Paragraph("소 제 목")
         .SetTextAlignment(TextAlignment.CENTER)
         .SetFont(font)
         .SetFontSize(15);
      document.Add(subheader);


      document.Add(newline);
      LineSeparator ls = 
	    new LineSeparator(new SolidLine());
      document.Add(ls);

      document.Add(newline);
      //이미지 추가
      Image img = new Image(ImageDataFactory
        .Create(IMAGE_PATH))
        .SetHorizontalAlignment(
		  HorizontalAlignment.CENTER);
      document.Add(img);

      document.Add(newline);
      //테이블 만들기
      Table table = new Table(2, false);
      Cell cell11 = new Cell()
         .SetBackgroundColor(ColorConstants.GRAY)
         .SetTextAlignment(TextAlignment.CENTER)
         .SetFont(font)
         .Add(new Paragraph("학번"));
      Cell cell12 = new Cell()
         .SetBackgroundColor(ColorConstants.GRAY)
         .SetTextAlignment(TextAlignment.CENTER)
         .SetFont(font)
         .Add(new Paragraph("이름"));

      Cell cell21 = new Cell()
         .SetTextAlignment(TextAlignment.CENTER)
         .Add(new Paragraph("1"));
      Cell cell22 = new Cell()
         .SetTextAlignment(TextAlignment.CENTER)
         .SetFont(font)
         .Add(new Paragraph("개똥이"));

      Cell cell31 = new Cell()
         .SetTextAlignment(TextAlignment.CENTER)
         .Add(new Paragraph("2"));
      Cell cell32 = new Cell()
         .SetTextAlignment(TextAlignment.CENTER)
         .SetFont(font)
         .Add(new Paragraph("영희"));


      table.AddCell(cell11);
      table.AddCell(cell12);
      table.AddCell(cell21);
      table.AddCell(cell22);
      table.AddCell(cell31);
      table.AddCell(cell32);
      document.Add(table);

      document.Add(newline);
      //하이퍼링크 만들기

      Link link = new Link("click here",
        PdfAction.CreateURI("https://harostudio.co.kr"));
        Paragraph hyperLink = new Paragraph("Please ")
        .Add(link.SetBold().SetUnderline()
        .SetItalic().SetFontColor(ColorConstants.BLUE))
        .Add(" to go harostudio Blog");

      document.Add(hyperLink);

      //페이지 번호 추가

      int n = pdf.GetNumberOfPages();
      for (int i = 1; i <= n; i++)
      {
        document.ShowTextAligned(
		  new Paragraph(
		    String.Format("page" + i + " of " + n)),
          559, 806, i, TextAlignment.RIGHT,
          VerticalAlignment.TOP, 0);
      }

      document.Close();
    }
  }
}

결론

C# iText 7을 사용하여 PDF 문서를 만드는 방법을 알아보았습니다. 이것은 정보를 효과적으로 공유하고 저장하는 강력한 도구입니다. C# 개발자로서 PDF 문서 생성 능력을 향상시키면 프로젝트에서 더 다양한 기능을 구현할 수 있을 것입니다.

Leave a Comment