Javaを利用してWordテキストボックスでテキストの回転方向を設定する方法
背景
Word文書にテキストボックスを追加し、テキストボックスを水平方向のテキスト配置または垂直方向のテキスト配置に設定するか、テキストボックスでテキストの回転方向までも設定できます。Javaプログラムコードにより、上記のテキストボックスの操作も実現できます。以下は、具体的な実装手順を示すJavaコード例です。
プログラムテスト環境は以下のとおりです。
Wordテストドキュメントバージョン:.docx 2019
Word Jarパッケージツール:free spire.doc.jar 3.9.0
コードコンパイルツール:IDEA
JDKバージョン:1.8.0
ドキュメントの操作に必要なjarパッケージツールをインポートし、結果は以下の通りです:
Javaコード
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;
import java.awt.*;
public class SetTextDirection {
public static void main(String[] args) {
//Word文書を作成する
Document doc = new Document();
Section section = doc.addSection();
//ページ余白を設定する
section.getPageSetup().getMargins().setLeft(90f);
section.getPageSetup().getMargins().setRight(90f);
Paragraph paragraph = section.addParagraph();
//一番目のテキストボックスを追加する
TextBox textBox1 = paragraph.appendTextBox(280, 250);
//テキストボックスを固定位置に設定する
textBox1.getFormat().setHorizontalOrigin(HorizontalOrigin.Page);
textBox1.getFormat().setHorizontalPosition(150);
textBox1.getFormat().setVerticalOrigin(VerticalOrigin.Page);
textBox1.getFormat().setVerticalPosition(80);
//テキストの回転方向を設定する
textBox1.getFormat().setTextAnchor(ShapeVerticalAlignment.Center);
textBox1.getFormat().setLayoutFlowAlt(TextDirection.Left_To_Right);//テキストを回転(反時計回り)
//textBox1.getFormat().setLayoutFlowAlt(TextDirection.Left_To_Right_Rotated);//垂直テキスト表示
//テキストを追加してフォントを設定する
Paragraph textBoxPara1 = textBox1.getBody().addParagraph();
TextRange txtRg = textBoxPara1.appendText("名前_______番号_________クラス__________");
txtRg.getCharacterFormat().setFontName("Contour");
txtRg.getCharacterFormat().setFontSize(10);
txtRg.getCharacterFormat().setTextColor(Color.black);
textBoxPara1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
//ファイルを保存する
doc.saveToFile("Result.docx");
doc.dispose();
}
}
プログラムを実行すると、Word文書が生成され、文書を開いた後、テキストボックス内のテキスト回転効果を表示できます。さまざまな回転効果を設定することにより、テキストボックスにテキスト効果を表示できます以下の図に示すように:
Left_To_Rightの回転効果:
Left_To_Right_Rotated垂直表示効果:
以上は全ての内容でした、最後まで読んでいただきありがとうございます。