スタイルの操作

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

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

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

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

Word文書内の特定のスタイルでフォーマットされたテキストを取得するための解決策は、通常、Aspose.Wordsを使用して経済的で簡単です。

解決策

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

  • Documentクラスを使用してWord文書を開く。
  • ドキュメント内のすべての段落とすべての実行のコレクションを取得します。
  • 必要な段落と実行のみを選択します。 具体的には、このサンプルWord文書から、‘Heading1’段落スタイルと’Intense Emphasis’文字スタイルで書式設定されたテキストを取得します。

working-with-styles-aspose-words-cpp-1

このサンプル文書では、‘Heading1’段落スタイルで書式設定されたテキストは’Insert Tab’、‘Quick Styles’、‘Theme’であり、‘Intense emphasis’文字スタイルで書式設定されたテキストは、‘galleries’や’overall look’などの青、斜体、太字

コード

スタイルベースのクエリの実装は、Aspose.Wordsドキュメントオブジェクトモデルでは、既に配置されているツールを使用するだけなので、非常に簡単です。 このソリューションには2つのクラスメソッドが実装されています:ParagraphsByStyleName-このメソッドは、ドキュメント内の特定のスタイル名を持つ段落の配列を取得します。 RunsByStyleName-このメソッドは、特定のスタイル名を持つドキュメント内の実行の配列を取得します。 これらのメソッドはどちらも非常に似ていますが、唯一の違いは、ノードタイプと、段落ノードと実行ノード内のスタイル情報の表現です。 ここにParagraphsByStyleNameの実装があります。 以下の例では、指定されたスタイルでフォーマットされたすべての段落を検索します。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::SharedPtr<Paragraph>> ParagraphsByStyleName(System::SharedPtr<Document> doc, System::String const &styleName)
{
// Create an array to collect paragraphs of the specified style.
std::vector<System::SharedPtr<Paragraph>> paragraphsWithStyle;
// Get all paragraphs from the document.
System::SharedPtr<NodeCollection> paragraphs = doc->GetChildNodes(NodeType::Paragraph, true);
// Look through all paragraphs to find those with the specified style.
for (System::SharedPtr<Paragraph> paragraph : System::IterateOver<System::SharedPtr<Paragraph>>(paragraphs))
{
if (paragraph->get_ParagraphFormat()->get_Style()->get_Name() == styleName)
{
paragraphsWithStyle.push_back(paragraph);
}
}
return paragraphsWithStyle;
}

また、段落内の項目にアクセスするときにのみ段落がこのコレクションに読み込まれるため、paragraphコレクションは即時のオーバーヘッドを作成しないこ 次に、各演算子の標準を使用してコレクションを調べ、指定されたスタイルを持つ段落をparagraphsWithStyle配列に追加するだけです。 Paragraphスタイル名はスタイルで見つけることができます。 Paragraph.ParagraphFormatオブジェクトのNameプロパティ。 RunsByStyleNameの実装はほぼ同じですが、明らかにNodeType.Runを使用して実行ノードを取得しています。 RunオブジェクトのFont.Styleプロパティは、Runノードのスタイル情報にアクセスするために使用されます。 Below codeの例では、指定されたスタイルでフォーマットされたすべての実行を検索します。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::SharedPtr<Run>> RunsByStyleName(System::SharedPtr<Document> doc, System::String const &styleName)
{
// Create an array to collect runs of the specified style.
std::vector<System::SharedPtr<Run>> runsWithStyle;
// Get all runs from the document.
System::SharedPtr<NodeCollection> runs = doc->GetChildNodes(NodeType::Run, true);
// Look through all runs to find those with the specified style.
for (System::SharedPtr<Run> run : System::IterateOver<System::SharedPtr<Run>>(runs))
{
if (run->get_Font()->get_Style()->get_Name() == styleName)
{
runsWithStyle.push_back(run);
}
}
return runsWithStyle;
}

両方のクエリが実装されている場合は、documentオブジェクトを渡し、取得するコンテンツのスタイル名を指定するだけです。以下の例では、クエリを実行して結果を表示します。 この例のテンプレートファイルはこちらからダウンロードできます。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithStyles();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Define style names as they are specified in the Word document.
const System::String paraStyle = u"Heading 1";
const System::String runStyle = u"Intense Emphasis";
// Collect paragraphs with defined styles.
// Show the number of collected paragraphs and display the text of this paragraphs.
std::vector<System::SharedPtr<Paragraph>> paragraphs = ParagraphsByStyleName(doc, paraStyle);
std::cout << "Paragraphs with \"" << paraStyle.ToUtf8String() << "\" styles (" << paragraphs.size() << "):" << std::endl;
for (System::SharedPtr<Paragraph> paragraph : paragraphs)
{
std::cout << paragraph->ToString(SaveFormat::Text).ToUtf8String();
}
std::cout << std::endl;
// Collect runs with defined styles.
// Show the number of collected runs and display the text of this runs.
std::vector<System::SharedPtr<Run>> runs = RunsByStyleName(doc, runStyle);
std::cout << "Runs with \"" << runStyle.ToUtf8String() << "\" styles (" << runs.size() << "):" << std::endl;
for (System::SharedPtr<Run> run : runs)
{
std::cout << run->get_Range()->get_Text().ToUtf8String() << std::endl;
}

