1.21 jigowatts

Great Scott!

ASP.NET MVCはじめました~PDFを出力する

概要

TuesPechkinというライブラリを使ってPDFを出力するやり方について調べてみました。

GitHub - tuespetre/TuesPechkin: A .NET wrapper for the wkhtmltopdf library with an object-oriented API.

f:id:sh_yoshida:20170330165500p:plain

環境

TuesPechkin?

Google翻訳してみたら「火器屋」って…物騒ですねぇ。以下、README.mdから。

TuesPechkin is a .NET Wrapper for the wkhtmltopdf library.

https://github.com/tuespetre/TuesPechkin

HTMLをPDFに変換してくれるwkhtmltopdfライブラリの.NETラッパーとあります。wkhtmltopdfというのが本体なんですね。

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をダウンロードします。ただ、出力したいのはデータ部分のみ。ヘッダーもフッターも余計なリンクとかもいらないですね。

f:id:sh_yoshida:20170330165446p:plain

なので出力イメージのView(レイアウトページ使用なし)を用意しておきます。Viewなのでブラウザで見ることも可能。
※PDF出力の際に表示されるわけではありません。

f:id:sh_yoshida:20170330165506p:plain

ダウンロードリンクを押下すると、PDF出力処理が走って出力イメージのViewをPDFに変換してくれます。そして、Viewの通りに出力されました!BootStrapを使ってますが、問題なく理解してくれてますね!

f:id:sh_yoshida:20170330165500p:plain

ソース

github.com