1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package com.stone.service;
import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.BaseFont; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Service; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.*;
@Service public class Html2Pdf {
public byte[] convert(String htmlStr) { ITextRenderer renderer = new ITextRenderer(); ITextFontResolver fontResolver = renderer.getFontResolver(); try { fontResolver.addFont("/Users/shidonghua/IdeaProjects/vm2pdf/src/main/resources/fonts/SimSun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream os = new ByteArrayOutputStream(); renderer.setDocumentFromString(htmlStr); renderer.layout(); try { renderer.createPDF(os); } catch (DocumentException e) { e.printStackTrace(); }
return os.toByteArray(); }
public static void main(String[] args) throws IOException { Html2Pdf html2Pdf = new Html2Pdf();
ClassLoader classLoader = html2Pdf.getClass().getClassLoader(); File htmlFile = new File(classLoader.getResource("html/htmlTest1.html").getFile());
String htmlStr = FileUtils.readFileToString(htmlFile);
byte[] content = html2Pdf.convert(htmlStr);
FileOutputStream fstream = null; BufferedOutputStream stream = null; File file = null; try { file = new File("test.pdf"); fstream = new FileOutputStream(file); stream = new BufferedOutputStream(fstream);
stream.write(content); } catch (IOException e) { e.printStackTrace(); } finally {
if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } }
if (fstream != null) { try { fstream.close(); } catch (IOException e) { e.printStackTrace(); } }
} } }
|