html代码 转换成图片(偶尔会生成空白)

package com.by;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class CreatPicByHtml {
    public static void main(String[] args) {
        String html = getHtml();
        OutputStream fos;
        try{
            String htmlPath = "D:\\tiantianbaiying\\by_timer\\src\\test\\com\\by\\ysd.html";
            String pngPath = "D:\\tiantianbaiying\\by_timer\\src\\test\\com\\by\\ysd.png";
            fos = new FileOutputStream(htmlPath);
            fos.write(html.getBytes("UTF-8"));
            fos.flush();
            fos.close();
            System.out.println("成功");
            createPic(htmlPath,pngPath);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("失败");
        }finally {

        }
//        createPic();
    }

    public static String getHtml(){
        //编写html
        StringBuffer html = new StringBuffer();
        html.append("\n" +
                "" +
                "\t\n" +
                "\t\t
工程部验收单
\n" + "\t\t
\n" + "\t\t\t
\n" + "\t\t\t订单编号:BN2018070309253872604

\n" + "\t\t\t店铺ID:2454

\n" + "\t\t\t店铺名称:宁波印象城Ningbo In City

\n" + "\t\t\t施工地址:上海市闵行区莘庄公路6088号龙之梦商务楼2楼

\n" + "\t\t\t报修内容:

\n" + "\t\t\t
\n" + "\t\t\t\t立体发光字整体不亮,报修数量10个,需紧急维修\n" + "\t\t\t
\n" + "\t\t\t
\n" + "\t\t
\n" + "\t\t
\n" + "\t\t
\n" + "\t\t\t上门师傅姓名:张梓晨\n" + "\t\t
\n" + "\t
\n" + "\t
\n" + "\t\t\t
店铺验收结果:
\n" + "\t\t\t
\n" + "\t\t\t
3454 屈臣氏浦东店
\n" + "\t\t
\n" + "\t\n" + ""); System.out.println(html); return html.toString(); } public static void createPic(String htmlPath,String pngPath){ //转换成图片 try { // JEditorPane ed = new JEditorPane("file:///" + "C:\\Users\\Administrator\\Desktop\\ysd.html"); JEditorPane ed = new JEditorPane("file:///" + htmlPath); ed.setSize(655,820); 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("C:\\Users\\Administrator\\Desktop\\html1.png")); ImageIO.write((RenderedImage)image, "png", new File(pngPath)); System.out.println("完成了啊?"); }catch (Exception e){ e.printStackTrace(); System.out.println("报错了?"); } } }

 

你可能感兴趣的:(java)