이전에 포스팅 한 글에서 C# 프로그램으로 PDF 문서에 워터마크(Watermark)를 삽입하거나 여러 개의 PDF 파일을 하나의 PDF 파일로 합치는 방법에 대해 설명한 적이 있습니다.
이번에 소개할 내용은 ASP.NET C#에서 HTML 문서를 PDF 파일로 변환 하는 방법에 대한 설명입니다.
HTML 문서를 PDF 문서로 변환한다는 것은 웹 페이지를 PDF로 변환한다는 의미와 동일합니다.
C# 프로그램을 통해 특정 웹 페이지를 PDF로 변환해서 저장하는 방법에 대해서 알아보겠습니다.

C#에서 HTML 문서를 PDF 파일로 변환 하는 방법
C#에서 HTML 문서를 PDF 문서로 쉽게 변환하기 위해 iTextSharp 라이브러리 참조가 필요합니다.
iTextSharp는 AGPL라이센스이며, 인터넷에서 쉽게 구할 수 있습니다.
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void Button1_Click(object sender, System.EventArgs e) { String htmlText = “<font “ + ” color=\”#0000FF\”><b><i>Title One</i></b></font><font “ + ” color=\”black\”><br><br>Some text here<br><br><br><font “ + ” color=\”#0000FF\”><b><i>Another title here “ + ” </i></b></font><font “ + ” color=\”black\”><br><br>Text1<br>Text2<br><OL><LI><DIV Style=’color:green’>Pham Duy Hoa</DIV></LI><LI>how are u</LI></OL><br/>” + “<table border=’1′><tr><td style=’color:red;text-align:right;width:20%’>123456</td><td style=’color:green;width:60%’>78910</td><td style=’color:red;width:20%’>ASFAFA</td></tr>” + “<tr><td style=’color:red;text-align:right’>123456</td><td style=’color:green;width:60%’>78910</td><td style=’color:red;width:20%’>DAFSDGAFW</td></tr></table><br/>”+ “<div><ol><li>123456</li><li>123456</li><li>123456</li><li>123456</li></ol></div>”; HTMLToPdf(htmlText, “PDFfile.pdf”); } public void HTMLToPdf(string sHTML, string sFilePath) { Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + “\\” + sFilePath, FileMode.Create)); document.Open(); Image pdfImage = Image.GetInstance(Server.MapPath(“logo.png”)); //로고 이미지를 추가할 경우 pdfImage.ScaleToFit(100, 50); pdfImage.Alignment = iTextSharp.text.Image.UNDERLYING; pdfImage.SetAbsolutePosition(180, 760); document.Add(pdfImage); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(sHTML)); document.Close(); ShowPdf(sFilePath); //생성된 PDF 파일 열기 } private void ShowPdf(string sFile) { Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader(“Content-Disposition”, “inline;filename=” + sFile); Response.ContentType = “application/pdf”; Response.WriteFile(sFile); Response.Flush(); Response.Clear(); } } |
결론적으로 C# 프로그램에서 비교적 쉽고 간단하게 HTML을 PDF로 변환해서 저장하는 로직을 구현할 수 있습니다.
특정 사이트의 웹 페이지를 PDF로 저장해야 할 경우 참고하시면 쉽게 구현이 가능합니다.
※ 함께 읽으면 도움이 될 만한 다른 포스팅 글입니다.
이 글이 도움이 되었기를 바랍니다. ^-^