チュートリアル

簡単にライブラリーを使用するためのチュートリアルコレクション

チュートリアル»docjavadocumentoperation

Displaying items by tag: docjavadocumentoperation

Word 文書の印刷は、文書管理の基本的な側面であり、デジタルファイルを目に見える物理的なコピーに変換することができます。参照用、配布用、保存用など、どのような目的でハードコピーを作成する必要がある場合でも、Word 文書を印刷する能力は、さまざまな仕事や個人的な場面で役立つ貴重なスキルです。

この記事では、Spire.Doc for Java ライブラリと java.awt.print パッケージを使用して、Java で Word 文書を印刷する方法を説明します。

Spire.Doc for Java をインストールします

まず、Spire.Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.5.1</version>
    </dependency>
</dependencies>

Java で Word 文書をデフォルトのプリンターで印刷する

Word ドキュメントをデフォルトのプリンターで印刷するのは、便利で簡単な方法です。この方法は、特定のプリンター設定が不要な場合や、プリンターに設定されているデフォルト設定を利用したい場合など、通常の印刷作業に適していることが多い。

以下は、Spire.Doc for Java と java.awt.print.PrinterJob オブジェクトを使用して、デフォルトプリンタで Word ドキュメントを印刷する手順です。

  • PrinterJob オブジェクトを作成し、その下のメソッドを呼び出して印刷ジョブを設定します。
  • Document オブジェクトを作成し、Document.LoadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • PrinterJob.setPrintable() メソッドを使用して、指定されたフォーマットでドキュメントの各ページをレンダリングします。
  • PrinterJob.print() メソッドを呼び出して Word ドキュメントを印刷します。
  • Java
import com.spire.doc.Document;

