본문 바로가기
JAVA

pd4ml을 이용하여 PDF 생성하기

by IT History 2021. 6. 29.
728x90
반응형

HTML 태그를 입력 받아 PDF로 변환해주는 예제 입니다.

 

pd4ml_demo.jar 및 fonts.jar 라이브러리를 활용 하였습니다.

 

참고 : https://pd4ml.com/index.htm

public void pd4ml() throws Exception{
	String editor = request.getParameter("editor");

	String HtmlString = "";
	editor = editor.replaceAll("&lt;", "<");
	editor = editor.replaceAll("&gt;", ">");
	editor = editor.replaceAll("&quot;", "'");
	editor = editor.replaceAll("&middot;", "·");
        
	HtmlString = "<html>" + "<body>"
        	   + "<font face=\"gulim\">" 
        	   + editor 
        	   + "</font></body>" 
        	   + "</html>";
               
	if(!pd4mlTEst(htmlText)) {
		return;
	};
}


public boolean pd4mlTEst(String HtmlString) throws InvalidParameterException, MalformedURLException, IOException {
	int topValue = 10;  
	int leftValue = 20;  
	int rightValue = 10;  
	int bottomValue = 10;  
	int userSpaceWidth = 750;  
	String url = "";
	String outputPath = "D:/fileTest/pd4ml.pdf";

	File output = new File(outputPath);  
	FileOutputStream fos = new FileOutputStream(output);  
        
	PD4ML pd4ml = new PD4ML();  
	pd4ml.setHtmlWidth(userSpaceWidth); // set frame width of "virtual web browser"   
	// choose target paper format and "rotate" it to landscape orientation  
	pd4ml.setPageSize(PD4Constants.A4);   
	// define PDF page margins  
	pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));   
	// source HTML document also may have margins, could be suppressed this way   
	// (PD4ML *Pro* feature):  
	pd4ml.addStyle("BODY {margin: 0}", true);
	
	pd4ml.useTTF("java:fonts", true); //이 코드를 넣어야 한글이 정상적으로 만들어짐
	pd4ml.setDefaultTTFs("Times New Roman", "Arial", "Courier New"); // 한글 관련 Font설정
    
	pd4ml.render(new StringReader(HtmlString), fos); //actual document conversion from URL to file  
	fos.close();
    
	return false;
 }

 

결과

 

 

728x90
반응형

댓글