/WinRT - Windows.Data.Pdfを使ってみた


このサンプルでは、PDFを読み込んでページ数を出力します。

環境 Windows10 (Visual Studioいれてないとダメかも)

ソースコード

※await/asyncを使い慣れていないので、良い書き方かどうかは自信はないです。


using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using Windows.Data.Pdf;

namespace MyPdfTest
{
    public class MyPdf
    {
        public static async Task<uint> LoadPdfFile(string fileName)
        {
            Windows.Storage.StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(fileName);
            uint t = LoadPdfDocumentAsync(sampleFile).Result;
            return t;
        }

        static async Task<uint> LoadPdfDocumentAsync(Windows.Storage.StorageFile pdfFile)
        {
            PdfDocument _pdfDoc = await PdfDocument.LoadFromFileAsync(pdfFile);
            return _pdfDoc.PageCount;
        }

        [STAThread]
        static void Main(string[] args)
        {
            Task<uint> t = LoadPdfFile(@"C:\SvnLocal\trunk\Pdf_WinRT\PDF32000_2008.pdf");
            uint t2 = t.Result;
            Console.WriteLine(t2);
        }
    }
}

コンパイル用バッチファイル

compile.bat ソースファイル名.cs でコンパイル

compile.bat

csc /r:C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Runtime.WindowsRuntime\v4.0_4.0.0.0__b77a5c561934e089\system.runtime.windowsruntime.dll ^
/r:C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Runtime.InteropServices.WindowsRuntime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.InteropServices.WindowsRuntime.dll ^
/r:C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Runtime\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Runtime.dll ^
"/r:C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Annotated\Windows.winmd" %*

実行結果


C:\SvnLocal\trunk\Pdf_WinRT>PdfWinRT_Test.exe
756

以下はAdobe Reader DCで確認したページ数。

正しいページ数が得られている。

参考サイト

  1. https://www.atmarkit.co.jp/ait/articles/1310/24/news070.html
  2. https://docs.microsoft.com/en-us/uwp/api/windows.storage.storagefile.getfilefrompathasync

追記

参考サイト1によると、ページを画像として抽出するのには使えそうだが、テキストを抽出するのには使えなさそうである。ILSpyでメンバーとかみた感じ、その通りっぽい。

追記その2

続編:C#/WinRT - PDFを画像に変換して保存する