본문 바로가기
Java

[java] xsl+xml 을 pdf파일로 변환하기

by Yeoseungwon 2024. 6. 19.
728x90

employeesfo2.xsl
0.00MB
fop.xml
0.00MB
malgun.ttf
4.14MB
malgun.xml
0.85MB

@RequestMapping(value = "/sign/convertToPDF.do")
	public void convertToPDF()  throws IOException, FOPException, TransformerException, SAXException {
		// the XSL FO file
		File xsltFile = new File("src/main/resources/static/homepage/xml/employeesfo.xsl");
		// the XML file which provides the input
		StreamSource xmlSource = new StreamSource(new File("src/main/resources/static/homepage/xml/_sign_20240619131638.xml"));
		// FOP 팩토리 인스턴스 생성
		//FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
		FopFactory fopFactory = FopFactory.newInstance(new File("src/main/resources/static/homepage/xml/fop.xml"));
		// FOP 사용자 에이전트 생성
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

		String currentTime = DateUtil.getCurrentDateTime();
		String pdfNm = "_sign_".concat(currentTime);
		// Setup output
		OutputStream out = new java.io.FileOutputStream("src/main/resources/static/homepage/xml/"+pdfNm+".pdf");

		//BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/main/resources/static/homepage/xml/employee3.pdf"),"UTF-8"));
		try {
			// Construct fop with desired output format
			Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

			// Setup XSLT
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));

			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");


			Result res = new SAXResult(fop.getDefaultHandler());

			transformer.transform(xmlSource, res);
		} finally {
			out.close();
		}
	}

 

 

 

한글 인코딩이 안되는데, 

아래 Test 로 돌려서 fop.xml 파일을 만들어서 적용시키고 xsl 에도 font-family 로 적용시켜주면 된다.

import org.apache.fop.fonts.apps.TTFReader;
import org.apache.fop.fonts.truetype.TTFFile;
import org.w3c.dom.Document;

public class Test2 {

	public static void main(String[] args) throws Exception {
		String src = "D:\\99. dev\\workspace\\api\\src\\main\\java\\usdt\\malgun.ttf";
		String out = "D:\\99. dev\\workspace\\api\\src\\main\\java\\usdt\\malgun.xml";
		TTFReader app = new TTFReader();

		TTFFile ttf = app.loadTTF(src,null, true, true);

		Document doc = app.constructFontXML(ttf, null,null, null, null, true, null);

		app.writeFontXML(doc,out);
	}
}
728x90

'Java' 카테고리의 다른 글

[java] java로 xml 다운로드  (0) 2024.07.01
[java] xml 생성  (1) 2024.06.19
[java] pdf 생성  (0) 2024.06.19
Java 타입  (0) 2023.09.22
[Java] 객체지향언어 / 클래스, 객체, 인스턴스, 참조변수, 메서드  (0) 2023.06.11