tech.chakapoko.com
Home / Java / Apache PDFBox

[Java]PDFBoxで文字を表示する

ビルトインのフォントを使う

package com.example;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.File;

public class PDFBoxExample {

    public static void main(String[] args) {
        try (PDDocument pdDocument = new PDDocument()) {
            PDPage pdPage = new PDPage();

            pdDocument.addPage(pdPage);

            float pageHeight = pdPage.getMediaBox().getHeight();

            try (PDPageContentStream stream = new PDPageContentStream(pdDocument, pdPage)) {
                PDFont font = PDType1Font.HELVETICA;
                stream.beginText();
                stream.setFont(font, 12);
                stream.newLineAtOffset(100f, pageHeight - 100f);
                stream.showText("Hello");
                stream.endText();
            }

            pdDocument.save(new File("Example.pdf"));
        }
    }

}

display-text.png

カスタムフォントを使う

package com.example;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

class PDFBoxExample {

    public static void main(String[] args) throws IOException {
        try (PDDocument pdDocument = new PDDocument()) {
            PDPage pdPage = new PDPage();

            pdDocument.addPage(pdPage);

            float pageHeight = pdPage.getCropBox().getHeight();

            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            try (PDPageContentStream stream = new PDPageContentStream(pdDocument, pdPage);
                 InputStream in = classLoader.getResourceAsStream("ipaexg.ttf")) {
                PDFont font = PDType0Font.load(pdDocument, in);
                stream.beginText();
                stream.setFont(font, 12);
                stream.newLineAtOffset(100f, pageHeight - 100f);
                stream.showText("こんにちは");
                stream.endText();
            }

            pdDocument.save(new File("Example.pdf"));
        }
    }

}

display-text2.png