Programming/JAVA

[openhtmltopdf] HTML을 PDF로 변환하기

빈쿵바라기 2023. 1. 18. 17:06

공식 GitHub URL : https://github.com/danfickle/openhtmltopdf

1. Dependency 추가

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>
<dependency>
    <groupId>com.openhtmltopdf</groupId>
    <artifactId>openhtmltopdf-core</artifactId>
    <version>1.0.6</version>
</dependency>
<dependency>
    <groupId>com.openhtmltopdf</groupId>
    <artifactId>openhtmltopdf-pdfbox</artifactId>
    <version>1.0.6</version>
</dependency>

 

2. Sample code

// html 파일
ClassPathResource resource = new ClassPathResource("pdf/industry-application.html");

String outputFile = "output.pdf";

// HTML 읽기
String html = new String(Files.readAllBytes(Paths.get(resource.getFile().getAbsolutePath())));
Document document = Jsoup.parse(html);

// HTML 수정하기
document.getElementById("name").val("빈쿵");

// PDF 생성
try (OutputStream os = new FileOutputStream(outputFile)) {
    PdfRendererBuilder builder = new PdfRendererBuilder();

    // 폰트 추가
    builder.useFont(new ClassPathResource("font/malgunsl.ttf").getFile(), "Malgun Gothic");
    builder.useFont(new ClassPathResource("font/NotoEmoji-Regular.ttf").getFile(), "Noto Emoji");

    builder.toStream(os);
    builder.withW3cDocument(new W3CDom().fromJsoup(document), "/");
    builder.run();
}

 

Tip

  • HTML의 style을 normalize 하고 작업할 것
  • font 파일은 os마다 없는 폰트가 존재하기 때문에 프로젝트내 resource에 위치하여 사용할 것
  • css font-family의 지정 이름과 builder.userFont()의 fontFamily parma을 맞춰줄 것
  • input 태그를 활용하려면 form 태그로 감싸줄 것
  • A4 용지 맞추기 위해서는 아래의 코드를 style에 추가해줄 것
@page {
    margin: 0%;
    size: A4 portrait;
}