Azure FunctionsとDioDocsでExcelやPDFファイルを出力する(2)

前回に引き続き、本記事でもAzure Functionsで「DioDocs(ディオドック)」を使用したC#( .NET Core 3.1)のクラスライブラリをベースにした関数を作成し、ExcelやPDFファイルを出力する方法について紹介します。

Azure Functionsとは

Azure FunctionsはMicrosoft Azureで提供されている、各種イベントをトリガーに処理を実行するサーバーレスなアプリケーションを作成できるクラウドサービスです。

今回はVisual Studio 2019でAzure Functionsアプリケーションを作成し、Azureへデプロイして確認してみます。

実装する内容

実装する内容は今回も非常にシンプルです。Azure FunctionsアプリケーションでHTTPトリガーを使用する関数を作成します。関数の実行時にDioDocsを使用してExcelとPDFファイルを作成し、クエリパラメータで受け取った文字列を追加します。前回は作成したExcelとPDFファイルをFileContentResultで直接ローカルへ出力していましたが、今回は作成したExcelとPDFファイルをAzure Blob Storageへ出力します。

アプリケーションを作成

以下のドキュメントを参考にAzure Functionsアプリケーションを作成していきます。

クイック スタート:Visual Studio を使用して Azure で初めての関数を作成する

Visual Studio 2019でプロジェクトテンプレート「Azure Functions」を選択して[次へ]をクリックします。

Azure Functionsのプロジェクトテンプレート

プロジェクト名DioDocsFileIOFunctionAppを入力して[作成]をクリックします。

Azure Functionsのプロジェクトテンプレート

Azure Functionsで作成する関数のテンプレートを選択します。Http Triggerを選択して[作成]をクリックします。

Azure Functionsのプロジェクトテンプレート

DioDocsFileIOFunctionAppプロジェクトが作成されます。

Azure Functionsのプロジェクトテンプレート

NuGetパッケージの追加

Visual Studioの「NuGet パッケージ マネージャー」からDioDocsのパッケージGrapeCity.DioDocs.Excel.jaGrapeCity.DioDocs.Pdf.jaをインストールします。

NuGetパッケージの追加(DioDocs)

また、作成したExcelとPDFファイルをAzure Blob Storageへ出力するために、出力バインドでAzure Blob Storageを使用するので、必要なパッケージMicrosoft.Azure.WebJobs.Extensions.Storageをインストールします。

NuGetパッケージの追加(Azure Blob Storage)

Azure Blob Storageを使うコードを追加

Azure Blob Storageの出力バインドを設定するコードを追加してFunction1を以下のように更新します。

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        [Blob("output/result.xlsx", FileAccess.Write)] Stream outputfile,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}

追加した6行目のコードですが、出力バインドの属性コンストラクタ[Blob("output/result.xlsx", FileAccess.Write)]では、出力先となるAzure Blob Storageのコンテナとファイル名output/result.xlsxと、Azure Blob Storageへの書き込みアクセスFileAccess.Writeを設定しています。

DioDocs for Excelを使うコードを追加

DioDocsでExcelファイルを作成するコードを追加してFunction1を以下のように更新します。

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        [Blob("output/result.xlsx", FileAccess.Write)] Stream outputfile,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string Message = string.IsNullOrEmpty(name)
            ? "Hello, World!!"
            : $"Hello, {name}!!";

        Workbook workbook = new Workbook();

        workbook.Worksheets[0].Range["B2"].Value = Message;

        workbook.Save(outputfile);

        return new OkObjectResult("Finished.");
    }
}

DioDocs for PDFを使う関数を追加

ソリューションエクスプローラーからDioDocsFileIOFunctionAppプロジェクトを右クリックして[追加]-[新しい Azure 関数]を選択して、DioDocsでPDFファイルを作成する関数Function2を追加します。

新しいAzure Functionsの関数を追加
新しいAzure Functionsの関数を追加

関数のテンプレートを選択します。Http Triggerを選択して[追加]をクリックします。

新しいAzure Functionsの関数を追加

Azure Blob Storageを使うコードを追加

Azure Blob Storageの出力バインドを設定するコードを追加してFunction2を以下のように更新します。

