PDF生成のためのライブラリ選択肢
Spring BootアプリケーションでPDFを生成するには、複数のライブラリを利用可能です。以下に代表的な実装方法を紹介します。
1. Apache PDFBoxの利用
Apache PDFBoxはPDFの生成・編集が可能なオープンソースライブラリです。基本的な実装手順は以下の通りです:
- PDDocumentインスタンスの作成
- ページ追加とコンテンツストリームの設定
- テキスト描画とフォント指定
- ファイルへの保存処理
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class PdfBoxSample {
public static void main(String[] args) {
try (PDDocument pdfDoc = new PDDocument()) {
PDPage page = new PDPage();
pdfDoc.addPage(page);
try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page)) {
contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
contentStream.beginText();
contentStream.newLineAtOffset(50, 700);
contentStream.showText("PDFBoxサンプルドキュメント");
contentStream.endText();
}
pdfDoc.save("sample_output.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. iText7の利用
iText7は高度なPDF操作を可能にするライブラリです。Spring Bootでの実装例:
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
@Service
public class ITextPdfService {
public void createPdf(String filePath) throws Exception {
PdfWriter writer = new PdfWriter(filePath);
Document document = new Document(writer);
document.add(new Paragraph("iText7によるPDF生成"));
document.close();
}
}
3. HTMLテンプレートからの変換
HTMLコンテンツをPDFに変換するユースケースに適した方法:
@Service
public class HtmlPdfService {
public byte[] convertHtmlToPdf(String htmlContent) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfRendererBuilder builder = new PdfRendererBuilder();
builder.withHtmlContent(htmlContent, null);
builder.toStream(byteArrayOutputStream);
builder.run();
return byteArrayOutputStream.toByteArray();
}
}
4. ReportLabの利用
Python開発者にも馴染み深いPDF生成ライブラリ:
@RestController
@RequestMapping("/report")
public class ReportLabController {
@GetMapping("/generate")
public ResponseEntity generate() {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("report.pdf"));
doc.open();
doc.add(new Paragraph("レポート生成完了"));
doc.close();
return ResponseEntity.ok("PDF作成完了");
}
}
5. テンプレートベースのPDF生成
事前定義されたフォーマットに動的データを埋め込む場合:
public class TemplatePdfGenerator {
public void generateWithTemplate(String outputPath, Map data) throws Exception {
PdfDocument pdf = new PdfDocument(new PdfWriter(outputPath));
Document document = new Document(pdf);
document.add(new Paragraph("契約書"));
document.add(new Paragraph("契約日:" + data.get("date")));
document.add(new Paragraph("取引先:" + data.get("client")));
document.close();
}
}