C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )

C# 으로 HTML 을 PDF 로 만드는 강력한 라이브러리인 pdfHTML 이라는 라이브러리를 소개합니다.
이는 HTML 파일을 PDF 로 변환하며 CSS 까지 적용 가능합니다.
여타 다른 라이브러리 또는 이전 버전에서는 웹브라우저에 비해 조금 부족한 감이 있었습니다.
그렇지만 iText7+pdfHTML 은 거의 웹브라우저와 비슷하게 표현해 주고 있습니다.

이전 포스팅에서 필자는 “iText7 을 사용하여 PDF 파일 만들기” 라는 포스팅을 하였습니댜.

[C#] iText 7을 사용하여 PDF 파일 만들기 – 하로스튜디오 (harostudio.co.kr)

이는 수동으로 화면에 일일히 표현해야 하지만 이번 포스팅 라이브러리인 pdfHTML 은 HTML 으로 작성된 문서를 그대로 PDF로 변환하는 라이브러리입니다.

프로젝트 설정

1. 프로젝트 시작

이전과 같이 예제 프로젝트를 하나 생성합니다.
제가 사용할 이름은 pdfHTMLSample , Console App 이며 .netframe work 4.6.1 구형버전이긴 하지만 이것으로 시작하도록 하겠습니다.
이렇게 새로운 C# 프로젝트를 만들고 Nuget 패키지 관리 창에서 다음을 설치합니다.

C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림1. 프로젝트 설정

2. iText7 설치

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

C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림2. itext.pdfhtml, itext.bouncy-castle-adapter 설치

iText.pdfHTML 으로 개발 시작하기

1. Hello HTML to PDF

다음 예제는 아주 간다한 한줄짜리 예제를 보여줍니다.

static void Main(string[] args)
{
  string HTML = "<h1>Test</h1><p>Hello World</p>";
  string DEST = "output.pdf";
  HtmlConverter.ConvertToPdf(
    HTML, new FileStream(DEST, FileMode.Create));
}

아래는 출력한 PDF 파일입니다. GOOD 좋습니다.

C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림3. Hello World

2. 외부 CSS 및 이미지 표현하기

위 예제는 CSS 가 적용되지 않았습니다.
이제 외부 HTML 파일과 CSS 파일을 적용해 보도록 하겠습니다.

읽을 파일은 다음과 같습니다.
index.html

<!DOCTYPE html>
<html>

<head>
  <title>HTML to PDF</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <h1>HTML to PDF</h1>
  <p>
    <span class="itext">iText</span>
    <span class="description"> converting HTML to PDF</span>
  </p>
  <table>
    <tr>
      <th class="label">Title</th>
      <td>iText - C# HTML to PDF</td>
    </tr>
    <tr>
      <th>URL</th>
      <td>https://harostudio.co.kr</td>
    </tr>
  </table>
  <div class="center">
    <h2>Here is an image</h2>
    <div>
      <img src="HaroStudio.png" />
    </div>
    <div>
      <img src="https://www.w3schools.com/images/picture.jpg"
        alt="Mountain" />
    </div>
  </div>
</body>
</html>

style.css

h1 {
    color: #fc3d03;
}

table tr td {
    text-align: center;
    border: 1px solid gray;
    padding: 4px;
}

table tr th {
    background-color: #84C7FD;
    color: #fff;
    width: 100px;
}

.itext {
    color: #84C7FD;
    font-weight: bold;
}

.description {
    color: gray;
}

.center {
    text-align: center;
}

이번 역시 소스코드가 굉장히 단순합니다.

static void Main(string[] args)
{
  string HTML = "index.html";
  string DEST = "output.pdf";
  HtmlConverter.ConvertToPdf(
    new FileStream(HTML, FileMode.Open),
    new FileStream(DEST, FileMode.Create));
}
C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림4. 외부 HTML, CSS

출력물은 예상밖으로 좋습니다.

3. 한글 폰트 사용하기

index.html 을 다음처럼 한글을 약간 넣겠습니다.

<!DOCTYPE html>
<html>

<head>
  <title>HTML to PDF</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <h1>HTML 을 한글로 변환 - pdfHTML </h1>
  <p>
    <span class="itext">iText</span>
    <span class="description"> converting HTML to PDF</span>
  </p>
  <table>
    <tr>
      <th class="label">Title</th>
      <td>iText - C# HTML to PDF</td>
    </tr>
    <tr>
      <th>URL</th>
      <td>https://harostudio.co.kr</td>
    </tr>
  </table>
  <div class="center">
    <h2>Here is an image</h2>
    <div>
      <img src="HaroStudio.png" />
    </div>
    <div>
      <img src="https://www.w3schools.com/images/picture.jpg" 
	    alt="Mountain" />
    </div>
  </div>
</body>
</html>

C# 코드를 그대로 했을경우 다음처럼 한글이 표현되지 않음을 알 수 있습니다.

C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림5. 한글 표현 못함

이제 한글 표현을 위해서 코드를 약간 추가 하겠습니다.
폰트가 필요합니다. malgun.ttf 라는 폰트를 C:\\Windows\\Fonts 에서 복사하여 출력폴더에 넣고 실행합니다.

static void Main(string[] args)
{
  string HTML = "index.html";
  string DEST = "output.pdf";
  string FONT = "malgun.ttf";

  ConverterProperties properties = 
    new ConverterProperties();
  FontProvider fontProvider = 
    new DefaultFontProvider(false, false, false);
  FontProgram fontProgram = 
    FontProgramFactory.CreateFont(FONT);
  fontProvider.AddFont(fontProgram);
  properties.SetFontProvider(fontProvider);
  HtmlConverter.ConvertToPdf(
    new FileStream(HTML, FileMode.Open), 
    new FileStream(DEST, FileMode.Create), properties);
}
C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림6. 한글 표현

어떤가요? 몇줄 안되는 코드로 한글도 완벽하게 표현되었지요?

4.전체소스

using iText.Html2pdf.Resolver.Font;
using iText.Html2pdf;
using iText.IO.Font;
using iText.Layout.Font;
using System.IO;

namespace pdfHTMLSample
{
  internal class Program
  {
    static void Main(string[] args)
    {
      string HTML = "index.html";
      string DEST = "output.pdf";
      string FONT = "malgun.ttf";

      ConverterProperties properties = 
	    new ConverterProperties();
      FontProvider fontProvider = 
	    new DefaultFontProvider(false, false, false);
      FontProgram fontProgram = 
	    FontProgramFactory.CreateFont(FONT);
      fontProvider.AddFont(fontProgram);
      properties.SetFontProvider(fontProvider);
      HtmlConverter.ConvertToPdf(
	    new FileStream(HTML, FileMode.Open),
		new FileStream(DEST, FileMode.Create),
		properties);
    }
  }
}

이제 브라우저에서 보는것과 어떻게 다른지 보겠습니다.

C# HTML 파일을 PDF 로 만드는 강력한 방법. ( iText7 , pdfHTML )
그림7. 브라우저와 비교

왼쪽이 PDF, 오른쪽이 브라우저입니다.
브라우저에서 보는것과 거의 흡사합니다.

결론

C# iText pdfHTML은 HTML 콘텐츠를 PDF 문서로 변환하는, HTML 디자인 차원에서 문서 변환을 간편하게 할 수 있는 다재다능한 도구입니다.
이 기능은 보고서 프로그램, 송장 출력 프로그램 등 다양한 프로그램에서 활용될 것으로 보입니다.

Leave a Comment