HTML → PDF 변환
- IText PDF 라이브러리 사용
- 라이센스의 경우 Itext7를 사용한 소스 코드에 대한 요청 시 공개 할 수 있어야 함. 그렇지 않다면 유료 라이센스를 구매하여 사용.
- HTML 파일 경로, 생성될 PDF 파일 경로, 폰트 경로를 입력 받아 HTML 파일을 PDF로 변환.
ConverterProperties와 FontProvider를 사용하여 폰트 경로를 설정하고, HtmlConverter.convertToPdf 메소드를 사용하여 실제 변환 작업을 수행
- 변환 과정이 완료된 후,
finally 에서 AddCustomMetadata.addCustomMetadata 메소드를 호출
- 폰트를 지정해 주지 않았을 때 한글이 나오지 않던 문제가 발생하여 폰트 지정
public class HtmlToPdfConverter {
private HtmlToPdfConverter() {
throw new IllegalStateException("Utility class");
}
public static void convertHtmlToPdf(String htmlFilePath, String pdfFilePath, String fontPath) {
File htmlFile = new File(htmlFilePath);
if (!htmlFile.exists()) {
System.err.println("Html 파일이 존재하지 않습니다.: " + htmlFilePath);
return;
}
ConverterProperties converterProperties = new ConverterProperties();
FontProvider fontProvider = new FontProvider();
fontProvider.addFont(fontPath);
converterProperties.setFontProvider(fontProvider);
try (
FileInputStream htmlStream = new FileInputStream(htmlFilePath);
FileOutputStream pdfStream = new FileOutputStream(pdfFilePath)
) {
HtmlConverter.convertToPdf(htmlStream, pdfStream, converterProperties);
System.out.println("PDF 파일이 생성되었습니다: " + pdfFilePath);
} catch (IOException e) {
e.printStackTrace();
} finally {
AddCustomMetadata.addCustomMetadata(pdfFilePath);
}
}
public static void main(String[] args) {
String htmlFilePath = "D:/MakePdf/workspace/PDF/exam9.html";3
String pdfFilePath = "D:/MakePdf/workspace/PDF/outputPdf.pdf";
String fontPath = "D:/MakePdf/workspace/PDF/NanumGothic.otf";
convertHtmlToPdf(htmlFilePath,pdfFilePath,fontPath);
}
}