본문 바로가기
C#/기타 유용한 클래스

이미지를 포함하는 PDF 파일 생성하기

by edupicker(체르니) 2012. 5. 1.

PDF 파일을 생성하는 방법은 여러 가지가 있습니다. 오늘은 Bruno Lowagie 씨가 만든 Java 기반의 iText를 닷넷 기반으로 포딩한 iTextSharp을 이용하여 C#으로 이미지가 포함된 PDF 파일을 생성하는지 알아봅니다.

이 내용은 서울 성공회대학교 소프트웨어공학과 학생들을 대상으로 강의하고 있는 과목의 과제의 일부임을 밣히며 열심히 공부하고 있는 학생들에게 온라인 지면을 빌어 고마움을 전합니다.

전체적인 PDF 파일 생성과정은 다음의 링크를 참고하시기 바랍니다.

http://fromyou.tistory.com/371


ASP.NET 웹 응용 프로그램 프로젝트를 생성하고 간단히 Button 컨트롤을 하나 올려놓습니다. 그 다음 솔루션 탐색기에 itextSharp.dll 파일을 참조 추가하고 PDF 파일에 포함할 이미지를 다음과 같이 프로젝트에 포함시킵니다.


이제 Default.aspx 파일의 디자인 화면에 올려진 Button 컨트롤을 클릭하여 참조된 itextSharp 관련 네임 스페이스들과 PDF 파일을 생성할 것이므로 System.IO 네임 스페이스를  추가합니다.

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;


Button 컨트롤 클릭시 실행될 코드와 호출되는 사용자 정의 함수

protected void btnCreatePDF_Click(object sender, EventArgs e)
{
            string strPath = Server.MapPath("Images");
            Document mydoc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(mydoc, new FileStream(strPath +
                 "/homework.pdf",
FileMode.Create, FileAccess.Write));
            mydoc.Open();

            PdfPTable table = new PdfPTable(5);

            insertData(table, "아바타", "제임스 카메론", "어드벤쳐", "2009-12-17", strPath + "/avatar.jpg");
            insertData(table, "건축학개론", "이용주", "로맨틱", "2012-03-22", strPath + "/gunchook.jpg");
            insertData(table, "타이탄의 분노", "조나단 리브스만", "액션", "2012-03-29",
                 strPath + "/WrathofTitans.jpg");

            mydoc.Add(table);
            mydoc.Close();

}



private void insertData(PdfPTable inTable, string strTile, string strDirector, string strKind,
                                   string strDate, string strImage)

{
            PdfPCell cell1 = new PdfPCell(new Phrase(strTile, SetCustomFont(strTile)));
            inTable.AddCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Phrase(strDirector, SetCustomFont(strDirector)));
            inTable.AddCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Phrase(strKind, SetCustomFont(strKind)));
            inTable.AddCell(cell3);

            PdfPCell cell4 = new PdfPCell(new Phrase(strDate, SetCustomFont(strDate)));
            inTable.AddCell(cell4);

            iTextSharp.text.Image insertedImage = iTextSharp.text.Image.GetInstance(strImage);
            PdfPCell cellPoster = new PdfPCell(insertedImage);
            inTable.AddCell(cellPoster);
}

한글 출력을 위한 함수
private iTextSharp.text.Font SetCustomFont(string inFont)
{
           string BatangFont = Environment.GetFolderPath(Environment.SpecialFolder.System) +
               @"\..\Fonts\batang.ttc";
            iTextSharp.text.Font returnFont;
            FontFactory.Register(BatangFont);
            returnFont = FontFactory.GetFont("바탕체", BaseFont.IDENTITY_H, 10);
            return returnFont;
 }


영화제목, 개봉일 같은 한 쌍의 형태의 데이터를 클래스로 만들어 List<정의한 클래스> 형태로 만들어 사용할 수도 있으며 이에 대한 업그레이드는 여러분들에게 맡깁니다.
제 코드가 이 글을 보는 분들에게 조금이나마 도움이 되길 바라며 즐거운 프로그래밍 하시길 바랍니다.