
この記事では、http://developers.itextpdf.com/[iText PDF]ライブラリを使用してPDFを読み書きする方法について説明します。
pom.xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
P.S iTextPdf 5.5.10
でテスト済み
1. iText – PDFを書く
iText PDFファイルに内容を書き込む `PdfWriter`の例です。
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`
2. iText – PDFを読む
PDFファイルの上にあるiText `PdfReader`の例です。
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.トーク
上記のコードでは、2つの主要クラス、
PdfWriter`と
PdfReader`を使用しています。名前で示されるように、これらのクラスはpdfの読み書きの基盤を提供します。 `Document`オブジェクトは、基本的に対処されているPdfファイルです。 `Paragraph`はPdfに書き込むことができるコンテンツタイプです。
他の可能なコンテンツタイプには、アンカー、章、セクション、リスト、PdfPTableなどがあります。
iText pdfは、最新バージョンでHTML to Pdf、Image to Pdf、QRコードをサポートする最も便利なライブラリです。 iTextのpdfライブラリの唯一の欠点は、それを扱うのが複雑であることです。
クラス構造は理解するのが難しいです。
参考文献
iText Pdfコーディングについて]。
http://www.java2s.com/Code/Jar/i/Downloaditextpdf510jar.htm
[iText Pdf
jarダウンロード]。
https://www.gnostice.com/nl
article.asp?id=101&t=How
to
Read
and
Write
PDF
Files
in__Java[Write
PdfOneライブラリを用いたPdf]。
https://asprise.com/product/javapdf/index.php
[Pdf操作の使用
JavaのAspire Pdf]
リンク://タグ/itext/[itext]リンク://タグ/java-io/[java.io]
pdf