Created
October 16, 2025 14:53
-
-
Save hikaMaeng/22bfccb9fed3e7263a00c0f490253b13 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package kore.pdf | |
| import com.itextpdf.html2pdf.ConverterProperties | |
| import com.itextpdf.html2pdf.HtmlConverter | |
| import com.itextpdf.io.font.FontProgramFactory | |
| import com.itextpdf.io.source.ByteArrayOutputStream | |
| import com.itextpdf.kernel.geom.PageSize | |
| import com.itextpdf.kernel.pdf.PdfDocument | |
| import com.itextpdf.kernel.pdf.PdfWriter | |
| import com.itextpdf.layout.font.FontProvider | |
| import java.net.URL | |
| /** | |
| * HTML2Pdf | |
| * | |
| * HTML 문자열을 PDF로 변환하는 유틸리티 클래스입니다. | |
| * | |
| * @param fontUrls PDF에 사용할 폰트 파일의 URL 리스트 (기본값: 빈 리스트) | |
| * | |
| * 주요 기능: | |
| * - HTML을 PDF로 변환 | |
| * - 커스텀 폰트 적용 가능 | |
| * - PDF 페이지 크기 지정 가능 | |
| */ | |
| class HTML2Pdf(fontUrls: List<URL> = emptyList()) { | |
| /** | |
| * PDF 페이지 크기를 지정하는 데이터 클래스 | |
| * @property width 페이지의 너비 | |
| * @property height 페이지의 높이 | |
| */ | |
| data class Size(val width: Float, val height: Float) | |
| /** | |
| * 폰트 URL 리스트에서 폰트 프로그램 객체를 생성하여 보관 | |
| */ | |
| val fonts = fontUrls.map { woffBytes -> | |
| FontProgramFactory.createFont(woffBytes.readBytes()) | |
| } | |
| /** | |
| * HTML 문자열을 PDF로 변환합니다. | |
| * | |
| * @param html 변환할 HTML 문자열 | |
| * @param size PDF 페이지 크기 (null이면 기본값 사용) | |
| * @return 변환된 PDF의 바이트 배열 | |
| */ | |
| fun convert(html: String, size:Size? = null): ByteArray { | |
| val fontProvider = FontProvider() | |
| fonts.forEach { fontProvider.addFont(it) } | |
| val properties = ConverterProperties() | |
| properties.fontProvider = fontProvider | |
| val pdfFileOutputStream = ByteArrayOutputStream() | |
| val pdfDocument = PdfDocument(PdfWriter(pdfFileOutputStream)) //pdf 생성 | |
| size?.let { | |
| pdfDocument.defaultPageSize = PageSize(it.width, it.height) // PDF 기본 페이지 크기 설정 | |
| } | |
| HtmlConverter.convertToPdf(html, pdfDocument, properties) | |
| pdfDocument.close() | |
| return pdfFileOutputStream.toByteArray() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment