2010-10-18 20 views
5

¿Alguien sabe cómo hacer esto? Lo he intentado con JEditorPane pero no funciona? ¿Alguna otra idea?¿Cómo convertir HTML de un sitio web a una imagen?

Gracias de antemano.

Este es el código que estoy usando:

import java.awt.Dimension; 
import java.awt.Graphics2D; 
import java.awt.image.BufferedImage; 
import java.io.File; 

import javax.imageio.ImageIO; 
import javax.swing.JEditorPane; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

public class HtmlToImage 
    { 

     protected static File generateOutput() throws Exception 
     { 
      // Create a temporary output file for the PNG image. 
      File outputFile = new File("Reporte.png"); 
      outputFile.deleteOnExit(); 

      JEditorPane pane = new JEditorPane(); 
      pane.setContentType("text/html"); 
      pane.setPage("http://www.google.com"); 
      final JFrame frame = new JFrame(); 
      frame.pack(); 

      // Time Delay for the correct loading of the file. 
      try 
      { 
       Thread.sleep(5000); 
      } 
      catch(NumberFormatException nfe) 
      { 
      } 

      frame.add(pane); 
      frame.pack(); 

      Dimension prefSize = pane.getPreferredSize(); 
      pane.setSize(prefSize); 

      BufferedImage img = new BufferedImage( prefSize.width, prefSize.height, 
                BufferedImage.TYPE_INT_RGB); 
      Graphics2D g = (Graphics2D) img.getGraphics(); 

      SwingUtilities.paintComponent(g, pane, frame, 0, 0, prefSize.width, prefSize.height); 

      ImageIO.write(img, "png", outputFile); 

      return outputFile; 
     } 

     public static void main(String[] args) 
     { 
      try 
      {    
       generateOutput(); 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 
     } 

    } 
+0

cómo no funciona? – Bozho

+1

Me imagino porque JEditorPane es un componente de Swing y no tiene nada que ver con HTML en absoluto. –

+0

Hola @Bozho, gracias por la respuesta. El problema es la imagen resultante, está totalmente malformada. – hernangarcia

Respuesta

3

Es necesario hacer que el HTML y enviar el resultado como un archivo de imagen. Actualmente, no existe un renderizador de HTML completo en Core Java, por lo que necesitará una biblioteca o aplicación por separado, por ejemplo, WebRenderer. Simplemente inícielo desde un filtro de servlet y anule la respuesta con resultados de representación.

Editar alternativa de código abierto a WebRenderer es Cobra

+0

Gracias @Saul Estoy creando una aplicación de acceso abierto, por lo que me gustaría utilizar las herramientas/libs de fuentes abiertas. – hernangarcia

+0

HTMLEditorKit de Swing proporciona renderización de HTML (aunque primitiva). http://download.oracle.com/javase/6/docs/api/javax/swing/text/html/HTMLEditorKit.html – dogbane

+0

@dogbane: HTMLEditorKit sólo admite un conjunto muy mínimo de funcionalidad moderna utilización de sitios web. No es un motor de renderizado web completo. – Saul

1

Usted podría tratar de usar un JEditorPane de la siguiente manera:

//load the webpage into the editor 
JEditorPane ed = new JEditorPane(new URL("http://www.google.com")); 
ed.setSize(200,200); 

//create a new image 
BufferedImage image = new BufferedImage(ed.getWidth(), ed.getHeight(), 
             BufferedImage.TYPE_INT_ARGB); 

//paint the editor onto the image 
SwingUtilities.paintComponent(image.createGraphics(), 
           ed, 
           new JPanel(), 
           0, 0, image.getWidth(), image.getHeight()); 

//save the image to file 
ImageIO.write((RenderedImage)image, "png", new File("google.png")); 
+0

La pantalla está completamente en blanco, de color blanco. –

-1

También puede utilizar Html2Image Java API de Google.

Cuestiones relacionadas