java html 转图片_Java HTML转换为图片
第一次嘗試:用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容器的高度
* @param eb 設置容器的邊框
* @return
* @throws Exception
*/
private static ArrayList html2jpeg(Color bgColor, String html, int width, int height, EmptyBorder eb)
throws Exception {
ArrayList ret = new ArrayList();
try {
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();
String path = toJpeg(image);
ret.add(path);
pageIndex++;
}
} catch (Exception ex) {
throw ex;
}
return ret;
}
/**
* 將一個html轉換為圖片
* @param htmls
* @return
* @throws Exception
*/
public static ArrayList toImages(String html) throws Exception {
return html2jpeg(Color.white, html, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT, new EmptyBorder(0, 0, 0, 0));
}
TestCase:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath*:spring/application.xml", "classpath*:spring/plugin-*.xml" })
public class GraphUtilsTest extends TestCase {
@Autowired
private TaskService taskService;
@Autowired
private VelocitySimpleRelolver velocitySimpleRelolver;
@Test
public void testHtml2Image() {
try {
String imageTemplateFile = "mail/weekly/mile_schedule_task.vm";
//郵件內容
Map velocityData = new HashMap();
String projId = "6a9fb54e3439453e86e819a4d46fdafb";
MileSchedule mileSchedule = taskService.getMileSchedule(projId);
velocityData.put("mileSchedule", mileSchedule);
String htmlstr = velocitySimpleRelolver.relolve(imageTemplateFile, velocityData);
Assert.assertNotNull(htmlstr);
GraphUtils.toImages(htmlstr);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Second: 利用html2image組件
優點:方便,代碼簡單缺點:CSS支持極差,比不上Java自身的轉化
maven引入:
gui.ava
html2image
0.9
TestCase:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath*:spring/application.xml", "classpath*:spring/plugin-*.xml" })
public class Html2ImageTest extends TestCase {
@Autowired
private TaskService taskService;
@Autowired
private VelocitySimpleRelolver velocitySimpleRelolver;
@Test
public void testHtml2Image() {
try {
String imageTemplateFile = "mail/weekly/mile_schedule_task.vm";
//郵件內容
Map velocityData = new HashMap();
String projId = "6a9fb54e3439453e86e819a4d46fdafb";
MileSchedule mileSchedule = taskService.getMileSchedule(projId);
velocityData.put("mileSchedule", mileSchedule);
String htmlstr = velocitySimpleRelolver.relolve(imageTemplateFile, velocityData);
System.out.println(htmlstr);
Assert.assertNotNull(htmlstr);
String imageName = "G:/weekly_mile_" + projId + ".png";
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.setSize(new Dimension(1000, 200));
imageGenerator.loadHtml(htmlstr);
imageGenerator.getBufferedImage();
imageGenerator.saveAsImage(imageName);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testImage() {
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.setSize(new Dimension(1000, 200));
imageGenerator.loadUrl("http://www.baidu.com");
imageGenerator.getBufferedImage();
imageGenerator.saveAsImage("G:/aaa.png");
}
} Third:DJNativeSwing
參考:http://blog.csdn.net/cping1982/article/details/5353049
其中:JAR包下載地址:
此地址下down org.eclipse.swt 包,選擇適合你的開發環境
注意:swt 包針對不同的環境有不同的要求,windows與Linux下的不同,使用maven引入時采用properties方式,將下載的包放入你的maven庫,然后在POM中進行maven引入
eg:
chrriis.dj.nativeswing
DJNativeSwing
1.0.2
chrriis.dj.nativeswing.swt
DJNativeSwing-SWT
1.0.2
${swt.groupId}
${swt.artifactId}
4.3
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Semaphore;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import chrriis.dj.nativeswing.swtimpl.NativeComponent;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserEvent;
public class DJNativeSwingUtils extends JPanel {
private static final long serialVersionUID = 8675106494733722832L;
// 行分隔符
final static public String LS = System.getProperty("line.separator", "/n");
// 文件分割符
final static public String FS = System.getProperty("file.separator", "//");
//以javascript腳本獲得網頁全屏后大小
final static StringBuffer jsDimension;
static {
jsDimension = new StringBuffer();
jsDimension.append("var width = 0;").append(LS);
jsDimension.append("var height = 0;").append(LS);
jsDimension.append("if(document.documentElement) {").append(LS);
jsDimension.append(" width = Math.max(width, document.documentElement.scrollWidth);").append(LS);
jsDimension.append(" height = Math.max(height, document.documentElement.scrollHeight);").append(LS);
jsDimension.append("}").append(LS);
jsDimension.append("if(self.innerWidth) {").append(LS);
jsDimension.append(" width = Math.max(width, self.innerWidth);").append(LS);
jsDimension.append(" height = Math.max(height, self.innerHeight);").append(LS);
jsDimension.append("}").append(LS);
jsDimension.append("if(document.body.scrollWidth) {").append(LS);
jsDimension.append(" width = Math.max(width, document.body.scrollWidth);").append(LS);
jsDimension.append(" height = Math.max(height, document.body.scrollHeight);").append(LS);
jsDimension.append("}").append(LS);
jsDimension.append("return width + ':' + height;");
}
public static JPanel createContent(String htmlStr, final String fileName, final Semaphore semp) {
//瀏覽器面板
JPanel webBrowserPanel = new JPanel(new BorderLayout());
//swing的內嵌瀏覽器
final JWebBrowser webBrowser = new JWebBrowser();
//隱藏所有的欄
webBrowser.setBarsVisible(false);
//向瀏覽器寫入html內容
webBrowser.setHTMLContent(htmlStr);
//將瀏覽器嵌入瀏覽器面板
webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
//向瀏覽器增加監聽事件
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
// 監聽加載進度
public void loadingProgressChanged(WebBrowserEvent e) {
// 當加載完畢時
if (e.getWebBrowser().getLoadingProgress() == 100) {
try {
//執行JS獲取圖片的寬度,高度
String result = (String) webBrowser.executeJavascriptWithResult(jsDimension.toString());
int index = result == null ? -1 : result.indexOf(":");
NativeComponent nativeComponent = webBrowser.getNativeComponent();
//獲取圖片的原始尺寸
Dimension originalSize = nativeComponent.getSize();
//根據JS返回結果設定新的圖片尺寸
Dimension imageSize = new Dimension(Integer.parseInt(result.substring(0, index)), Integer
.parseInt(result.substring(index + 1)));
//計算圖片的新尺寸
imageSize.width = Math.max(originalSize.width, imageSize.width);
imageSize.height = Math.max(originalSize.height, imageSize.height);
nativeComponent.setSize(imageSize);
//創建一個不帶透明色的BufferedImage對象
BufferedImage image = new BufferedImage(imageSize.width, imageSize.height,
BufferedImage.TYPE_INT_RGB);
//對瀏覽器中圖片進行繪色
nativeComponent.paintComponent(image);
//截圖
image = image.getSubimage(0, 0, imageSize.width - 25, imageSize.height);
try {
// 輸出圖像
ImageIO.write(image, "jpg", new File(fileName));
} catch (IOException ex) {
ex.printStackTrace();
}
} finally {
// 退出操作 :釋放線程
NativeInterface.close();
semp.release();
}
}
}
});
return webBrowserPanel;
}
} service調用:
private String createImage(final String htmlStr, final Semaphore semaphore) {
final String fileName = FileUtils.getNewFileName("jpg");
NativeInterface.open();
UIUtils.setPreferredLookAndFeel();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// SWT組件轉Swing組件,不初始化父窗體將無法啟動webBrowser
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 加載指定頁面
frame.getContentPane().add(DJNativeSwingUtils.createContent(htmlStr, fileName, semaphore),
BorderLayout.CENTER);
// 僅初始化,但不顯示
frame.invalidate();
frame.pack();
frame.setVisible(false);
}
});
// 在MAC上使用時,因為MAC不支持雙進程,僅支持進程內模式,調用此方法進行事件調度。windows和Linux可以忽略此事件調度
//NativeInterface.runEventPump();
return new File(fileName).getAbsolutePath();
}
private int fillPicture(HSSFSheet sheet, Report report, int startRow) throws IOException {
if(null == weekly.getMileSchedule()){
return startRow + 1;
}
// 將高度設置為圖片的高度
HSSFRow pictureRow = sheet.getRow(startRow);
pictureRow.setHeightInPoints(162);
String htmlStr = this.createHtml(report);
String imagePath = null;
final Semaphore semp = new Semaphore(1);//設置信號量
try {
semp.acquire();
// 子線程生成圖片
imagePath = this.createImage(htmlStr, semp);
// 等待子線程釋放信號量
semp.acquire();
} catch (InterruptedException e) {
LOG.error("", e);
} finally {
semp.release();
}
try {
ExcelExportUtils.insertPicture(sheet, startRow, (short) 0, (short) 15, imagePath);
} catch (Exception e) {
e.printStackTrace();
} finally {
// delete 文件
new File(imagePath).delete();
}
return ++startRow;
}
windows 下截圖正常,Linux下異常,Linux下必須安裝Mollizia內核的瀏覽器,在服務器上安裝了一個Firefox后,也必須安裝圖形界面,剛開始采用安裝虛擬x-server,但是在CentOS 下安裝各種依賴,嘗試安裝圖形界面后tomcat也必須在圖形界面下啟動才能正常截圖,后廢棄此種方式,采用java原生繪圖方式,下一篇博文介紹
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的java html 转图片_Java HTML转换为图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java程序设计实用教程答案_Java程
- 下一篇: html 页面友情提示,HTML参考