웹페이지를 PDF로 다운 받아야 할 일이 있었다.
iTextSharp, EO.PDF, spire.net 등을 설치해서 테스트 해보았는데,
다운 받아야 할 페이지가 비동기로 검색하는 페이지가 있어 제대로 뜨지 않거나,
한글이 제대로 표기가 되지 않거나,
유료버전이라거나 하는 문제가 있었다.
하여 찾다보니
wkhtmltopdf 라는 사이트를 알게되었다. (GNU 라이센스)
여러 버전이 있던데, 우선 내 개발환경인 윈도우즈 버전으로 다운받아 설치하였고, 테스트는 잘 되었다.
wkhtmltox-0.12.2.4_msvc2013-win64.7z.001
wkhtmltox-0.12.2.4_msvc2013-win64.7z.002
아래와 같은 소스로 테스트 해볼 수 있다.
#define sync
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Control_PDF2 : PageBase
{
protected string sFilePath = string.Empty;
protected string fName = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string Url = Request.Form["txtURL"] ?? "";
if (!string.IsNullOrEmpty(Url))
{
string sRootPath = Server.MapPath("/");
sFilePath = sRootPath + "//pdf//";
//나중에 파일명 중복일어나면 다르게 변경하는 것 넣어야 합니다.
fName = string.Format("eDIS_{0}.pdf", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = sRootPath + @"wkhtmltopdf.exe";
processStartInfo.Arguments = string.Format(@"""{0}"" {1}{2}", Url, sFilePath, fName);
#if sync
Process p = Process.Start(processStartInfo);
//Wait for the window to finish loading.
// p.WaitForInputIdle(); //웹페이지에서는 필요없음
//Wait for the process to end.
p.WaitForExit();
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fName));
Response.WriteFile(sFilePath + fName);
Response.Flush();
Response.End();
#endif
#if async
Process p = new Process();
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(this.FileDown);
p.StartInfo = processStartInfo;
p.Start();
#endif
//자료가 1시간 이전 것은 모두 삭제합니다.
}
}
}
protected void FileDown(object sender, EventArgs e)
{
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fName));
Response.WriteFile(sFilePath + fName);
Response.Flush();
Response.End();
}
}