HOWTO · Java

JavaでPDFを結合

このチュートリアルでは、Java での PDF のマージについて説明します。

このページの内容

場合によっては、複数の PDF ファイルを結合して 1つの PDF ファイルにマージする必要があります。 このタスクは、Java で最も人気のある Apache ライブラリ PDFBox を使用して簡単に実行できます。

この記事では、Java で複数の PDF ファイルをマージする方法と、トピックを明確にするために必要な例と説明を示します。

PDFBox を使用して Java で PDF をマージする

以下の例では、PDFBox を使用して 2つの異なる PDF をマージする方法を示します。

以下の内容の 2つの PDF ファイルがあるとします。

PDF_1.pdf

This is line 1 of pdf 1
This is line 2 of pdf 1
This is line 3 of pdf 1
This is line 4 of pdf 1

PDF_2.pdf

This is line 1 of pdf 2
This is line 2 of pdf 2
This is line 3 of pdf 2
This is line 4 of pdf 2

これらの PDF ファイルの両方をマージする例のコードは次のようになります。

import java.io.File;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

public class App {
  public static void main(String[] args) throws Exception {
    File f1 = new File("G:/PDF_1.pdf"); // Locating file 1
    File f2 = new File("G:/PDF_2.pdf"); // Locating file 2

    PDFMergerUtility MrgPdf = new PDFMergerUtility(); // Creating an object for PDFMergerUtility
    // Setting the destination where the merged file will be created
    MrgPdf.setDestinationFileName("G:/mergedPDF.pdf");

    // Adding the source files
    MrgPdf.addSource(f1);
    MrgPdf.addSource(f2);

    // Merging files in one single document
    MrgPdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

    // Showing an output to the user that the files are successfully merged

    System.out.println("PDF merged successfully !!!");
  }
}

各行の目的はコメントとして残されています。 上記の例を実行すると、以下のような出力が得られます。

PDF merged successfully !!!

そして、マージされた PDF ファイルが、以下の内容で提供されたディレクトリに作成されていることがわかります。

Page 1:
This is line 1 of pdf 1
This is line 2 of pdf 1
This is line 3 of pdf 1
This is line 4 of pdf 1

Page 2:
This is line 1 of pdf 2
This is line 2 of pdf 2
This is line 3 of pdf 2
This is line 4 of pdf 2