public static class Function2
{
    [FunctionName("Function2")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        [Blob("output/result.pdf", FileAccess.Write)] Stream outputfile,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}

先程と同じように、追加した6行目のコードでは出力バインドの属性コンストラクタ[Blob("output/result.pdf", FileAccess.Write)]では、出力先となるAzure Blob Storageのコンテナとファイル名output/result.pdfと、Azure Blob Storageへの書き込みアクセスFileAccess.Writeを設定しています。

DioDocs for PDFを使うコードを追加

DioDocsでPDFファイルを作成するコードを追加してFunction2を以下のように更新します。

public static class Function2
{
    [FunctionName("Function2")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        [Blob("output/result.pdf", FileAccess.Write)] Stream outputfile,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string Message = string.IsNullOrEmpty(name)
            ? "Hello, World!!"
            : $"Hello, {name}!!";

        GcPdfDocument doc = new GcPdfDocument();
        GcPdfGraphics g = doc.NewPage().Graphics;

        g.DrawString(Message,
            new TextFormat() { Font = StandardFonts.Helvetica, FontSize = 12 },
            new PointF(72, 72));

        doc.Save(outputfile, false);

        return new OkObjectResult("Finished.");
    }
}

デバッグ実行で確認

今回はAzure Functionアプリケーションの関数で作成するExcelとPDFファイルの出力先として、関数の出力バインドで設定しているAzure Blob Storageを使用しています。ローカルでの確認にはAzure Storage Emulatorを使用します。Visual StudioでCloud Explorerを表示して[Blob Containers]を右クリックして表示されるメニューから[BLOB コンテナーの作成]を選択します。

デバッグ実行で確認(Azure Storage Emulator)

outputというコンテナを作成します。

デバッグ実行で確認(Azure Storage Emulator)

作成したAzure Functionsアプリケーションをローカルでデバッグ実行して確認します。Visual Studioからデバッグ実行すると以下のコンソールが表示されます。

デバッグ実行で確認

アプリケーションに含まれる関数のURLはhttp://localhost:7071/api/Function1http://localhost:7071/api/Function2となっています。このURLにクエリパラメータと文字列?name=DioDocsを追加して、それぞれの関数をブラウザで実行します。

デバッグ実行で確認
デバッグ実行で確認

Azure Storage Emulatorのコンテナーoutputに保存されたResult.xlsxResult.pdfを確認します。クエリパラメータで渡した文字列DioDocsが表示されていれば成功です。

デバッグ実行で確認(Azure Storage Emulator)
デバッグ実行で確認
デバッグ実行で確認

Azureへデプロイ

作成したAzure FunctionsアプリケーションをAzureへデプロイして確認します。ソリューションエクスプローラーからDioDocsFileIOFunctionAppプロジェクトを右クリックして[発行]を選択します。

デプロイして確認

公開するターゲットは「Azure」を選択します。特定のターゲットは「Azure Function App (Windows)」を選択します。

デプロイして確認
デプロイして確認

アプリケーションの名前やリソースグループ、使用するAzure Storageなどを設定して[作成]をクリックします。

デプロイして確認

以下の画面に切り替わったら[完了]をクリックします。

デプロイして確認

これで公開の準備が完了しました。Visual Studioで[発行]をクリックして作成したAzure FunctionアプリケーションをAzureへデプロイします。

デプロイして確認

公開が完了するとメッセージが表示されます。

デプロイして確認

デプロイしたアプリケーションを確認

Azure Functionsアプリケーションを実行する前に、ローカルでの確認と同じく関数の出力バインドで設定しているAzure Blob Storageのコンテナーoutputを作成しておきます。

デプロイしたAzure Functionsの関数を確認する

Visual StudioのCloud ExplorerからデプロイしたAzure Functionsアプリケーションを選択して「ポータルで開く」をクリックします。Azureポータルでデプロイしたアプリケーションが表示されます。

デプロイしたAzure Functionsの関数を確認する

Azureポータルで「関数」を選択するとAzure Functionsアプリケーションに含まれる関数Function1Function2が表示されます。

デプロイしたAzure Functionsの関数を確認する

関数Function1をクリックして「コードとテスト」を選択します。「関数の URL を取得」が表示されるのでこちらをクリックします。

デプロイしたAzure Functionsの関数を確認する

ポップアップで表示される「クリップボードにコピー」をクリックして関数のURLをコピーします。

デプロイしたAzure Functionsの関数を確認する

コピーしたURLをブラウザに張り付けて、さらにクエリパラメータと文字列&name=DioDocsを追加します。

デプロイしたAzure Functionsの関数を確認する

関数を実行するとデバッグ実行時と同じように、クエリパラメータで渡した文字列が追加されたExcelファイルがAzure Blob Storageのコンテナoutputに出力されます。関数Function2も同じ手順で確認できます。

デプロイしたAzure Functionsの関数を確認する

さいごに

動作を確認できるAzure Functionsアプリケーションのサンプルはこちらです。

https://github.com/GrapeCityJP/DioDocsFileIOFunctionApp

Azure FunctionsでDioDocsを利用する際に、日本語フォントを使用するTipsについては次回の記事で紹介しています。


弊社Webサイトでは、製品の機能を気軽に試せるデモアプリケーションやトライアル版も公開していますので、こちらもご確認いただければと思います。

また、ご導入前の製品に関するご相談やご導入後の各種サービスに関するご質問など、お気軽にお問合せください。

\  この記事をシェアする  /