PDFをC#で異なる画像形式に変換

概要

この記事では、C#を使用してPDFを異なる画像形式に変換する方法を説明します。以下のトピックをカバーしています。

C# PDFを画像に変換

以下のコードスニペットは、Aspose.PDF.Drawingライブラリでも動作します。

Aspose.PDF for .NETは、PDFを画像に変換するためのいくつかのアプローチを使用します。一般的に、デバイスアプローチを使用した変換とSaveOptionを使用した変換の2つのアプローチを使用します。このセクションでは、これらのアプローチのいずれかを使用して、PDF文書をBMP、JPEG、GIF、PNG、EMF、TIFF、SVG形式の画像に変換する方法を示します。

ライブラリには、画像を変換するための仮想デバイスを使用できるいくつかのクラスがあります。DocumentDeviceは文書全体の変換に向いていますが、ImageDeviceは特定のページに向いています。

DocumentDeviceクラスを使用してPDFを変換

Aspose.PDF for .NETは、PDFページをTIFF画像に変換することを可能にします。

TiffDevice(DocumentDeviceに基づく)クラスは、PDFページをTIFF画像に変換することを可能にします。このクラスは、PDFファイル内のすべてのページを単一のTIFF画像に変換するためのProcessというメソッドを提供します。

PDFページを1つのTIFF画像に変換

Aspose.PDF for .NETは、PDFファイル内のすべてのページを単一のTIFF画像に変換する方法を説明します:

PDFをTIFFに変換

  1. Documentクラスのオブジェクトを作成します。
  2. TiffSettingsおよびTiffDeviceオブジェクトを作成します。
  3. **TiffDevice.Process()**メソッドを呼び出して、PDF文書をTIFFに変換します。
  4. 出力ファイルのプロパティを設定するには、TiffSettingsクラスを使用します。

以下のコードスニペットは、すべてのPDFページを単一のTIFF画像に変換する方法を示しています。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFtoTIFF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PDFtoTIFF.pdf"))
    {
        // Create Resolution object
        var resolution = new Aspose.Pdf.Devices.Resolution(300);

        // Create TiffSettings object
        var tiffSettings = new Aspose.Pdf.Devices.TiffSettings
        {
            Compression = Aspose.Pdf.Devices.CompressionType.None,
            Depth = Aspose.Pdf.Devices.ColorDepth.Default,
            Shape = Aspose.Pdf.Devices.ShapeType.Landscape,
            SkipBlankPages = false
        };

        // Create TIFF device
        var tiffDevice = new Aspose.Pdf.Devices.TiffDevice(resolution, tiffSettings);

        // Convert a particular page and save the image to stream
        tiffDevice.Process(document, dataDir + "PDFtoTIFF_out.tif");
    }
}

1ページをTIFF画像に変換

Aspose.PDF for .NETは、PDFファイル内の特定のページをTIFF画像に変換することを可能にします。変換のためにページ番号を引数として受け取るProcess(..)メソッドのオーバーロード版を使用します。以下のコードスニペットは、PDFの最初のページをTIFF形式に変換する方法を示しています。

  1. Documentクラスのオブジェクトを作成します。
  2. TiffSettingsおよびTiffDeviceオブジェクトを作成します。
  3. fromPageおよびtoPageパラメータを使用してオーバーロードされた**TiffDevice.Process()**メソッドを呼び出し、PDF文書のページをTIFFに変換します。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFtoTiffSinglePage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PDFtoTiffSinglePage.pdf"))
    {
        // Create Resolution object
        var resolution = new Aspose.Pdf.Devices.Resolution(300);

        // Create TiffSettings object
        var tiffSettings = new Aspose.Pdf.Devices.TiffSettings
        {
            Compression = Aspose.Pdf.Devices.CompressionType.None,
            Depth = Aspose.Pdf.Devices.ColorDepth.Default,
            Shape = Aspose.Pdf.Devices.ShapeType.Landscape,
        };

        // Create TIFF device
        var tiffDevice = new Aspose.Pdf.Devices.TiffDevice(resolution, tiffSettings);

        // Convert a particular page and save the image to stream
        tiffDevice.Process(document, 1, 1, dataDir + "PDFtoTiffSinglePage_out.tif");
    }
}

変換中にブラッドリーアルゴリズムを使用

Aspose.PDF for .NETは、LZW圧縮を使用してPDFをTIFに変換する機能をサポートしており、その後AForgeを使用して二値化を適用できます。ただし、顧客の1人が特定の画像について、Otsuを使用してしきい値を取得する必要があるため、ブラッドリーも使用したいとリクエストしました。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFtoTiffBradleyBinarization()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PDFtoTiffBradleyBinarization.pdf"))
    {
        string outputImageFile = dataDir + "PDFtoTiffBradleyBinarization_out.tif";
        string outputBinImageFile = dataDir + "PDFtoTiffBradleyBinarization-bin_out.tif";

        // Create Resolution object
        var resolution = new Aspose.Pdf.Devices.Resolution(300);

        // Create TiffSettings object
        var tiffSettings = new Aspose.Pdf.Devices.TiffSettings
        {
            Compression = Aspose.Pdf.Devices.CompressionType.LZW,
            Depth = Aspose.Pdf.Devices.ColorDepth.Format1bpp
        };

        // Create TIFF device
        var tiffDevice = new Aspose.Pdf.Devices.TiffDevice(resolution, tiffSettings);

        // Convert a particular page and save the image to stream
        tiffDevice.Process(document, outputImageFile);

        // Binarize the image using Bradley method
        using (var inStream = new FileStream(outputImageFile, FileMode.Open))
        {
            using (var outStream = new FileStream(outputBinImageFile, FileMode.Create))
            {
                tiffDevice.BinarizeBradley(inStream, outStream, 0.1);
            }
        }
    }
}

