공식 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;
}
'Programming > JAVA' 카테고리의 다른 글
JAVA SHA-256 암호화 방법 (0) | 2023.05.10 |
---|---|
[Apache VFS] SFTP 파일 업로드 (0) | 2023.03.08 |
[Apache Tika] 문서파일에서 텍스트 추출하기 (0) | 2022.12.15 |
애니메이션 이미지인지 아닌지 체크하는 방법(Check image animated or not in JAVA) (0) | 2022.09.16 |
[BufferedImage] 이미지 이진화(Image Binarize) (0) | 2022.09.16 |