En ocasiones nos puede ser util poder convertir un html a PDF, para ellos utilizaremos dos librerias:
– core-renderer.jar
– itext-paulo-155.jar
Pincha aqui para descargar las librerias
El codigo es el siguiente:
import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; public byte[] createPDF() throws Exception { ITextRenderer renderer = new ITextRenderer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); renderer.setDocument(generateDocument(htmlString, null); renderer.layout(); renderer.createPDF(os); byte[] arrayBytes = os.toByteArray()); os.flush(); os.close(); return arrayBytes ; } private Document generateDocument(String template) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(IOUtils.toInputStream(template, "UTF-8")); }