スタイルとテーマの操作

StyleCollectionクラスは、組み込みを管理し、ユーザー定義の設定をスタイルに適用するために使用されます。

スタイルに基づいてコンテンツを抽出する方法

単純なレベルでは、Word文書からスタイルに基づいてコンテンツを取得することは、特定のスタイルでフォーマットされた段落やテキストの実行を識別、リスト、カウントするのに役立ちます。 たとえば、例、タイトル、参照、キーワード、図の名前、ケーススタディなど、ドキュメント内の特定の種類のコンテンツを特定する必要がある場合があります。

これをさらに数ステップ実行するために、これを使用して、使用するスタイルによって定義された文書の構造を活用して、HTMLなどの別の出力のために文書を再利用することもできます。 これは実際にAsposeのドキュメントがどのように構築されているかであり、Aspose.Wordsをテストに入れます。 Aspose.Wordsを使用して構築されたツールは、ソースWord文書を取得し、特定の見出しレベルでトピックに分割します。 XMLファイルは、左側に表示されるナビゲーションツリーを構築するために使用されるAspose.Wordsを使用して生成されます。 そしてAspose.Wordsは各トピックをHTMLに変換します。 Word文書内の特定のスタイルでフォーマットされたテキストを取得するための解決策は、通常、Aspose.Wordsを使用して経済的で簡単です。

スタイルに基づいてコンテンツを取得するAspose.Wordsがどのように簡単に処理されるかを説明するために、例を見てみましょう。 この例では、サンプルWord文書から特定の段落スタイルと文字スタイルで書式設定されたテキストを取得します。

高レベルでは、これには次のものが含まれます:

  1. Documentクラスを使用してWord文書を開く。
  2. ドキュメント内のすべての段落とすべての実行のコレクションを取得します。
  3. 必要な段落と実行のみを選択します。

具体的には、このサンプルWord文書から、‘Heading 1’段落スタイルと’Intense Emphasis’文字スタイルで書式設定されたテキストを取得します。

working-with-styles-aspose-words-java-1

このサンプル文書では、‘Heading 1’段落スタイルで書式設定されたテキストは’タブの挿入’、‘クイックスタイル’、‘テーマ’であり、‘強烈な強調’文字スタイルで書式設定されたテキストは、‘ギャラリー’や’全体的な外観’などの青、斜体、太字のテキストのいくつかのインスタンスです。

スタイルベースのクエリの実装は、Aspose.Wordsドキュメントオブジェクトモデルでは、すでに配置されているツールを使用するだけなので、非常に簡単です。 このソリューションには、2つのクラスメソッドが実装されています:

  1. ParagraphsByStyleName–このメソッドは、特定のスタイル名を持つ文書内の段落の配列を取得します。
  2. RunsByStyleName–このメソッドは、特定のスタイル名を持つドキュメント内の実行の配列を取得します。

これらのメソッドはどちらも非常に似ていますが、唯一の違いは、ノードタイプと、段落ノードと実行ノード内のスタイル情報の表現です。 指定したスタイルで書式設定されたすべての段落を見つけるために、以下のコード例に示すParagraphsByStyleNameの実装を次に示します。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static ArrayList<Paragraph> paragraphsByStyleName(Document doc, String styleName) throws Exception {
// Create an array to collect paragraphs of the specified style.
ArrayList<Paragraph> paragraphsWithStyle = new ArrayList();
// Get all paragraphs from the document.
NodeCollection paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);
// Look through all paragraphs to find those with the specified style.
for (Paragraph paragraph : (Iterable<Paragraph>) paragraphs) {
if (paragraph.getParagraphFormat().getStyle().getName().equals(styleName))
paragraphsWithStyle.add(paragraph);
}
return paragraphsWithStyle;
}

この実装では、DocumentクラスのDocument.getChildNodes()メソッドも使用され、すべての直接の子ノードのコレクションが返されます。

また、段落内の項目にアクセスするときにのみ段落がこのコレクションに読み込まれるため、paragraphコレクションは即時のオーバーヘッドを作成しないこ次に、標準のforeach演算子を使用してコレクションを調べ、指定されたスタイルを持つ段落をparagraphsWithStyle配列に追加するだけです。 Paragraphスタイル名はParagraph.getParagraphFormat()オブジェクトのStyle.getName()プロパティにあります。

RunsByStyleNameの実装はほぼ同じですが、明らかにNodeType.Runを使用して実行ノードを取得しています。 RunオブジェクトのFont.getStyle()プロパティは、Runノードのスタイル情報にアクセスするために使用されます。

次のコード例では、指定したスタイルで書式設定されたすべての実行を検索します。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static ArrayList<Run> runsByStyleName(Document doc, String styleName) throws Exception {
// Create an array to collect runs of the specified style.
ArrayList<Run> runsWithStyle = new ArrayList();
// Get all runs from the document.
NodeCollection runs = doc.getChildNodes(NodeType.RUN, true);
// Look through all runs to find those with the specified style.
for (Run run : (Iterable<Run>) runs) {
if (run.getFont().getStyle().getName().equals(styleName))
runsWithStyle.add(run);
}
return runsWithStyle;
}

