ASP.NET MVCはじめました~PDFを出力する
概要
TuesPechkinというライブラリを使ってPDFを出力するやり方について調べてみました。
環境
- Visual Studio Community 2015
- ASP.NET MVC5
- TuesPechkin 2.1.1
TuesPechkin?
Google翻訳してみたら「火器屋」って…物騒ですねぇ。以下、README.mdから。
TuesPechkin is a .NET Wrapper for the wkhtmltopdf library.
https://github.com/tuespetre/TuesPechkin
HTMLをPDFに変換してくれるwkhtmltopdfライブラリの.NETラッパーとあります。wkhtmltopdfというのが本体なんですね。
Azure Websites does not currently support the use of wkhtmltopdf.
https://github.com/tuespetre/TuesPechkin
試しにAzure App Serviceにデプロイしてみたけど現段階で動きませんでした。
You must have Visual C++ 2013 runtime installed to use these packages.
https://github.com/tuespetre/TuesPechkin
wkhtmltopdfがC++で書かれているからランタイムもないとダメなんすかね。
とりあえず、動かしてみましょう!
インストール
ライブラリのインストールはパッケージマネージャーコンソールより以下を実行。TuesPechkinライブラリも一緒にインストールされます。他にもTuesPechkin.Wkhtmltox.Win32とTuesPechkin.Wkhtmltox.Win64がそれぞれ用意されているので環境に合わせてって感じでしょうか。
PM> Install-Package TuesPechkin.Wkhtmltox.AnyCPU
実装
HTMLをPDFに変換してくれるってことは、出力したいイメージのViewを作成してあげればOKと理解したので、以前作ったToDoリストをPDF化してみます。ちょっと面倒なのはレイアウトページを使っているとヘッダーやフッターまで一緒に出力されてしまうので、Indexページをそのまま出力するんじゃなく、PDF出力用のIndexViewを用意しなきゃいけないとこですかね。
■/Controllers/ReportController.cs
public class ReportController : Controller { ... public ActionResult TodoReport() { var pdfData = CreatePDF("Todo", "Report", null); return File(pdfData, "application/pdf", "TodoReport.pdf"); } private byte[] CreatePDF(string actionName, string controllerName, object routeValues = null) { var helper = new UrlHelper(ControllerContext.RequestContext); var indexUrl = helper.Action(actionName, controllerName, routeValues, Request.Url.Scheme); return _service.Create(indexUrl); } }
■/Services/Report/ReportService.cs
public class ReportService : IReportService { ... public byte[] Create(string indexUrl) { var document = new HtmlToPdfDocument() { GlobalSettings = { ProduceOutline = true, DocumentTitle = "PDF Sample", PaperSize = PaperKind.A3, Margins = { All = 1.375, Unit = Unit.Centimeters } }, Objects = { new ObjectSettings() { PageUrl = indexUrl, }, } }; var converter = new StandardConverter( new PdfToolset( new WinAnyCPUEmbeddedDeployment( new TempFolderDeployment()))); var pdfData = converter.Convert(document); return pdfData; } }
実行結果
ToDoリストのIndexページの[Download PDF]リンクからPDFをダウンロードします。ただ、出力したいのはデータ部分のみ。ヘッダーもフッターも余計なリンクとかもいらないですね。
なので出力イメージのView(レイアウトページ使用なし)を用意しておきます。Viewなのでブラウザで見ることも可能。
※PDF出力の際に表示されるわけではありません。
ダウンロードリンクを押下すると、PDF出力処理が走って出力イメージのViewをPDFに変換してくれます。そして、Viewの通りに出力されました!BootStrapを使ってますが、問題なく理解してくれてますね!