Hoy he tenido que generar PDFs a partir de unas plantillas en HTML, nada muy complejo, unos contratos. Mi sorpresa ha sido que no he encontrado ninguna librería Java decente para convertir de HTML a PDFs. Así que he tenido que utilizar Wkhtmltopdf.
Wkhtmltopdf es una excelente herramienta en línea de comandos para Linux, Mac y Windows que nos permite generar PDFs y imagenes a partir de páginas web(Ficheros o URLs). Una vez descargado podemos utilizarlo así:
# Syntaxis wkhtmltopdf [web] [fichero.pdf] # Ejemplo: Convertir Google en PDF wkhtmltopdf http://www.google.com google.pdf # Ejemplo: Convertir Google en una imagen PNG wkhtmltoimage http://www.google.com google.png
Y si queremos usarlo en nuestras aplicaciones Java par convertir HTML a PDF y servirlo en un Servlet, por ejemplo:
public class PrintContractServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { /* Contenido a convertir */ String k="<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head><body>Mi contenido HTML!</body></html>"; /* Definimos los ficheros temporales*/ String tempFilename=new java.util.Date().getTime()+"_"+Math.random(); File hfile=new File(tempFilename+".html"); File pfile=new File(tempFilename+".pdf"); /* Escribimos el fichero temporal HTML*/ PrintWriter out = new PrintWriter( hfile ); out.print( k ); /* Ejecutamos Wkhtmlpdf */ Process p = Runtime.getRuntime().exec( PropsUtil.get("bgse.wkhtmltox.folder")+"/bin/wkhtmltopdf "+hfile.getPath()+" "+pfile.getPath() ); p.waitFor(); /* Leemos el fichero temporal PDF */ byte[] b=Files.readAllBytes( pfile.toPath() ); /* Eliminamos los ficheros temporales */ hfile.delete(); pfile.delete(); /* Escribimos el PDF por el servlet */ response.getOutputStream().write(b); response.getOutputStream().close(); } catch (Exception ex) { ex.printStackTrace(); } } }
En fin, espero que lo disfrutéis. Esto tiene un montón de aplicaciones practicas 😀