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
| public class Html2PdfUtil { private final static String FONTS_DIR = "C:\\Windows\\Fonts";
public static void main(String[] args) throws IOException { createPdf(readTextFromFile("d:\\input.html"),"d:\\output.pdf"); }
public static String readTextFromFile(String fileName) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(fileName)); String content; while ((content = br.readLine()) != null) { sb.append(content); } return sb.toString(); }
public static byte[] convert2Pdf(String htmlContent) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ConverterProperties props = new ConverterProperties(); FontProvider fp = new FontProvider(); fp.addStandardPdfFonts(); fp.addDirectory(StringUtils.isBlank(FONTS_DIR) ? "/usr/share/fonts" : FONTS_DIR); props.setFontProvider(fp);
List<IElement> elements = HtmlConverter.convertToElements(htmlContent, props); PdfDocument pdf = new PdfDocument(new PdfWriter(outputStream)); Document document = new Document(pdf, PageSize.A4.rotate(), false); for (IElement element : elements) { if (element instanceof HtmlPageBreak) { document.add((HtmlPageBreak) element); } else { document.add((IBlockElement) element); } } document.close(); return outputStream.toByteArray(); }
public static void convert2Pdf(String htmlContent, String dest) throws IOException { ConverterProperties props = new ConverterProperties(); FontProvider fp = new FontProvider(); fp.addStandardPdfFonts(); fp.addDirectory(StringUtils.isBlank(FONTS_DIR) ? "/usr/share/fonts" : FONTS_DIR); props.setFontProvider(fp);
List<IElement> elements = HtmlConverter.convertToElements(htmlContent, props); PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); Document document = new Document(pdf, PageSize.A4.rotate(), false); for (IElement element : elements) { if (element instanceof HtmlPageBreak) { document.add((HtmlPageBreak) element); } else { document.add((IBlockElement) element); } } document.close(); } }
|