ImageDeviceクラスを使用してPDFを変換

ImageDeviceBmpDeviceJpegDeviceGifDevicePngDeviceEmfDeviceの祖先です。

  • BmpDeviceクラスは、PDFページをBMP画像に変換することを可能にします。
  • EmfDeviceクラスは、PDFページをEMF画像に変換することを可能にします。
  • JpegDeviceクラスは、PDFページをJPEG画像に変換することを可能にします。
  • PngDeviceクラスは、PDFページをPNG画像に変換することを可能にします。
  • GifDeviceクラスは、PDFページをGIF画像に変換することを可能にします。

PDFページを画像に変換する方法を見てみましょう。

BmpDeviceクラスは、PDFファイルの特定のページをBMP画像形式に変換するためのProcessというメソッドを提供します。他のクラスも同じメソッドを持っています。したがって、PDFページを画像に変換する必要がある場合は、必要なクラスをインスタンス化するだけです。

  1. Documentクラスを使用してPDFファイルを読み込みます。
  2. ImageDeviceのサブクラスのインスタンスを作成します。
    • BmpDevice(PDFをBMPに変換するため)。
    • EmfDevice(PDFをEmfに変換するため)。
    • JpegDevice(PDFをJPGに変換するため)。
    • PngDevice(PDFをPNGに変換するため)。
    • GifDevice(PDFをGIFに変換するため)。
  3. **ImageDevice.Process()**メソッドを呼び出してPDFから画像への変換を実行します。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFusingImageDevice()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Create Resolution object            
    var resolution = new Aspose.Pdf.Devices.Resolution(300);
    var bmpDevice = new Aspose.Pdf.Devices.BmpDevice(resolution);
    var jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution);
    var gifDevice = new Aspose.Pdf.Devices.GifDevice(resolution);
    var pngDevice = new Aspose.Pdf.Devices.PngDevice(resolution);
    var emfDevice = new Aspose.Pdf.Devices.EmfDevice(resolution);

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "ConvertAllPagesToBmp.pdf"))
    {
        ConvertPDFtoImage(bmpDevice, "bmp", document, dataDir);
        ConvertPDFtoImage(jpegDevice, "jpeg", document, dataDir);
        ConvertPDFtoImage(gifDevice, "gif", document, dataDir);
        ConvertPDFtoImage(pngDevice, "png", document, dataDir);
        ConvertPDFtoImage(emfDevice, "emf", document, dataDir);
    }
}

private static void ConvertPDFtoImage(ImageDevice imageDevice,
        string ext, Document document, var dataDir)
{
    for (int pageCount = 1; pageCount <= document.Pages.Count; pageCount++)
    {
        using (FileStream imageStream =
            new FileStream($"{dataDir}image{pageCount}_out.{ext}",
            FileMode.Create))
        {
            // Convert a particular page and save the image to stream
            imageDevice.Process(document.Pages[pageCount], imageStream);
        }
    }
}

透明な背景でPDFを画像に変換

PDFページは、白い背景の代わりに透明な背景を持つPNG画像に変換できます。

特定のページ領域を画像に変換

ページの特定の領域をCropBoxを使用して画像に変換できます。

SaveOptionsクラスを使用してPDFを変換

この記事のこの部分では、C#とSaveOptionsクラスを使用してPDFをSVGに変換する方法を示します。

**スケーラブルベクターグラフィックス(SVG)**は、静的および動的(インタラクティブまたはアニメーション)の2次元ベクターグラフィックス用のXMLベースのファイル形式の仕様のファミリーです。SVG仕様は、1999年からWorld Wide Web Consortium(W3C)によって開発されているオープンスタンダードです。

SVG画像とその動作はXMLテキストファイルで定義されています。これは、検索、インデックス作成、スクリプト化、必要に応じて圧縮できることを意味します。XMLファイルとして、SVG画像は任意のテキストエディタで作成および編集できますが、Inkscapeなどの描画プログラムを使用して作成する方が便利です。

Aspose.PDF for .NETは、SVG画像をPDF形式に変換する機能をサポートし、PDFファイルをSVG形式に変換する機能も提供します。この要件を達成するために、SvgSaveOptionsクラスがAspose.PDF名前空間に導入されました。SvgSaveOptionsのオブジェクトをインスタンス化し、Document.Save(..)メソッドの第2引数として渡します。

以下のコードスニペットは、.NETを使用してPDFファイルをSVG形式に変換する手順を示しています。

PDFをSVGに変換

  1. Documentクラスのオブジェクトを作成します。
  2. 必要な設定でSvgSaveOptionsオブジェクトを作成します。
  3. **Document.Save()**メソッドを呼び出し、SvgSaveOptionsオブジェクトを渡してPDF文書をSVGに変換します。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFtoSVG()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "PDFtoSVG.pdf"))
    {
        // Instantiate an object of SvgSaveOptions
        var saveOptions = new Aspose.Pdf.SvgSaveOptions
        {
            // Do not compress SVG image to Zip archive
            CompressOutputToZipArchive = false,
            TreatTargetFileNameAsDirectory = true                
        };

        // Save SVG file
        document.Save(dataDir + "PDFToSVG_out.svg", saveOptions);
    }
}