HTML을 PDF로 변환

lsm·2024년 3월 15일

PDF&메타데이터

목록 보기
2/6

HTML → PDF 변환

  • IText PDF 라이브러리 사용
    • 라이센스의 경우 Itext7를 사용한 소스 코드에 대한 요청 시 공개 할 수 있어야 함. 그렇지 않다면 유료 라이센스를 구매하여 사용.
  • HTML 파일 경로, 생성될 PDF 파일 경로, 폰트 경로를 입력 받아 HTML 파일을 PDF로 변환. ConverterPropertiesFontProvider를 사용하여 폰트 경로를 설정하고, 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 객체 
        File htmlFile = new File(htmlFilePath);
        
        // HTML 파일 존재 확인
        if (!htmlFile.exists()) {
            System.err.println("Html 파일이 존재하지 않습니다.: " + htmlFilePath);
            return;
        }

        // 설정을 담는 ConverterProperties 객체 
        ConverterProperties converterProperties = new ConverterProperties();
        // 폰트 관리 FontProvider 객체 
        FontProvider fontProvider = new FontProvider();
        // FontProvider에 폰트 경로 추가
        fontProvider.addFont(fontPath);
        // ConverterProperties에 FontProvider 값 설정
        converterProperties.setFontProvider(fontProvider);

        try (
            // HTML 파일 읽기  
            FileInputStream htmlStream = new FileInputStream(htmlFilePath);
            // PDF 파일 쓰기  
            FileOutputStream pdfStream = new FileOutputStream(pdfFilePath)
        ) {
            // HTML을 PDF로 변환
            HtmlConverter.convertToPdf(htmlStream, pdfStream, converterProperties);
            System.out.println("PDF 파일이 생성되었습니다: " + pdfFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // PDF 파일에 커스텀 메타데이터를 추가하는 메소드 호출
             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);
	}
}

0개의 댓글