Java或其他技术 将html转化成图片?[持续更新](一)

2014-11-24 02:50:35 · 作者: · 浏览: 1

如何使用Java或其他技术将html转换为图片呢?知道的朋友交流一下~

网上找了一下,发现几种方法。

1、html2image【java】

html2image:http://code.google.com/p/java-html2image/

jar包下载地址:http://code.google.com/p/java-html2image/downloads/list

HtmlImageGenerator imageGenerator = new HtmlImageGenerator();

imageGenerator.loadHtml(Hello World! Please goto Google.);

imageGenerator.saveAsImage(hello-world.png);

imageGenerator.saveAsHtmlWithMap(hello-world.html, hello-world.png);

HtmlImageGenerator Methods
loadUrl(url) - Loads HTML from URL object or URL string. (从url载入html)
loadHtml(html) - Loads HTML source. (载入本地html)
saveAsImage(file) - Save loaded HTML as image. (以图片形式保存html)
saveAsHtmlWithMap(file, imageUrl) - Creates an HTML file containing client-side image-mapgenerated from HTML's links. (创建一个HTML文件包含客户端image-map)
getLinks() - List all links in the HTML document and their corresponding href, target, title, position and dimension. (列出所有在HTML文档的链接和相应href、目标、头衔、位置和尺寸)
getBufferedImage() - Get AWT buffered image of the HTML. (获得awt,html缓冲后的图片)
getLinksMapMarkup(mapName) - Get HTML snippet of the client-side image-mapgenerated from the links. (HTML代码段里获得的客户端image-map <地图>产生的链接)
get/setOrientation(orientation) - Get/Set document orientation (left-to-right or right-to-left). (get/set文本定位)
get/setSize(dimension) - Get/Set size of the generated image. (设置生成图片大小)

测试结果:不支持相对路径链接图片,排版错乱。

2、纯Java http://www.tuicool.com/articles/2yAryy

Java中江HTML片段转换为图片,不需要调用额外的jar包,支持css,但写在style之间的css和外置的css文件不受支持,只能写在标签上。

知道不支持外置css文件就没测试了。

示例代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicEditorPaneUI;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.xxx.util.FileUtil;

/**
 * HTML转换图片的方式
 *
 * 
 */
public class HTML2Picture {

    public static int DEFAULT_IMAGE_WIDTH = 730;
    public static int DEFAULT_IMAGE_HEIGHT = 700;

    public static boolean paintPage(Graphics g, int hPage, int pageIndex,
            JTextPane panel) {
        Graphics2D g2 = (Graphics2D) g;
        Dimension d = ((BasicEditorPaneUI) panel.getUI())
                .getPreferredSize(panel);
        double panelHeight = d.height;
        double pageHeight = hPage;
        int totalNumPages = (int) Math.ceil(panelHeight / pageHeight);
        g2.translate(0f, -(pageIndex - 1) * pageHeight);
        panel.paint(g2);
        boolean ret = true;

        if (pageIndex >= totalNumPages) {
            ret = false;
            return ret;
        }
        return ret;
    }

    /**
     * html转换为jpeg文件
     * 
     * @param bgColor
     *            图片的背景色
     * @param html
     *            html的文本信息
     * @param width
     *            显示图片的Text容器的宽度
     * @param height
     *            显示图片的Text容器的高度
     * @param eb
     *             置容器的边框
     * @return
     * @throws Exception
     */
    private static void html2jpeg(Color bgColor, String html, int width,
            int height, EmptyBorder eb) throws Exception {

        JTextPane tp = new JTextPane();
        tp.setSize(width, height);
        if (eb == null) {
            eb = new EmptyBorder(0, 50, 0, 50);
        }
        if (bgColor != null) {
            tp.setBackground(bgColor);
        }
        if (width <= 0) {
            width = DEFAULT_IMAGE_WIDTH;
        }
        if (height <= 0) {
            height = DEFAULT_IMAGE_HEIGHT;
        }
        tp.setBorder(eb);
        tp.setContentType(text/html);
        tp.setText(html);

        int pageIndex = 1;
        boolean bcontinue = true;
        while (bcontinue) {
            BufferedImage image = new java.awt.image.BufferedImage(width,
                    height, java.awt.image.BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.setClip(0, 0, width, height);
            bcontinue = paintPage(g, height, pageIndex, tp);
            g.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(1.0f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(image);
            byte[] bytes = baos.toByteArray();
            baos.close();

            FileUtil.writeBinFile(C:S.jpg, bytes);
            pageIndex++;
        }
    }

    public static void main(String[] args) throws Exception {
        html2jpeg(Color.white, FileUtil.readAscFile(C:	able.html),
                DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_WIDTH, new EmptyBorder(0, 0,
                        0, 0));
        System.out.println(over!);

    }
}


3、html2canvas 【JS截图技术】

官网:http://html2canvas.hertzen.com/

测试结