Javaを使用してWordに画像を挿入する方法

この簡単なチュートリアルでは、Javaを使用してWordに画像を挿入する方法を学習します。画像を追加した後、ファイルをDOCまたはDOCX形式で保存できます。次の手順を使用して、アプリケーションでJavaを使用してWord文書に画像を追加できます。

Javaを使用してWordに画像を挿入する手順

  1. MavenリポジトリからAspose.Wordsをインストールします
  2. Documentクラスオブジェクトを使用して入力Word文書をロードします
  3. DocumentBuilderクラスオブジェクトをインスタンス化します
  4. Word文書ヘッダーに画像を挿入します
  5. Word文書に画像を追加段落
  6. 画像を挿入した後、出力されたWord文書を保存します

これらの手順では、Documentクラスを初期化して入力Word文書をロードしてから、ヘッダーと段落に画像を挿入します。出力ファイルはDOCX形式で保存されますが、要件に応じて他の形式を選択できます。

Javaを使用してWord文書に画像を追加するコード

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.License;
import com.aspose.words.Shape;
public class InsertPictureInWordDocumentUsingJava
{
public static void main(String[] args) throws Exception { //main function for InsertPictureInWordDocumentUsingJava class
// Initialize a license to avoid trial version watermark in the output Word file after adding image
License license = new License();
license.setLicense("Aspose.Words.lic");
// Load input Word DOCX document
Document AddImagesToWordDOC = new Document("input.docx");
// Initialize DocumentBuilder class object to add image
DocumentBuilder imageWriter = new DocumentBuilder(AddImagesToWordDOC);
// Move the cursor to the Primary Header
imageWriter.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
// Insert a picture in Word document header
Shape headerImage = imageWriter.insertImage("SampleImage.jpg");
// Set Image Size in Header section
headerImage.setWidth(1 * 72); // equals to one inch
headerImage.setHeight(1 * 72);
// Move cursor to last Paragraph in Document
imageWriter.moveTo(AddImagesToWordDOC.getLastSection().getBody().getLastParagraph());
// Add the picture to Word Document and Link it with the file
Shape imageAsLinkToFile = imageWriter.insertImage("SampleImage.jpg");
imageAsLinkToFile.getImageData().setSourceFullName("SampleImage.jpg");
// Save output DOCX file after inserting image
AddImagesToWordDOC.save("Word with Embedded and Linked Images.docx");
}
}

このJavaコードサンプルは、MSWordアプリケーションやその他のワードプロセッシングアプリケーションを必要とせずにWord文書をロードします。次に、コントロールをヘッダーと最後の段落に移動して、それぞれ画像を挿入します。最後に、適切なファイル拡張子を指定するか、保存関数の2番目の引数としてSaveFormat列挙子を使用することで、ファイルを保存できます。

このチュートリアルでは、Javaを使用してMSWordに画像を挿入する方法を学習しました。 Word文書を最初から作成する方法を学びたい場合は、記事Javaを使用してWord文書を作成する方法を参照してください。

 日本語