import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithDefaultPrinter {

    public static void main(String[] args) {

        // ドキュメントオブジェクトを作成する
        Document document = new Document();

        // Wordファイルをロードする
        document.loadFromFile("サンプル.docx");

        // PrinterJobオブジェクトを作成する
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // PageFormatオブジェクトを作成し、デフォルトのサイズと向きに設定する
        PageFormat pageFormat = printerJob.defaultPage();

        // このPageFormatに関連付けられたPaperオブジェクトのコピーを返す
        Paper paper = pageFormat.getPaper();

        // このPaperの印刷可能な領域を設定する
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // 印刷するコピーの数を設定する
        printerJob.setCopies(1);

        // このPageFormatに対するPaperオブジェクトを設定する
        pageFormat.setPaper(paper);

        // 指定されたフォーマットでページをレンダリングするためのペインターを呼び出す
        printerJob.setPrintable(document, pageFormat);

        // ドキュメントを印刷する
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}

Java で指定したプリンターで Word 文書を印刷する

Java を使用して指定されたプリンターで Word ドキュメントを印刷すると、印刷タスクを処理する特定のプリンターを選択できます。この方法は、利用可能なプリンタが複数あり、特定のプリンターに印刷出力を指示したい場合に便利です。

以下は、Spire.Doc for Java と java.awt.print.PrinterJob オブジェクトを使用して、指定されたプリンタで Word ドキュメントを印刷する手順です。

  • PrinterJob オブジェクトを作成し、その下のメソッドを呼び出して印刷ジョブをセットアップします。
  • カスタムメソッド findPrintService() を使用して、プリンター名で印刷サービスを見つけます。
  • PrinterJob.setPrintService() メソッドを使用して印刷サービスを適用します。
  • Document オブジェクトを作成し、Document.LoadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • PrinterJob.setPrintable() メソッドを使用して、指定されたフォーマットでドキュメントの各ページをレンダリングします。
  • PrinterJob.print() メソッドを呼び出して、Word ドキュメントを印刷します。
  • Java
import com.spire.doc.Document;

import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithSpecifiedPrinter {

    public static void main(String[] args) throws PrinterException {

        // デフォルトのプリンターに関連付けられたPrinterJobオブジェクトを作成する
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // プリンター名を指定する
        PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
        printerJob.setPrintService(myPrintService);

        // PageFormatインスタンスを作成し、デフォルトのサイズと向きに設定する
        PageFormat pageFormat = printerJob.defaultPage();

        // このPageFormatに関連付けられたPaperオブジェクトのコピーを返す
        Paper paper = pageFormat.getPaper();

        // このPaperの印刷可能な領域を設定する
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // このPageFormatに対するPaperオブジェクトを設定する
        pageFormat.setPaper(paper);

        // ドキュメントオブジェクトを作成する
        Document document = new Document();

        // Wordファイルをロードする
        document.loadFromFile("サンプル.docx");

        // 指定されたフォーマットでページをレンダリングするためのペインターを呼び出す
        printerJob.setPrintable(document, pageFormat);

        // ドキュメントを印刷する
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }

    // プリンターサービスを検索する
    private static PrintService findPrintService(String printerName) {

        PrintService[] printServices = PrinterJob.lookupPrintServices();
        for (PrintService printService : printServices) {
            if (printService.getName().equals(printerName)) {
                return printService;
            }
        }
        return null;
    }
}

Java で印刷ダイアログボックスを使って Word 文書を印刷する

印刷ダイアログボックスを使用して Word ドキュメントを印刷すると、ユーザーはプロセスを開始する前にプリンタを選択し、印刷設定をカスタマイズすることができます。印刷ダイアログボックスを表示することで、ユーザーに印刷操作の自由度と制御性を提供することができます。

Java で印刷ダイアログボックスを使って Word ドキュメントを印刷するには、以下の手順に従ってください。

  • PrinterJob オブジェクトを作成し、その下で印刷ジョブをセットアップするメソッドを呼び出します。
  • Document オブジェクトを作成し、Document.LoadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • PrinterJob.setPrintable() メソッドを使用して、指定されたフォーマットでドキュメントの各ページをレンダリングします。
  • PrinterJob.printDialog() メソッドを呼び出して印刷ダイアログを表示します。
  • PrinterJob.print() メソッドを呼び出して Word ドキュメントを印刷します。
  • Java
import com.spire.doc.Document;

import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintWithDialogBox {

    public static void main(String[] args) {

        // デフォルトのプリンターに関連付けられたPrinterJobオブジェクトを作成する
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // PageFormatオブジェクトを作成し、デフォルトのサイズと向きに設定する
        PageFormat pageFormat = printerJob.defaultPage();

        // このPageFormatに関連付けられたPaperオブジェクトのコピーを返す
        Paper paper = pageFormat.getPaper();

        // このPaperの印刷可能な領域を設定する
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // このPageFormatに対するPaperオブジェクトを設定する
        pageFormat.setPaper(paper);

        // ドキュメントオブジェクトを作成する
        Document document = new Document();

        // Wordファイルをロードする
        document.loadFromFile("サンプル.docx");

        // 指定されたフォーマットでページをレンダリングするためのペインターを呼び出す
        printerJob.setPrintable(document, pageFormat);

        // 印刷ダイアログを表示する
        if (printerJob.printDialog()) {
            try {
                // ドキュメントを印刷する
                printerJob.print();
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        }
    }
}

Java で Word 文書のページ範囲を印刷する

Word ドキュメントの範囲指定印刷は、ドキュメント全体を印刷するのではなく、ドキュメントから特定のページを選択して、そのページのみを印刷できる便利な機能です。これは、長いドキュメントを扱う場合や、特定のセクションだけを印刷する必要がある場合に特に便利です。

Java で Word ドキュメントを印刷する際に印刷範囲を設定する手順は以下の通りです。

  • PrinterJob オブジェクトを作成し、印刷ジョブをセットアップするためにその下のメソッドを呼び出します。
  • Document オブジェクトを作成し、Document.LoadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • PrinterJob.setPrintable() メソッドを使用して、指定されたフォーマットでドキュメントの各ページをレンダリングします。
  • PrintRequestAttributeSet オブジェクトを作成し、印刷範囲を属性セットに追加します。
  • ページの範囲を印刷するために PrinterJob.print() メソッドを呼び出します。
  • Java
import com.spire.doc.Document;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintPageRange {

    public static void main(String[] args) {

        // ドキュメントオブジェクトを作成する
        Document document = new Document();

        // Wordファイルをロードする
        document.loadFromFile("サンプル.docx");

        // PrinterJobオブジェクトを作成する
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // PageFormatオブジェクトを作成し、デフォルトのサイズと向きに設定する
        PageFormat pageFormat = printerJob.defaultPage();

        // このPageFormatに関連付けられたPaperオブジェクトのコピーを返す
        Paper paper = pageFormat.getPaper();

        // このPaperの印刷可能な領域を設定する
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // コピーの数を設定する
        printerJob.setCopies(1);

        // このPageFormatに対するPaperオブジェクトを設定する
        pageFormat.setPaper(paper);

        // 指定されたフォーマットでページをレンダリングするためのペインターを呼び出す
        printerJob.setPrintable(document, pageFormat);

        // PrintRequestAttributeSetオブジェクトを作成する
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        // 印刷範囲を設定する
        attributeSet.add(new PageRanges(1, 5));

        // ドキュメントを印刷する
        try {
            printerJob.print(attributeSet);
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}

Java で Word 文書を両面モードで印刷する

両面印刷は、両面印刷とも呼ばれ、用紙の両面に自動的に印刷できるため、長いレポートやプレゼンテーション、配布資料などに便利です。

Java で Word ドキュメントを両面モードで印刷する手順は以下の通りです。

  • PrinterJob オブジェクトを作成し、その下のメソッドを呼び出して印刷ジョブをセットアップします。
  • Document オブジェクトを作成し、Document.LoadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • PrinterJob.setPrintable() メソッドを使用して、指定されたフォーマットでドキュメントの各ページをレンダリングします。
  • PrintRequestAttributeSet オブジェクトを作成し、両面印刷モードを属性セットに追加します。
  • PrinterJob.print() メソッドを呼び出して Word ドキュメントを印刷します。
  • Java
import com.spire.doc.Document;

import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintInDuplexMode {

    public static void main(String[] args) {

        // ドキュメントオブジェクトを作成する
        Document document = new Document();

        // Wordファイルをロードする
        document.loadFromFile("サンプル.docx");

        // デフォルトのプリンターに関連付けられたPrinterJobオブジェクトを作成する
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        // PageFormatオブジェクトを作成し、デフォルトのサイズと向きに設定する
        PageFormat pageFormat = printerJob.defaultPage();

        // このPageFormatに関連付けられたPaperオブジェクトのコピーを返す
        Paper paper = pageFormat.getPaper();

        // このPaperの印刷可能な領域を設定する
        paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

        // このPageFormatに対するPaperオブジェクトを設定する
        pageFormat.setPaper(paper);

        // 指定されたフォーマットでページをレンダリングするためのペインターを呼び出す
        printerJob.setPrintable(document, pageFormat);

        // PrintRequestAttributeSetオブジェクトを作成する
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        // デュプレックス印刷モードを有効にする
        attributeSet.add(Sides.TWO_SIDED_SHORT_EDGE);

        // ドキュメントを印刷する
        try {
            printerJob.print(attributeSet);
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 印刷

Word ドキュメントからコンテンツを抽出することは、仕事でも勉強でも重要な役割を果たします。1 ページ分の内容を抽出すると、重要なポイントをすばやく閲覧して要約するのに役立ち、1 つのセクションから内容を抽出すると、特定のトピックやセクションを詳しく学習するのに役立ちます。ドキュメント全体を抽出することで、ドキュメントの内容を包括的に理解することができ、深い分析や包括的な理解が容易になります。この記事では、Java プロジェクトで Spire.Doc for Java を使用して Word ドキュメントのページ、セクション、コンテンツ全体を読み取る方法を紹介します。

Spire.Doc for Java をインストールします

まず、Spire.Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.3.1</version>
    </dependency>
</dependencies>

Java で Word ドキュメントからページを読み取る

FixedLayoutDocument クラスと FixedLayoutPage クラスを使用すると、指定したページから内容を簡単に抽出することができます。抽出された内容を見やすくするために、次のコード例では、抽出された内容を新しい Word ドキュメントに保存しています。詳しい手順は以下の通りです:

  • Document クラスのオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • FixedLayoutDocument クラスのオブジェクトを作成します。
  • ドキュメント内のページの FixedLayoutPage オブジェクトを取得します。
  • FixedLayoutPage.getSection() メソッドを使用して、ページのあるセクションを取得します。
  • セクション内のページの最初の段落のインデックス位置を取得します。
  • セクション内のページの最後の段落のインデックス位置を取得します。
  • 別の Document クラスのオブジェクトを作成 します。
  • Document.addSection() メソッドを使用して新しいセクションを追加します。
  • Section.cloneSectionPropertiesTo(newSection) メソッドを使用して、元のセクションのプロパティを新しいセクションにコピーします。
  • ページの内容を、元のドキュメントから新しいドキュメントにコピーします。
  • Document.saveToFile() メソッドを使用して、結果のドキュメントを保存します。
  • Java
import com.spire.doc.*;
import com.spire.doc.pages.*;
import com.spire.doc.documents.*;

public class readWordPage {
    public static void main(String[] args) {
        // 新しいドキュメントオブジェクトを作成する
        Document document = new Document();

        // 指定されたファイルからドキュメントの内容を読み込む
        document.loadFromFile("サンプル.docx");

        // 固定レイアウトドキュメントオブジェクトを作成する
        FixedLayoutDocument layoutDoc = new FixedLayoutDocument(document);

        // 最初のページを取得する
        FixedLayoutPage page = layoutDoc.getPages().get(0);

        // ページが所属しているセクションを取得する
        Section section = page.getSection();

        // ページの最初の段落を取得する
        Paragraph paragraphStart = page.getColumns().get(0).getLines().getFirst().getParagraph();
        int startIndex = 0;
        if (paragraphStart != null) {
            // セクション内での段落のインデックスを取得する
            startIndex = section.getBody().getChildObjects().indexOf(paragraphStart);
        }

        // ページの最後の段落を取得する
        Paragraph paragraphEnd = page.getColumns().get(0).getLines().getLast().getParagraph();

        int endIndex = 0;
        if (paragraphEnd != null) {
            // セクション内での段落のインデックスを取得する
            endIndex = section.getBody().getChildObjects().indexOf(paragraphEnd);
        }

        // 新しいドキュメントオブジェクトを作成する
        Document newdoc = new Document();

        // 新しいセクションを追加する
        Section newSection = newdoc.addSection();

        // 元のセクションのプロパティを新しいセクションにクローンする
        section.cloneSectionPropertiesTo(newSection);

        // 元のドキュメントのページの内容を新しいドキュメントにコピーする
        for (int i = startIndex; i <= endIndex; i++) {
            newSection.getBody().getChildObjects().add(section.getBody().getChildObjects().get(i).deepClone());
        }

        // 新しいドキュメントを指定されたファイルに保存する
        newdoc.saveToFile("output/ページの内容.docx", FileFormat.Docx);

        // 新しいドキュメントを閉じて解放する
        newdoc.close();
        newdoc.dispose();

        // 元のドキュメントを閉じて解放する
        document.close();
        document.dispose();
    }
}

Java:Word ドキュメントから内容を読み取る方法

Java で Word ドキュメントからセクションを読み取る

Document.Sections[index] プロパティを使用すると、ドキュメントのヘッダー、フッター、本文を含む特定のセクションクラスのオブジェクトにアクセスすることができます。次の例では、あるセクションのすべての内容を別のドキュメントにコピーする簡単な方法を示します。詳しい手順は以下のとおりです:

  • Document クラスのオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • Document.getSections().get(1) メソッドを使用して、ドキュメントの 2 番目のセクションを取得します。
  • 別の新しい Document クラスのオブジェクトを作成します。
  • Document.cloneDefaultStyleTo(newdoc) メソッドを使用して、元のドキュメントのデフォルトのスタイルを新しいドキュメントに複製します。
  • Document.getSections().add(section.deepClone()) メソッドを使用して、元のドキュメントの 2 番目のセクションの内容を新しいドキュメントにコピーします。
  • Document.saveToFile() メソッドを使用して、結果のドキュメントを保存します。
  • Java
import com.spire.doc.*;

public class readWordSection {
    public static void main(String[] args) {
        // 新しいドキュメントオブジェクトを作成する
        Document document = new Document();

        // ファイルからWordドキュメントを読み込む
        document.loadFromFile("サンプル.docx");

        // ドキュメントの2番目のセクションを取得する
        Section section = document.getSections().get(1);

        // 新しいドキュメントオブジェクトを作成する
        Document newdoc = new Document();

        // デフォルトスタイルを新しいドキュメントにクローンする
        document.cloneDefaultStyleTo(newdoc);

        // 2番目のセクションを新しいドキュメントにクローンする
        newdoc.getSections().add(section.deepClone());

        // 新しいドキュメントをファイルに保存する
        newdoc.saveToFile("output/セクションの内容.docx", FileFormat.Docx);

        // 新しいドキュメントオブジェクトを閉じて解放する
        newdoc.close();
        newdoc.dispose();

        // 元のドキュメントオブジェクトを閉じて解放する
        document.close();
        document.dispose();
    }
}

Java:Word ドキュメントから内容を読み取る方法

Java で Word ドキュメントから内容全体を読み取る

この例では、元のドキュメントの各セクションを繰り返し処理して、ドキュメントの内容全体を読み取り、各セクションを新しいドキュメントにコピーする方法を示します。この方法は、ドキュメント全体の構造と内容の両方をすばやく複製し、新しいドキュメントで元のドキュメントの書式とレイアウトを保持するのに役立ちます。このような操作は、ドキュメント構造の整合性と一貫性を維持するために非常に便利です。詳しい手順は以下のとおりです:

  • Document クラスのオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • 別の新しい Document クラスのオブジェクトを作成します。
  • Document.cloneDefaultStyleTo(newdoc) メソッドを使用して、元のドキュメントのデフォルトのスタイルを新しいドキュメントにコピーします。
  • 元のドキュメントの各セクションを繰り返し処理し、新しいドキュメントにコピーします。
  • Document.saveToFile() メソッドを使用して、結果のドキュメントを保存します。
  • Java
import com.spire.doc.*;

public class readWordContent {
    public static void main(String[] args) {
        // 新しいドキュメントオブジェクトを作成する
        Document document = new Document();

        // ファイルからWordドキュメントを読み込む
        document.loadFromFile("サンプル.docx");

        // 新しいドキュメントオブジェクトを作成する
        Document newdoc = new Document();

        // デフォルトスタイルを新しいドキュメントにクローンする
        document.cloneDefaultStyleTo(newdoc);

        // 元のドキュメント内の各セクションをイテレーションし、新しいドキュメントにクローンする
        for (Section sourceSection : (Iterable<Section>) document.getSections()) {
            newdoc.getSections().add(sourceSection.deepClone());
        }

        // 新しいドキュメントをファイルに保存する
        newdoc.saveToFile("output/ドキュメント内容.docx", FileFormat.Docx);

        // 新しいドキュメントオブジェクトを閉じて解放する
        newdoc.close();
        newdoc.dispose();

        // 元のドキュメントオブジェクトを閉じて解放する
        document.close();
        document.dispose();
    }
}

Java:Word ドキュメントから内容を読み取る方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

Word 文書における変数は、テキストの置換や削除など、便利で正確なテキスト管理ができることを特徴とするフィールドの一種です。検索・置換機能に比べ、変数に値を代入してテキストを置換する方が、高速でエラーも少ない。この記事では、Spire.Doc for Java を使用して Word 文書で変数を追加または変更する方法を示します。

Spire.Doc for Java をインストールします

まず、Spire.Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Java で Word への変数を挿入する

変数は Word のフィールドの一種であるため、Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) メソッドを使用して変数をWord文書に挿入し、VariableCollection.add() メソッドを使用して変数に値を割り当てることができます。なお、変数に値を割り当てた後は、文書のフィールドを更新して割り当てられた値を表示する必要があります。詳細な手順は以下の通りです。

  • Document のオブジェクトを作成します。
  • Document.addSection() メソッドを使用して、文書にセクションを追加します。
  • Section.addParagraph() メソッドを使用して、セクションに段落を追加します。
  • Paragraph.appendField(String fieldName, FieldType.Field_Doc_Variable) メソッドを使用して、段落に変数フィールドを追加します。
  • Document.getVariables() メソッドを使用して、変数コレクションを取得します。
  • VariableCollection.add() メソッドを使用して、変数に値を代入します。
  • Document.isUpdateFields() メソッドを使用して、文書内のフィールドを更新します。
  • Document.saveToFile() メソッドを使用して結果文書を保存します。
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.formatting.CharacterFormat;

public class AddVariables {
    public static void main(String[] args) {

        //Documentのオブジェクトを作成する
        Document document = new Document();

        //セクションを追加する
        Section section = document.addSection();

        //段落を追加する
        Paragraph paragraph = section.addParagraph();

        //テキスト形式を設定する
        CharacterFormat characterFormat = paragraph.getStyle().getCharacterFormat();
        characterFormat.setFontName("Yu Mincho");
        characterFormat.setFontSize(12);

        //ページ余白を設定する
        section.getPageSetup().getMargins().setTop(80f);

        //変数フィールドを段落に追加する
        paragraph.appendField("Time", FieldType.Field_Doc_Variable);
        paragraph.appendText("は宝物であり、逃げる水のように貴重です。\r\n");
        paragraph.appendField("Time", FieldType.Field_Doc_Variable);
        paragraph.appendText("は風のように過ぎ去り、砂のように滑ります。\r\n");
        paragraph.appendField("Time", FieldType.Field_Doc_Variable);
        paragraph.appendText("は人生の舞台であり、私たちはその中で輝きます。");

        //変数コレクションを取得する
        VariableCollection variableCollection = document.getVariables();

        //変数に値を代入する
        variableCollection.add("Time", "時間");

        //文書内のフィールドを更新する
        document.isUpdateFields(true);

        //結果文書を保存する
        document.saveToFile("AddVariables.docx", FileFormat.Auto);
        document.dispose();
    }
}

Java:Word 文書で変数を追加または変更する方法

Java で Word で変数の値を変更する

Spire.Doc for Java では、VariableCollection.set() メソッドを使用して変数の値を変更することができます。また、文書内のフィールドを更新した後、変数のすべての出現箇所には新しく割り当てられた値が表示されるため、高速かつ正確なテキストの置換が実現されます。詳細な手順は以下の通りです。

  • Document のオブジェクトを作成します。
  • Document.loaFromFile() メソッドを使用して Word 文書をロードします。
  • Document.getVariables() メソッドを使用して変数コレクションを取得します。
  • VariableCollection.set() メソッドを使用して、名前で特定の変数に新しい値を代入します。
  • Document.isUpdateFields() メソッドを使用して、文書内のフィールドを更新します。
  • Document.saveToFile() メソッドを使用して結果文書を保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.VariableCollection;

public class ChangeVariableValue {
    public static void main(String[] args) {

        //Documentのオブジェクトを作成する
        Document document = new Document();

        //Word文書をロードする
        document.loadFromFile("AddVariables.docx");

        //変数コレクションを取得する
        VariableCollection variableCollection = document.getVariables();

        //変数に値を代入する
        variableCollection.set("Time", "じかん");

        //文書内のフィールドを更新する
        document.isUpdateFields(true);

        //結果文書を保存する
        document.saveToFile("ChangeVariable.docx", FileFormat.Auto);
        document.dispose();
    }
}

Java:Word 文書で変数を追加または変更する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

数式は、物理学、工学、コンピュータ科学、経済学の分野で一般的に使用される数式です。専門的な Word ドキュメントを作成する際、複雑な概念を説明したり、問題を解決したり、特定の議論をサポートしたりするために、数式を含める必要がある場合があります。この記事では、Spire.Doc for Java を使用して、Java プログラムで Word ドキュメントに数式を挿入する方法について説明します。

Spire.Doc for Java をインストールします

まず、Spire.Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.6.0</version>
    </dependency>
</dependencies>

Java で Word ドキュメントに数式を挿入する

Spire.Doc for Java では、OfficeMath.fromLatexMathCode(String latexMathCode) メソッドと OfficeMath.fromMathMLCode(String mathMLCode) メソッドを使用して、LaTeX コードと MathML コードから数式を生成できます。以下に詳細な手順を示します。

  • LaTeX コードと MathML コードから2つの文字列配列を作成します。
  • Document インスタンスを作成し、Document.addSection() メソッドを使用してそれにセクションを追加します。
  • 文字列配列内の各 LaTeX コードを繰り返し処理します。
  • OfficeMath.fromLatexMathCode() メソッドを使用して、LaTeX コードから数式を作成します。
  • そのセクションに段落を追加し、Paragraph.getItems().add() メソッドを使用して段落に数式を追加します。
  • 文字列配列の各 MathML コードを繰り返し処理します。
  • OfficeMath.fromMathMLCode() メソッドを使用して、MathML コードから数式を作成します。
  • そのセクションに段落を追加し、Paragraph.getItems().add() メソッドを使用して段落に数式を追加します。
  • Document.saveToFile() メソッドを使用して、結果のドキュメントを保存します。
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.omath.*;

public class AddMathEquations {
    public static void main(String[] args){

        //LaTeXコードから文字列配列を作成する
        String[] latexMathCode = {
                "x^{2}+\\sqrt{x^{2}+1}=2",
                "\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta",
                "k_{n+1} = n^2 + k_n^2 - k_{n-1}",
                "\\frac {\\frac {1}{x}+ \\frac {1}{y}}{y-z}",
                "\\int_0^ \\infty \\mathrm {e}^{-x} \\, \\mathrm {d}x",
                "\\forall x \\in X, \\quad \\exists y \\leq \\epsilon",
                "\\alpha, \\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi",
                "A_{m,n} = \\begin{pmatrix} a_{1,1} & a_{1,2} & \\cdots & a_{1,n} \\\\ a_{2,1} & a_{2,2} & \\cdots & a_{2,n} \\\\ \\vdots  & \\vdots  & \\ddots & \\vdots  \\\\ a_{m,1} & a_{m,2} & \\cdots & a_{m,n} \\end{pmatrix}",
        };

        //MathMLコードから文字列配列を作成する
        String[] mathMLCode = {
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><mo>≠</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>x</mi><mo>=</mo><mrow><mfrac><mrow><mo>−</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></mrow></math>",
        };

        //ドキュメントのインスタンスを作成する
        Document doc = new Document();

        //セクションを追加する
        Section section = doc.addSection();

        //セクションに段落を追加する
        Paragraph textPara = section.addParagraph();
        textPara.appendText("LaTeXコードから方程式を作成する");
        textPara.applyStyle(BuiltinStyle.Heading_1);
        textPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //文字列配列内の各LaTeXコードに対して繰り返す
        for (int i = 0; i < latexMathCode.length; i++)
        {
            //LaTeXコードから数式を作成する
            OfficeMath officeMath = new OfficeMath(doc);
            officeMath.fromLatexMathCode(latexMathCode[i]);

            //数式をセクションに追加する
            Paragraph paragraph = section.addParagraph();
            paragraph.getItems().add(officeMath);
            section.addParagraph();
        }

        //セクションに段落を追加する
        textPara = section.addParagraph();
        textPara.appendText("MathMLコードから方程式を作成する");
        textPara.applyStyle(BuiltinStyle.Heading_1);
        textPara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //文字列配列内の各MathMLコードに対して繰り返す
        for (int j = 0; j < mathMLCode.length; j++)
        {
            //MathMLコードから数式を作成する
            OfficeMath officeMath = new OfficeMath(doc);
            officeMath.fromMathMLCode(mathMLCode[j]);

            //数式をセクションに追加する
            Paragraph paragraph = section.addParagraph();
            paragraph.getItems().add(officeMath);
            section.addParagraph();
        }

        //結果のドキュメントを保存する
        doc.saveToFile("数式の追加.docx", FileFormat.Docx_2016);
        doc.dispose();
    }
}

Java:Word ドキュメントに数式を挿入する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

目次は、Word 文書内のフィールドで、文書内のすべてのレベルの見出しとそれに対応するページ番号を表示します。さらに、目次は文書の内容に変更が加えられた後に更新することができ、新しい文書の内容に従って新しい見出しとページ番号を生成することができます。したがって、目次は文書を編集するときにも、読むときにも大変便利であり、また、文書をよりプロフェッショナルなものにすることができます。この記事では、Spire.Doc for Java を使用して Word で目次を作成する方法を示します。

Spire.Doc for Java をインストールします

まず、Spire.Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.10.3</version>
    </dependency>
</dependencies>

Java で Word 文書に既定の形式での目次を作成する

目次を作成する前に、各見出しのレベルを設定する必要があります。Spire.Doc for Java では、Paragraph.appendTOC() メソッドを使用して段落に目次を挿入することができます。詳細な手順は以下の通りです。

  • Document クラスのオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して、Word ドキュメントをロードします。
  • Document.addSection() メソッドを使用して、ドキュメントにセクションを追加します。
  • そして、Document.getSections().insert() メソッドを使用して、表紙セクションの後にそのセクションを挿入します。
  • Section.addParagraph() メソッドを使用して、セクションに段落を追加します。
  • Paragraph.appendTOC() メソッドを使用して、段落に目次を作成します。
  • Document.updateTableOfContents() メソッドを使用して、目次を更新して、ドキュメント内の見出しとそのページ番号を表示します。
  • Document.saveToFile() メソッドを使用して結果文書を保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TableOfContent;

public class insertTableOfContents {
    public static void main(String[] args) {

        //Documentクラスのオブジェクトを作成する
        Document doc = new Document();

        //Word文書を読み込む
        doc.loadFromFile("Sample.docx");

        //セクションを追加し、文書の表紙セクションの後に挿入する
        Section section = doc.addSection();
        doc.getSections().insert(1, section);

        //セクションに段落を追加する
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("目次\r\n");
        paragraph.getStyle().getCharacterFormat().setFontSize(12f);

        //段落内に目次を作成する
        paragraph.appendTOC(2, 3);

        //目次を更新する
        doc.updateTableOfContents();

        //結果文書を保存する
        doc.saveToFile("CreateTableOfContents.docx");
    }
}

Java:Word で目次を作成する方法

Java で Word 文書にカスタマ形式での目次を作成する

Spire.Doc for Java では、TableOfContent クラスは Word 文書の目次を表します。目次に表示される部分は、TableOfContent クラスのインスタンスを初期化する際にスイッチを使用してカスタマイズすることができます。例えば、スイッチ "{\\o \"1-3\" \\n 1-2}" は、1から3レベルの見出しを表示し、1と2レベルの見出しのページ番号を省略することを意味します。詳細な手順は以下の通りです。

  • Document クラスのオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して、Wordドキュメントをロードします。
  • Document.getSections().insert() メソッドを使用して、表紙セクションの後にセクションを挿入します。
  • Section.addParagraph() メソッドを使用して、セクションに段落を追加します。
  • TableOfContent クラスのインスタンスを作成して、1から3レベルの見出しを表示し、1と2レベルの見出しのページ番号を省略する目次を作成します。
  • Paragraph.getItems().add() メソッドを使用して、段落に目次を挿入します。
  • Paragraph.appendFieldMark() メソッドを使用して、目次フィールドを終了するためにフィールド区切りマークとフィールド終了マークを段落に挿入します。
  • Document.setTOC() メソッドを使用して、インスタンスを文書の目次として設定します。
  • Document.updateTableOfContents() メソッドを使用して、文書の現在の内容を表示するために目次を更新します。
  • Document.saveToFile() メソッドを使用して、結果文書を保存します。
  • Java
*import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.FieldMarkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TableOfContent;

public class insertTableOfContentsWithCustomizedStyle {
    public static void main(String[] args) {

        //Documentクラスのオブジェクトを作成する
        Document doc = new Document();

        //Word文書を読み込む
        doc.loadFromFile("Sample.docx");

        //最初のセクションの後にセクションを挿入し、そのセクションに段落を追加する
        Section section = doc.addSection();
        doc.getSections().insert(1, section);
        Paragraph paragraph = section.addParagraph();
        paragraph.getStyle().getCharacterFormat().setFontSize(12f);

        //TableOfContent クラスのインスタンスを初期化する
        TableOfContent toc = new TableOfContent(doc, "{\\o \"1-3\" \\n 1-2}");

        //目次を挿入する
        paragraph.getItems().add(toc);

        //フィールドマークを挿入してフィールドを終了する
        paragraph.appendFieldMark(FieldMarkType.Field_Separator);
        paragraph.appendFieldMark(FieldMarkType.Field_End);

        //作成した目次を文書の目次として設定する
        doc.setTOC(toc);

        //目次を更新する
        doc.updateTableOfContents();

        //結果文書を保存する
        doc.saveToFile("TableOfContentsWithCustomizedStyle.docx");
        doc.dispose();
    }
}

Java:Word で目次を作成する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

ドキュメントの作成プロセスでは、レイアウト要件を満たし、論理的な構造を確立するために、ドキュメントのコンテンツを分割する必要があることがよくあります。セクション区切りやページ区切りの挿入は、コンテンツを分割する最も一般的な方法であり、ページやセクションの分割を柔軟に制御することができます。さらに、改ページや改セクションは、ドキュメントの各部分に独自の書式やスタイルを作成する際にも非常に便利です。この記事では、Spire.Doc for Java を使用して、Java プログラムを通じて Word ドキュメントにページ区切りやセクション区切りを挿入する方法を紹介します。

Spire.Doc for Java をインストールします

まず、Spire. Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.8.1</version>
    </dependency>
</dependencies>

Word ドキュメントにページ区切りを挿入する

Spire.Doc for Java には、段落の最後に改ページを挿入するための Paragraph.appendBreak(BreakType.PageBreak) メソッドがあります。 その手順は次のとおりです。

  • Document クラスのオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して、Word ドキュメントを読み込みます。
  • Document.getSections().get() メソッドを使用して、ドキュメントの最初のセクションを取得します。
  • Section.getParagraphs().get() メソッドを使用して、セクションの 8 番目の段落を取得します。
  • Paragraph.appendBreak(BreakType.PageBreak) メソッドを使用して、段落の最後に改ページを追加します。
  • Document.saveToFile() メソッドを使用してドキュメントを保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;

public class InsertPageBreak {
    public static void main(String[] args) {
        //Documentクラスのオブジェクトを作成する
        Document doc = new Document();

        //Word文書を読み込む
        doc.loadFromFile("サンプル.docx");

        //最初のセクションを取得する
        Section section = doc.getSections().get(0);

        //セクション内の8番目の段落を取得する
        Paragraph paragraph = section.getParagraphs().get(7);

        //段落の末尾にページ区切りを追加する
        paragraph.appendBreak(BreakType.Page_Break);

        //文書を保存する
        doc.saveToFile("ページ区切り.docx", FileFormat.Auto);
    }
}

Java:Word 文書にページ区切りとセクション区切りを挿入する方法

Word ドキュメントにセクション区切りを挿入する

セクション区切りを挿入するには、Paragraph.insertSectionBreak(SectionBreakType) メソッドが必要です。次の表は、セクション区切りの種類と、それに対応する列挙型と説明の一覧です。

セクション区切り 列挙型 説明
次のページから開始 SectionBreakType.New_Page 次のページで新しいセクションを開始する。
現在の位置から開始 SectionBreakType.No_Break 同じページで新しいセクションを開始する。
奇数ページから開始 SectionBreakType.Odd_Page 次の偶数ページに新しいセクションを開始する。
偶数ページから開始 SectionBreakType.Even_Page 次の奇数ページに新しいセクションを開始する。
次の段から開始 SectionBreakType.New_Column 次の段で新しいセクションを開始する(段分割が有効になっている必要があります)。

セクション区切りを挿入する詳しい手順は以下の通りです。

  • Document クラスのオブジェクトを作成し ます。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • Document.getSections().get() メソッドを使用して、ドキュメントの最初のセクションを取得します。
  • Section.getParagraphs().get() メソッドを使用して、セクションの 4 番目の段落を取得します。
  • Paragraph.insertSectionBreak(SectionBreakType) メソッドを使用して、段落の最後にセクション区切りを追加します。
  • Document.saveToFile() メソッドを使用して、ドキュメントを保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SectionBreakType;

public class InsertSectionBreak {
    public static void main(String[] args) {
        // Documentクラスのオブジェクトを作成する
        Document doc = new Document();

        // Word文書を読み込む
        doc.loadFromFile("サンプル.docx");

        // 最初のセクションを取得する
        Section section = doc.getSections().get(0);

        // セクション内の4番目の段落を取得する
        Paragraph paragraph = section.getParagraphs().get(3);

        // セクション区切りを挿入する
        paragraph.insertSectionBreak(SectionBreakType.No_Break);

        // 文書を保存する
        doc.saveToFile("セクション区切り.docx", FileFormat.Auto);
    }
}

Java:Word 文書にページ区切りとセクション区切りを挿入する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

チーム作業が必要なかなり長い Word ドキュメントがある場合、作業を効率化するためにドキュメントをいくつかの短いファイルに分割し、それぞれの担当者に割り当てる必要があるかもしれません。この記事では、手作業でカット&ペーストする代わりに、Spire.Doc for Java を使ってプログラムで Word ドキュメントを分割する方法を紹介します。

Spire.Doc for Java をインストールします

まず、Spire. Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.6.0</version>
    </dependency>
</dependencies>

Word ドキュメントを改ページで分割する

Word ドキュメントには、改ページで区切られた複数のページを含めることができます。Word ドキュメントを改ページで分割するには、以下の手順とコードを参照してください。

  • Document のインスタンスを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • 新しい Word ドキュメントを作成し、そこにセクションを追加します。
  • 元のドキュメントの各セクションにあるすべてのボディの子オブジェクトを走査し、子オブジェクトが段落か表かを判断します。
  • セクションの子オブジェクトが表の場合は、Section.getBody().getChildObjects().add() メソッドを使用して、新規ドキュメントのセクションに直接追加します。
  • セクションの子オブジェクトが段落の場合は、まずその段落オブジェクトを新規ドキュメントのセクションに追加します。次に、段落のすべての子オブジェクトを走査し、子オブジェクトが改ページかどうかを判定します。
  • 子オブジェクトが改ページであれば、そのインデックスを取得し、インデックスでその段落から改ページを削除します。
  • 新しい Word ドキュメントを保存し、上記の処理を繰り返します。
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;

public class splitByPageBreak {
    public static void main(String[] args) {

        //Documentのインスタンスを作成する
        Document original = new Document();

        //Wordドキュメントを読み込む
        original.loadFromFile("サンプル.docx");

        //新しいWordドキュメントを作成し、そこにセクションを追加する
        Document newWord = new Document();
        Section section = newWord.addSection();
        int index = 0;

        //原文のすべてのセクションをループする
        for (int s = 0; s < original.getSections().getCount(); s++) {
            Section sec = original.getSections().get(s);

            //各セクションに含まれるボディーの子オブジェクトをすべてループする
            for (int c = 0; c < sec.getBody().getChildObjects().getCount(); c++) {
                DocumentObject obj = sec.getBody().getChildObjects().get(c);
                if (obj instanceof Paragraph) {
                    Paragraph para = (Paragraph) obj;
                    sec.cloneSectionPropertiesTo(section);

                    //元のセクションの段落オブジェクトを新しいドキュメントのセクションに追加する
                    section.getBody().getChildObjects().add(para.deepClone());
                    for (int i = 0; i < para.getChildObjects().getCount(); i++) {
                        DocumentObject parobj = para.getChildObjects().get(i);
                        if (parobj instanceof Break) {
                            Break break1 = (Break) parobj;
                            if (break1.getBreakType().equals(BreakType.Page_Break)) {

                                //段落内の改ページのインデックスを取得する
                                int indexId = para.getChildObjects().indexOf(parobj);

                                //段落から改ページを削除する
                                Paragraph newPara = (Paragraph) section.getBody().getLastParagraph();
                                newPara.getChildObjects().removeAt(indexId);

                                //新しいWordドキュメントを保存する
                                newWord.saveToFile("Output/ドキュメント/ドキュメント"+index+".docx", FileFormat.Docx);
                                index++;

                                //新しいWordドキュメントを作成し、そこにセクションを追加する
                                newWord = new Document();
                                section = newWord.addSection();

                                //元のセクションの段落オブジェクトを新しいドキュメントのセクションに追加する
                                section.getBody().getChildObjects().add(para.deepClone());
                                if (section.getParagraphs().get(0).getChildObjects().getCount() == 0) {

                                    //最初の空白段落を削除する
                                    section.getBody().getChildObjects().removeAt(0);
                                } else {

                                    //改ページの前に子オブジェクトを削除する
                                    while (indexId >= 0) {
                                        section.getParagraphs().get(0).getChildObjects().removeAt(indexId);
                                        indexId--;
                                    }
                                }
                            }
                        }
                    }
                }
                if (obj instanceof Table) {

                    //元のセクションの表のオブジェクトを新しいドキュメントのセクションに追加する
                    section.getBody().getChildObjects().add(obj.deepClone());
                }
            }
        }

        //ドキュメントを保存する
        newWord.saveToFile("Output/ドキュメント/ドキュメント"+index+".docx", FileFormat.Docx);
    }
}

Java:Word ドキュメントを分割する方法

Word ドキュメントをセクション区切りで分割する

Word ドキュメントでは、セクションは独自のページ書式を含むドキュメントの一部です。複数のセクションを含むドキュメントについては、Spire.Doc for Java はセクション区切りによるドキュメントの分割もサポートしています。詳しい手順は以下の通りです。

  • Document のインスタンスを作成します。
  • Document.LoadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • 新しい Word ドキュメントのオブジェクトを定義します。
  • 元の Word ドキュメントのすべてのセクションを走査します。
  • Section.deepClone() メソッドを使用して、元のドキュメントの各セクションをクローンします。
  • Document.getSections().add() メソッドを使用して、コピーしたセクションを新しいセクションとして新しいドキュメントに追加します。
  • Document.saveToFile() メソッドを使用して、結果のドキュメントを保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.Section;

public class splitBySectionBreak {
    public static void main(String[] args) {

        //Documentのインスタンスを作成する
        Document document = new Document();

        //Word ドキュメントを読み込む
        document.loadFromFile("サンプル.docx");

        //新しいWordドキュメントのオブジェクトを定義する
        Document newWord;

        //元のWordドキュメントのすべてのセクションをループする
        for (int i = 0; i < document.getSections().getCount(); i++) {
            newWord = new Document();

            //元の文書の各セクションをコピーし、新しいセクションとして新しい文書に追加する
            newWord.getSections().add(document.getSections().get(i).deepClone());

            //結果ドキュメントを保存する
            newWord.saveToFile("ドキュメント1/ドキュメント" + i + ".docx");
        }
    }
}

Java:Word ドキュメントを分割する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

ドキュメントのプロパティとは、タイトル、サブタイトル、作成者、会社名、キーワードなど、Word ドキュメントに含まれるいくつかの重要な情報です。この情報を読み取ることで、ドキュメントの特定、ドキュメントの種類や出所の迅速な確認、ドキュメントの保管や整理の効率化などに役立てることができます。ただし、作成者や会社名などの文書のプロパティが他人に知られることが不適切な場合は、プライバシー保護のために削除することができます。この記事では、Spire.Doc for Java を使用して、プログラム的に Word ドキュメントのプロパティを読んだり削除したりする方法を紹介します。

Spire.Doc for Java をインストールします

まず、Spire. Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.5.5</version>
    </dependency>
</dependencies>

Word 文書から組み込みとユーザー定義のプロパティを読み取る

Word ドキュメントには、組み込みのプロパティとユーザー定義のプロパティの2種類があります。組み込みプロパティとは、あらかじめ定義されたプロパティのことで、ユーザー定義プロパティとは、名前、型、値などをカスタマイズしたプロパティのことです。この2種類の文書プロパティを読み取るための詳細な手順は、以下の通りです。

  • Document のオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • Document.getBuiltinDocumentProperties() メソッドと Document.getCustomDocumentProperties() メソッドを使用して、すべての組み込みプロパティとユーザー定義プロパティを取得します。
  • BuiltinDocumentProperties クラスのメソッドを使用して、各ビルトインプロパティを取得します。
  • CustomDocumentProperties クラスのメソッドを使って、ユーザー定義プロパティをループして、その名前と値を取得します。
  • Java
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;

public class GetDocumentProperties {
    public static void main(String[] args) {

        //Documentのオブジェクトを作成する
        Document document = new Document();

        //Wordドキュメントを読み込む
        document.loadFromFile("C:/サンプル.docx");

        //StringBuilderのオブジェクトを作成する
        StringBuilder properties = new StringBuilder();

        //すべての組み込みプロパティとユーザー定義プロパティを取得する
        BuiltinDocumentProperties builtinDocumentProperties = document.getBuiltinDocumentProperties();
        CustomDocumentProperties customDocumentProperties = document.getCustomDocumentProperties();

        //各組み込みプロパティを取得する
        String title = builtinDocumentProperties.getTitle();
        String subject = builtinDocumentProperties.getSubject();
        String author = builtinDocumentProperties.getAuthor();
        String manager = builtinDocumentProperties.getManager();
        String category = builtinDocumentProperties.getCategory();
        String company = builtinDocumentProperties.getCompany();
        String keywords = builtinDocumentProperties.getKeywords();
        String comments = builtinDocumentProperties.getComments();

        //表示する文字列の形式を設定する
        String builtinProperties = String.format("組み込みのプロパティ:\r\nタイトル:" + title
                + "\r\nサブタイトル:" + subject + "\r\n作成者:" + author
                + "\r\n管理者:" + manager + "\r\n分類:" + category
                + "\r\n会社名:" + company + "\r\nキーワード:"+ keywords
                + "\r\nコメント:" + comments
        );

        //StringBuilderのオブジェクトに組み込みのプロパティを追加する
        properties.append(builtinProperties);

        //各ユーザー定義プロパティを取得する
        properties.append("\r\n\r\nユーザー定義のプロパティ:");
        for (int i = 0; i < customDocumentProperties.getCount(); i++) {
            String customProperties = String.format("\r\n" + customDocumentProperties.get(i).getName() + ":" + document.getCustomDocumentProperties().get(i).getValue());

            //StringBuilderのオブジェクトにユーザー定義のプロパティを追加する
            properties.append(customProperties);
        }

        //ドキュメントのプロパティを出力する
        System.out.println(properties);
    }
}

Java:Word ドキュメントのプロパティの読み取りと削除

Word 文書から組み込みとユーザー定義のプロパティを削除する

組み込みのドキュメントのプロパティは、その値を空に設定することで削除することができます。ユーザー定義のドキュメントのプロパティについては、CustomDocumentProperties.get().getName() メソッドで名前を取得し、CustomDocumentProperties.remove() メソッドを使用して削除することができます。詳しい手順は以下の通りです。

  • Document のオブジェクトを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • Document.getBuiltinDocumentProperties() メソッドと Document.getCustomDocumentProperties() メソッドを使用して、すべての組み込みプロパティとユーザー定義プロパティを取得します。
  • BuiltinDocumentProperties クラスのメソッドを使用して、値を空にして組み込みプロパティを削除します。
  • CustomDocumentProperties.getCount() メソッドを使用して、ユーザー定義プロパティの件数を取得します。
  • CustomDocumentProperties.get().getName() メソッドを使用してユーザー定義プロパティをループして名前を取得し、CustomDocumentProperties.remove() メソッドを使用して名前によって各ユーザー定義プロパティを削除します。
  • Document.saveToFile() メソッドを使用して、ドキュメントを保存します。
  • Java
import com.spire.doc.BuiltinDocumentProperties;
import com.spire.doc.CustomDocumentProperties;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveDocumentProperties {
    public static void main(String[] args) {

        //Documentのオブジェクトを作成する
        Document document = new Document();

        //Wordドキュメントを読み込む
        document.loadFromFile("C:/サンプル.docx");

        //すべての組み込みプロパティとユーザー定義プロパティを取得する
        BuiltinDocumentProperties builtinDocumentProperties = document.getBuiltinDocumentProperties();
        CustomDocumentProperties customDocumentProperties = document.getCustomDocumentProperties();

        //組み込みプロパティの値を空に設定することで削除する
        builtinDocumentProperties.setTitle("");
        builtinDocumentProperties.setSubject("");
        builtinDocumentProperties.setAuthor("");
        builtinDocumentProperties.setManager("");
        builtinDocumentProperties.setCompany("");
        builtinDocumentProperties.setCategory("");
        builtinDocumentProperties.setKeywords("");
        builtinDocumentProperties.setComments("");

        //ユーザー定義プロパティの件数を取得する
        int count = customDocumentProperties.getCount();

        //ユーザー定義プロパティをループして削除する
        for (int i = count; i > 0; i-- ){

            //ユーザー定義プロパティの名前を取得する
            String name = customDocumentProperties.get(i-1).getName();

            //ユーザー定義プロパティをその名前で削除する
            customDocumentProperties.remove(name);
        }

        //ドキュメントを保存する
        document.saveToFile("ドキュメントのプロパティの削除.docx", FileFormat.Auto);
        document.dispose();
    }
}

Java:Word ドキュメントのプロパティの読み取りと削除

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

変更履歴とは、Word ドキュメントの機能で、ドキュメントに加えられたすべての変更を確認し、その変更を承諾するか元に戻すかを決定することができるものです。特に、同じ契約書や学校の課題で複数の人と共同作業をしている場合に非常に便利です。この記事では、Spire.Doc for Java を使用して、Word ドキュメントで変更履歴をすべて承諾または元に戻す方法について説明します。

Spire.Doc for Java をインストールします

まず、Spire. Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.4.2</version>
    </dependency>
</dependencies>

Word ドキュメントですべての変更履歴を承諾する

詳しい手順は以下の通りです。

  • Document のインスタンスを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • Document.acceptChanges() メソッドを使用して、ドキュメントのすべての変更を承諾します。
  • Document.saveToFile() メソッドを使用してドキュメントを保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class AcceptTrackedChanges {
    public static void main(String[] args) {

        //Documentのインスタンスを作成する
        Document doc = new Document();

        //Wordドキュメントを読み込む
        doc.loadFromFile("C:/変更履歴.docx");

        //ドキュメントのすべての変更を承諾する
        doc.acceptChanges();

        //ドキュメントを保存する
        doc.saveToFile("すべての変更の承諾.docx", FileFormat.Docx);
    }
}

Java:Word ドキュメントで変更履歴を承諾または元に戻す方法

Word ドキュメントですべての変更履歴を元に戻す

詳しい手順は以下の通りです。

  • Document のインスタンスを作成します。
  • Document.loadFromFile() メソッドを使用して Word ドキュメントを読み込みます。
  • Document.rejectChanges() メソッドを使用して、ドキュメント内のすべての変更を元に戻します。
  • Document.saveToFile() メソッドを使用してドキュメントを保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RejectTrackedChanges {
    public static void main(String[] args) {

        //Documentのインスタンスを作成する
        Document doc = new Document();

        //Wordドキュメントを読み込む
        doc.loadFromFile("C:/変更履歴.docx");

        //ドキュメントのすべての変更を元に戻す
        doc.rejectChanges();

        //ドキュメントを保存する
        doc.saveToFile("すべての変更を元に戻す.docx", FileFormat.Docx);
    }
}

Java:Word ドキュメントで変更履歴を承諾または元に戻す方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作

ドキュメントの比較とは、異なる貢献者による変更を識別するために、新しいバージョンのドキュメントを以前のコピーと照合するプロセスです。これらの違いには、単語、文章、段落の追加や削除、書式の調整などが含まれます。この記事では、Spire.Doc for Java を使用して、Java で2つの Word ドキュメントを比較する方法について説明します。

以下は、比較対象となる2つの Word ドキュメントの表示画像です。

Java:2つの Word ドキュメントを比較する方法

Spire.Doc for Java をインストールします

まず、Spire. Doc for Java を Java プロジェクトに追加する必要があります。JAR ファイルは、このリンクからダウンロードできます。Maven を使用する場合は、次のコードをプロジェクトの pom.xml ファイルに追加する必要があります。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.4.2</version>
    </dependency>
</dependencies>

2つのドキュメントを比較し、結果を保存する

比較結果を別の Word ドキュメントに保存すると、挿入、削除、書式の変更など、元のドキュメントに加えられたすべての変更を確認することができます。以下は、Spire.Doc for Java を使用して、2つのドキュメントを比較し、その結果を3つ目の Word ドキュメントに保存する手順です。

  • Document のオブジェクトを2つ作成します。
  • Document.loadFromFile() メソッドを用いて、2つの Word ドキュメントを読み込みます。
  • Document.compare() メソッドを使用して、2つのドキュメントを比較します。
  • Document.saveToFile() メソッドを使用して、結果を3番目の Word ドキュメントに保存します。
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class CompareDocuments {

    public static void main(String[] args) {

        //Documentのオブジェクトを2つ作成する
        Document doc1 = new Document();
        Document doc2 = new Document();

        //Wordドキュメントを読み込む
        doc1.loadFromFile("C:/比較1.docx");

        //他のWordドキュメントを読み込む
        doc2.loadFromFile("C:/比較2.docx");

        //2つのドキュメントを比較する
        doc1.compare(doc2, "John");

        //相違点を第3のドキュメントに保存する
        doc1.saveToFile("相違点.docx", FileFormat.Docx_2013);
        doc1.dispose();
    }
}

Java:2つの Word ドキュメントを比較する方法

2つのドキュメントを比較し、挿入と削除を返す

時には、全体の差分ではなく、挿入と削除だけを気にすることがあります。以下は、2つのリストで挿入と削除を取得する手順です。

  • Document のオブジェクトを2つ作成する。
  • Document.loadFromFile() メソッドを使用して、2つの Word ドキュメントを読み込みます。
  • Document.compare() メソッドを使用して、2つのドキュメントを比較します。
  • DifferRevisions のコンストラクタ関数を使用して、リビジョンを取得します。
  • DifferRevisions.getInsertRevisions() メソッドを使用して、挿入のリストを取得します。
  • DifferRevisions.getDeleteRevisions() メソッドを使用して削除のリストを取得します。
  • 2つのリストの要素をループして、特定の挿入と削除を取得します。
  • Java
import com.spire.doc.DifferRevisions;
import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.fields.TextRange;
import com.spire.ms.System.Collections.Generic.List;

public class CompareReturnResultsInLists {

    public static void main(String[] args) {

        //Documentのオブジェクトを2つ作成する
        Document doc1 = new Document();
        Document doc2 = new Document();

        //Wordドキュメントを読み込む
        doc1.loadFromFile("C:/比較1.docx");

        //他のWordドキュメントを読み込む
        doc2.loadFromFile("C:/比較2.docx");

        //2つのWordドキュメントを比較する
        doc1.compare(doc2, "Author");

        //改訂を取得する
        DifferRevisions differRevisions = new DifferRevisions(doc1);

        //挿入改訂をリストで返す
        List insertRevisionsList = differRevisions.getInsertRevisions();

        //削除改訂をリストで返す
        List  deleteRevisionsList = differRevisions.getDeleteRevisions();

        //2つのint変数を作成する
        int m = 0;
        int n = 0;

        //挿入改訂リストをループする
        for (int i = 0; i < insertRevisionsList.size(); i++)
        {
            if (insertRevisionsList.get(i) instanceof TextRange)
            {
                m += 1;
                //特定の改訂を取得し、その内容を取得する
                TextRange textRange = (TextRange)insertRevisionsList.get(i) ;
                System.out.println("挿入 #" + m + ":" + textRange.getText());
            }
        }
        System.out.println("============================================");
        //削除改訂リストをループする
        for (int i = 0; i < deleteRevisionsList.size() ; i++)
        {
            if (deleteRevisionsList.get(i) instanceof TextRange)
            {
                n += 1;
                //特定の改訂を取得し、その内容を取得する
                TextRange textRange = (TextRange) deleteRevisionsList.get(i) ;
                System.out.println("削除 #" + n + ":" + textRange.getText());
            }
        }
    }
}

Java:2つの Word ドキュメントを比較する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Published in 文書操作
1 / 2