C#でWord文書を画像に変換する方法

Aspose.Words for .NETを使用すると、DOCX、DOC、RTF、ODT、HTMLなどのドキュメントをPNG、JPEG、BMP、GIFなどの画像ファイル形式に変換できます。このチュートリアルでは、Word文書をC#で画像に変換する方法を学習します。

C#でWord文書を画像に変換する手順

  1. NuGet.orgからAspose.Words for .NETパッケージをインストールします
  2. Aspose.WordsおよびAspose.Words.Saving名前空間への参照を追加します
  3. License.SetLicenseメソッドを使用してAspose.Wordsfor.NETのライセンスを設定します
  4. 入力ドキュメントをAspose.WordsのDOMにインポートします
  5. ImageSaveOptionsクラスのインスタンスを作成して、ドキュメントページを画像にレンダリングするときのオプションを指定します
  6. IPageSavingCallbackインターフェイスを実装し、PageSavingArgs.PageFileNameプロパティを使用してファイル名のパスを設定します
  7. 画像変換用のWord文書のページ範囲を設定する
  8. 最後に、Document.Saveメソッドを使用して画像をディスクに保存します

ドキュメントを操作するときは、多くの場合、異なるフォントのフォーマットとスタイルを使用する必要があります。ドキュメントで使用されているフォントがインストールされていないマシンでドキュメントを開くと、ドキュメントビューアでのテキスト表現が異なります。 Aspose.Wordsの場合も同じです。ドキュメントを固定ページ形式(JPEG、PNG、PDF、またはXPS)にレンダリングする場合は、TrueTypeフォントが必要です。入力ドキュメントで使用されるフォントは、Wordドキュメントを画像に変換するマシンにインストールする必要があります。

以前、別のハウツートピックでC#を使用してWord文書を印刷する方法を調べました。このトピックでは、Word文書をC#で画像に変換するためのすべての手順について説明します。

C#でWord文書を画像に変換するコード

using Aspose.Words;
using Aspose.Words.Saving;
using System;
namespace KBCodeExamples
{
class How_to_Convert_Word_Document_to_Images_in_C_sharp
{
public static void ConvertWordDocumenttoImages(String wordtoimage_directory)
{
//Set Aspose license before converting word document to images
//using Aspose.Words for .NET
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License();
AsposeWordsLicense.SetLicense(wordtoimage_directory + @"Aspose.Words.lic");
//Import the document into Aspose.Words DOM.
//The document can be imported from disk or memory stream.
Document doc = new Document(wordtoimage_directory + "input.docx");
//Set ImageSaveOptions to convert document pages to image.
ImageSaveOptions wordpagestoimage = new ImageSaveOptions(SaveFormat.Png);
//Set page ranges to convert all word pages to image.
PageRange pagerange = new PageRange(0, doc.PageCount - 1);
wordpagestoimage.PageSet = new PageSet(pagerange);
wordpagestoimage.PageSavingCallback = new Word_Pages_To_Images();
//Save document's pages to PNG
doc.Save(@"output.png", wordpagestoimage);
}
//Implement this interface if you want to control how Aspose.Words saves separate pages
//when saving a document to fixed page formats.
class Word_Pages_To_Images : IPageSavingCallback
{
public void PageSaving(PageSavingArgs args)
{
args.PageFileName = string.Format(@"output_{0}.png", args.PageIndex);
}
}
}
}

上記のC#のコードは、MSOfficeをインストールせずにWord文書を画像に変換します。 .NETがWindows、Linux、macOS、およびクラウドプラットフォーム(Amazon WebServicesおよびMicrosoftAzure)にインストールされている場所で使用できます。

 日本語