最終結果

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

working-with-styles-aspose-words-cpp-2

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

目次フィールドを挿入して操作する方法

多くの場合、目次(TOC)を含むドキュメントを操作します。 Aspose.Wordsを使用すると、数行のコードを使用して、独自の目次を挿入したり、ドキュメント内の既存の目次を完全に再構築したりできます。Aspose.Wordsを使用すると、独自の目次を挿入することができます。 この記事では、目次フィールドを操作する方法の概要と、次のことを示します:

  • 新しいTOCを挿入する方法
  • 文書内の新規または既存のTOCsを更新します。
  • 目次の書式設定と全体的な構造を制御するスイッチを指定します。
  • 目次のスタイルと外観を変更する方法。
  • 文書からすべてのエントリとともにTOCフィールド全体を削除する方法。

TCフィールドの挿入

多くの場合、特定のテキスト行がTOCに指定され、TCフィールドでマークされます。 MS Wordでこれを行う簡単な方法は、テキストを強調表示してALT+SHIFT+Oを押すことです。 これにより、選択したテキストを使用してTCフィールドが自動的に作成されます。 同じ手法は、コードを介して達成することができます。 以下のコードは、入力に一致するテキストを検索し、テキストと同じ位置にTCフィールドを挿入します。 このコードは、記事で使用されているのと同じ手法に基づいています。 以下の例は、文書内のテキストにTCフィールドを見つけて挿入する方法を示しています。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<FindReplaceOptions> options = System::MakeObject<FindReplaceOptions>();
// Highlight newly inserted content.
options->get_ApplyFont()->set_HighlightColor(System::Drawing::Color::get_DarkOrange());
options->set_ReplacingCallback(System::MakeObject<InsertTCFieldHandler>(u"Chapter 1", u"\\l 1"));
// Insert a TC field which displays "Chapter 1" just before the text "The Beginning" in the document.
doc->get_Range()->Replace(System::MakeObject<System::Text::RegularExpressions::Regex>(u"The Beginning"), u"", options);
For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
class InsertTCFieldHandler : public IReplacingCallback
{
typedef InsertTCFieldHandler ThisType;
typedef IReplacingCallback BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
public:
InsertTCFieldHandler(const System::String& text, const System::String& switches)
: mFieldText(text), mFieldSwitches(switches) {}
InsertTCFieldHandler(const System::String& switches)
: mFieldText(System::String::Empty), mFieldSwitches(switches) {}
ReplaceAction Replacing(System::SharedPtr<ReplacingArgs> args) override;
private:
System::String mFieldText;
System::String mFieldSwitches;
};
ReplaceAction InsertTCFieldHandler::Replacing(System::SharedPtr<ReplacingArgs> args)
{
// Create a builder to insert the field.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(System::DynamicCast<Document>(args->get_MatchNode()->get_Document()));
// Move to the first node of the match.
builder->MoveTo(args->get_MatchNode());
// If the user specified text to be used in the field as display text then use that, otherwise use the
// Match string as the display text.
System::String insertText;
if (!System::String::IsNullOrEmpty(mFieldText))
{
insertText = mFieldText;
}
else
{
insertText = args->get_Match()->get_Value();
}
// Insert the TC field before this node using the specified string as the display text and user defined switches.
builder->InsertField(System::String::Format(u"TC \"{0}\" {1}", insertText, mFieldSwitches));
// We have done what we want so skip replacement.
return ReplaceAction::Skip;
}

目次を変更する

スタイルの書式設定を変更する

TOC内のエントリの書式設定は、マークされたエントリの元のスタイルを使用せず、代わりに各レベルは同等のTOCスタイルを使用して書式設定されます。 たとえば、TOCの最初のレベルはTOC1スタイルで書式設定され、2番目のレベルはTOC2スタイルで書式設定されます。 これは、TOCの外観を変更するには、これらのスタイルを変更する必要があることを意味します。 Aspose.Wordsでは、これらのスタイルはロケールに依存しないStyleIdentifier.TOC1からStyleIdentifier.TOC9で表され、これらの識別子を使用してDocument.Stylesコレクションから取得できます。 文書の適切なスタイルが取得されたら、このスタイルの書式を変更することができます。 これらのスタイルへの変更は、文書内のTOCsに自動的に反映されます。 Below codeの例では、最初のレベルTOCスタイルで使用される書式設定プロパティを変更します。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Retrieve the style used for the first level of the TOC and change the formatting of the style.
doc->get_Styles()->idx_get(StyleIdentifier::Toc1)->get_Font()->set_Bold(true);

