このステップバイステップのチュートリアルでは、C# を使用して Word のすべての改ページを削除する方法を説明します。開発環境の設定方法の詳細、プログラミング タスクのリスト、C# を使用して Word で改ページを削除するための実行可能なサンプル コードが含まれています。 Word 文書の構造と、Word ファイルに含まれるさまざまな種類の改ページについての詳細を共有します。
C# を使用して Word で改ページを削除する手順
- Aspose.Words for .NET を使用して改ページを排除するように開発環境を設定します
- ターゲットの Word ファイルを Document オブジェクトにロードし、すべての paragraphs にアクセスします
- すべての段落を解析し、段落の前の改ページを確認します。
- 各段落の前の改ページを削除します
- 各段落内のすべてのランを解析し、すべての改ページを空の文字列に置き換えます。
- 結果として得られた Word ファイルを改ページせずに保存します。
これらの手順では、C# を使用して Word で改ページを削除する方法 のプロセスについて説明します。各 Word ファイルには段落のコレクションがあり、各段落には、最初から改行を削除するには ‘false’ に設定する必要がある、ParagraphFormat.PageBreakBefore プロパティがあります。さらに、各段落にはランのコレクションがあり、各ランには複数の場所で改ページを含めることができ、空の文字列に置き換えることで削除できます。
C# を使用して Word の改ページを削除するコード
using Aspose.Words; | |
class Program{ | |
static void Main(string[] args) // Remove page breaks in a Word file using C# | |
{ | |
// Set PDF license | |
new License().SetLicense("Aspose.Total.lic"); | |
// Load the sample Word file having page breaks in it | |
Document doc = new Document("DocWithPageBreaks.docx"); | |
// Get access to all the paragraphs | |
NodeCollection docParagraphs = doc | |
.GetChildNodes(NodeType.Paragraph, true); | |
foreach (Paragraph currentPara in docParagraphs) | |
{ | |
// Check if the page break is there before | |
// the paragraph | |
if (currentPara.ParagraphFormat.PageBreakBefore) | |
{ | |
// Remove the page break from the start | |
currentPara.ParagraphFormat | |
.PageBreakBefore = false; | |
} | |
// Parse through all the runs in the paragraph | |
foreach (Run currentRun in currentPara.Runs) | |
{ | |
// Check page break | |
if (currentRun.Text.Contains(ControlChar.PageBreak)) | |
{ | |
// Replace the page break with an empty string | |
currentRun.Text = currentRun.Text | |
.Replace(ControlChar.PageBreak, string.Empty); | |
} | |
} | |
} | |
// Save the resultant DOCX without any page break in it | |
doc.Save("DocxWithoutPageBreaks.docx"); | |
} | |
} |
このコードでは、C# を使用して Word で改ページを削除する方法を観察しました。 NodeType.Paragraph を引数として指定して GetChildNodes() メソッドを使用し、段落のコレクションにアクセスします。各ランのテキストには、改行、段落区切りなどのさまざまな種類の制御文字を含めることができます。また、改ページに使用したのと同じ方法を使用して列区切りを削除することもできます。
この記事では、Word ファイル内の改ページを削除する方法を説明しました。 Word ファイル内の空白ページを削除するプロセスについて知りたい場合は、C#を使用してWordの空白ページを削除する方法 の記事を参照してください。