iText - JavaでPDFを読み書きする

iText – JavaでPDFを読み書きする

itext-logo

この記事では、iText PDFライブラリを使用したPDFの読み取りと書き込みについて説明します。

pom.xml

        
            com.itextpdf
            itextpdf
            5.5.10
        

P.S Tested with iTextPdf 5.5.10

1. iText – PDFを書く

PDFファイルにコンテンツを書き込むiTextPdfWriterの例。

PdfWriteExample.java

package com.techfou;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class PdfWriteExample {

    private static final String FILE_NAME = "/tmp/itext.pdf";

    public static void main(String[] args) {
        writeUsingIText();
    }

    private static void writeUsingIText() {

        Document document = new Document();

        try {

            PdfWriter.getInstance(document, new FileOutputStream(new File(FILE_NAME)));

            //open
            document.open();

            Paragraph p = new Paragraph();
            p.add("This is my paragraph 1");
            p.setAlignment(Element.ALIGN_CENTER);

            document.add(p);

            Paragraph p2 = new Paragraph();
            p2.add("This is my paragraph 2"); //no alignment

            document.add(p2);

            Font f = new Font();
            f.setStyle(Font.BOLD);
            f.setSize(8);

            document.add(new Paragraph("This is my paragraph 3", f));

            //close
            document.close();

            System.out.println("Done");

        } catch (FileNotFoundException | DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

出力、新しいPDFファイルが作成されます–/tmp/itext.pdf

itext-pdf-example

2. iText – PDFを読む

上記のPDFファイルを読み取るiTextPdfReaderの例。

PdfReadExample.java

package com.techfou;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

import java.io.IOException;

public class PdfReadExample {

    private static final String FILE_NAME = "/tmp/itext.pdf";

    public static void main(String[] args) {

        PdfReader reader;

        try {

            reader = new PdfReader("f:/itext.pdf");

            // pageNumber = 1
            String textFromPage = PdfTextExtractor.getTextFromPage(reader, 1);

            System.out.println(textFromPage);

            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

出力

This is my paragraph 1
This is my paragraph 2
This is my paragraph 3

3. Talk

上記のコードは、PdfWriterPdfReaderの2つの主要なクラスを使用しています。 名前が示すように、これらのクラスはpdfの読み取りおよび書き込みのベースを提供します。 Documentオブジェクトは、基本的にアドレス指定されているPdfファイルです。 Paragraphは、PDFに書き込むことができるコンテンツタイプです。 他の可能なコンテンツタイプには、AnchorChapterSectionListPdfPTableなどがあります。 これらのクラスはすべて、pdfの要件に従って特定の種類のコンテンツを作成するのに役立ちます。

iText pdfは、HTML to Pdf、Image to Pdf、およびQRコードをサポートする最新バージョンの最も便利なライブラリです。 iText pdfライブラリの唯一の欠点は、それを操作するのが複雑なことです。 クラス構造は理解するのが難しいです。

Note
その他のiText PDF examples