また、TOCを含めるようにマークされた段落の直接の書式設定(スタイルではなく段落自体で定義されている)は、目次のエントリにコピーされることに注意 たとえば、見出し1スタイルを使用してTOCのコンテンツをマークし、このスタイルには太字の書式があり、段落には斜体の書式が直接適用されています。 結果のTOCエントリはスタイルの書式設定の一部であるため太字ではありませんが、段落で直接書式設定されているため斜体になります。 また、各エントリとページ番号の間で使用される区切り文字の書式設定を制御することもできます。 デフォルトでは、これはタブ文字を使用してページ番号に広がる点線であり、右マージンの近くに並んでいる右タブストップがあります。

変更する特定のTOCレベルに対して取得されたStyleクラスを使用して、これらが文書内でどのように表示されるかを変更することもできます。 これが最初にどのように表示されるかを変更するには、スタイルの段落書式を取得するためにStyle.ParagraphFormatを呼び出す必要があります。 これにより、タブストップはParagraphFormat.TabStopsを呼び出し、適切なタブストップを変更することによって取得できます。 この同じ手法を使用して、タブ自体を移動または完全に削除することができます。 Below codeの例は、TOC関連する段落の右タブストップの位置を変更する方法を示しています。 この例のテンプレートファイルはこちらからダウンロードできます。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithStyles();
System::String outputDataDir = GetOutputDataDir_WorkingWithStyles();
// Open the document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.TableOfContents.doc");
// Iterate through all paragraphs in the document
for (System::SharedPtr<Paragraph> para : System::IterateOver<System::SharedPtr<Paragraph>>(doc->GetChildNodes(NodeType::Paragraph, true)))
{
// Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
if (para->get_ParagraphFormat()->get_Style()->get_StyleIdentifier() >= StyleIdentifier::Toc1 && para->get_ParagraphFormat()->get_Style()->get_StyleIdentifier() <= StyleIdentifier::Toc9)
{
// Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
System::SharedPtr<TabStop> tab = para->get_ParagraphFormat()->get_TabStops()->idx_get(0);
// Remove the old tab from the collection.
para->get_ParagraphFormat()->get_TabStops()->RemoveByPosition(tab->get_Position());
// Insert a new tab using the same properties but at a modified position.
// We could also change the separators used (dots) by passing a different Leader type
para->get_ParagraphFormat()->get_TabStops()->Add(tab->get_Position() - 50, tab->get_Alignment(), tab->get_Leader());
}
}
System::String outputPath = outputDataDir + u"ChangeTOCTabStops.doc";
doc->Save(outputPath);

ドキュメントから目次を削除する

目次は、TOCフィールドのFieldStartノードとFieldEndノードの間にあるすべてのノードを削除することによって、ドキュメントから削除できます。 以下のコードはこれを示しています。 TOCフィールドの削除は、ネストされたフィールドを追跡しないため、通常のフィールドよりも簡単です。 代わりに、現在の目次の終わりに遭遇したことを意味するFieldEndノードのタイプがFieldType.FieldTOCであることを確認します。 この場合、適切に形成された文書は別のTOCフィールド内に完全にネストされたTOCフィールドを持たないと仮定できるので、ネストされたフィールドを気にせずにこの手法を使用することができます。 まず、各TOCFieldStartノードが収集され、格納されます。 次に、指定されたTOCが列挙され、フィールド内のすべてのノードが訪問されて格納されます。 その後、ノードはドキュメントから削除されます。 Below codeの例は、指定されたTOCを文書から削除する方法を示しています。 この例のテンプレートファイルはこちらからダウンロードできます。

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithStyles();
System::String outputDataDir = GetOutputDataDir_WorkingWithStyles();
// Open a document which contains a TOC.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Document.TableOfContents.doc");
// Remove the first table of contents from the document.
RemoveTableOfContents(doc, 0);
System::String outputPath = outputDataDir + u"RemoveTOCFromDocument.doc";
// Save the output.
doc->Save(outputPath);

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

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

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Style> paraStyle = builder->get_Document()->get_Styles()->Add(StyleType::Paragraph, u"MyParaStyle");
paraStyle->get_Font()->set_Bold(false);
paraStyle->get_Font()->set_Size(8);
paraStyle->get_Font()->set_Name(u"Arial");
// Append text with "Heading 1" style.
builder->get_ParagraphFormat()->set_StyleIdentifier(StyleIdentifier::Heading1);
builder->Write(u"Heading 1");
builder->InsertStyleSeparator();
// Append text with another style.
builder->get_ParagraphFormat()->set_StyleName(paraStyle->get_Name());
builder->Write(u"This is text with some other formatting ");
System::String outputPath = outputDataDir + u"InsertStyleSeparator.doc";
// Save the document to disk.
doc->Save(outputPath);

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

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

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::String fileName = inputDataDir + u"template.docx";
System::SharedPtr<Document> doc = System::MakeObject<Document>(fileName);
// Open the document.
System::SharedPtr<Document> target = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
target->CopyStylesFromTemplate(doc);
System::String outputPath = outputDataDir + u"CopyStyles.doc";
doc->Save(outputPath);