次のコード例では、クエリを実行して結果を表示します。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");
// Define style names as they are specified in the Word document.
final String PARA_STYLE = "Heading 1";
final String RUN_STYLE = "Intense Emphasis";
// Collect paragraphs with defined styles.
// Show the number of collected paragraphs and display the text of this paragraphs.
ArrayList<Paragraph> paragraphs = paragraphsByStyleName(doc, PARA_STYLE);
System.out.println(java.text.MessageFormat.format("Paragraphs with \"{0}\" styles ({1}):", PARA_STYLE, paragraphs.size()));
for (Paragraph paragraph : paragraphs)
System.out.print(paragraph.toString(SaveFormat.TEXT));
// Collect runs with defined styles.
// Show the number of collected runs and display the text of this runs.
ArrayList<Run> runs = runsByStyleName(doc, RUN_STYLE);
System.out.println(java.text.MessageFormat.format("\nRuns with \"{0}\" styles ({1}):", RUN_STYLE, runs.size()));
for (Run run : runs)
System.out.println(run.getRange().getText());

すべてが完了すると、サンプルを実行すると、次の出力が表示されます:

working-with-styles-aspose-words-java-2

ご覧のとおり、これは非常に簡単な例であり、収集された段落の数とテキストを示し、サンプルWord文書で実行されます。

別の段落スタイルを配置するには、スタイル区切り文字を挿入します

スタイルセパレータは、Ctrl+Alt+EnterキーボードショートカットをMSWordに使用して段落の最後に追加できます。 この機能を使用すると、1つの論理的に印刷された段落で使用される2つの異なる段落スタイルを使用できます。 特定の見出しの先頭からのテキストを目次に表示したいが、見出し全体を目次に表示したくない場合は、この機能を使用できます。

次のコード例は、異なる段落スタイルを配置するためにスタイル区切り文字を挿入する方法を示しています。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Style paraStyle = builder.getDocument().getStyles().add(StyleType.PARAGRAPH, "MyParaStyle");
paraStyle.getFont().setBold(false);
paraStyle.getFont().setSize(8);
paraStyle.getFont().setName("Arial");
// Append text with "Heading 1" style.
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.write("Heading 1");
builder.insertStyleSeparator();
// Append text with another style.
builder.getParagraphFormat().setStyleName(paraStyle.getName());
builder.write("This is text with some other formatting ");
dataDir = dataDir + "InsertStyleSeparator_out.doc";
doc.save(dataDir);

テンプレートからすべてのスタイルをコピーする

ある文書から別の文書にすべてのスタイルをコピーする場合があります。 Document.CopyStylesFromTemplateメソッドを使用すると、指定したテンプレートからドキュメントにスタイルをコピーできます。 スタイルがテンプレートからドキュメントにコピーされると、ドキュメント内の同様の名前のスタイルがテンプレート内のスタイルの説明と一致するよ テンプレートの一意のスタイルがドキュメントにコピーされます。 ドキュメント内の一意のスタイルはそのまま残ります。

次のコード例は、あるドキュメントから別のドキュメントにスタイルをコピーする方法を示しています。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
Document doc = new Document(dataDir + "template.docx");
Document target = new Document(dataDir + "TestFile.doc");
target.copyStylesFromTemplate(doc);
dataDir = dataDir + "CopyStyles_out.docx";
doc.save(dataDir);

テーマのプロパティを操作する方法

ドキュメントテーマプロパティにアクセスするために、Aspose.Wordsに基本的なAPIを追加しました。 今のところ、このAPIには次のパブリックオブジェクトが含まれています:

  • テーマ
  • ThemeFonts
  • ThemeColors

テーマプロパティを取得する方法は次のとおりです:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetThemeProperties.class);
Document doc = new Document(dataDir + "Document.doc");
Theme theme = doc.getTheme();
// Major (Headings) font for Latin characters.
System.out.println(theme.getMajorFonts().getLatin());
// Minor (Body) font for EastAsian characters.
System.out.println(theme.getMinorFonts().getEastAsian());
// Color for theme color Accent 1.
System.out.println(theme.getColors().getAccent1());

そして、ここでは、テーマのプロパティを設定する方法です:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetThemeProperties.class);
Document doc = new Document(dataDir + "Document.doc");
Theme theme = doc.getTheme();
// Set Times New Roman font as Body theme font for Latin Character.
theme.getMinorFonts().setLatin("Algerian");
// Set Color.Gold for theme color Hyperlink.
theme.getColors().setHyperlink(java.awt.Color.DARK_GRAY);
doc.save(dataDir + "output.doc");