第一次尝试:用awt 包将HTML源码转换为图片
优点:不依赖任何外部JAR包,缺点:对CSS的支持比较差,复杂点的样式就无法展示,且不支持外部引入的CSS和写在style中的CSS,只能写在标签上
Eg:
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 java.io.File;
import java.util.ArrayList;
import java.util.UUID;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicEditorPaneUI;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class GraphUtils {
private final static Log log = LogFactory.getLog(GraphUtils.class);
public static int DEFAULT_IMAGE_WIDTH = 1000;
//默认值最好设置大点,因为我们再导之前,不知道这个流有多大,如果过小,则生成的图片后面的为黑色,因为流没有读取完整
public static int DEFAULT_IMAGE_HEIGHT = 200;
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;
}
/**
* 将BufferedImage转换为图片的信息
*/
public static String toJpeg(BufferedImage image) {
// 获取图片文件的在服务器的路径
String imageName = "G:\\" + UUID.randomUUID().toString() + ".jpg";
try {
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[] buff = baos.toByteArray();
baos.close();
// 将字节流写入文件保存为图片
FileUtils.writeByteArrayToFile(new File(imageName), buff);
} catch (Exception ex) {
log.error("保存删除图片失败:" + ex.getMessage());
}
return imageName;
}
/**
* html转换为jpeg文件
* @param bgColor 图片的背景色
* @param html html的文本信息
* @param width 显示图片的Text容器的宽度
* @param height 显示图片的Text容器的高度
* &