我的解决方案包括 3 个步骤:
- 创建一个
BufferedImage
并创建其Graphics
- 创建
JEditorPane
并调用print(Graphics)
- 输出过
BufferedImage
孔ImageIO
代码:
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
public class Test {
public static void main(String[] args) {
String html = "<h1>Hello, world.</h1>Etc. Etc.";
int width = 200, height = 100;
// Create a `BufferedImage` and create the its `Graphics`
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(width, height);
Graphics graphics = image.createGraphics();
// Create an `JEditorPane` and invoke `print(Graphics)`
JEditorPane jep = new JEditorPane("text/html", html);
jep.setSize(width, height);
jep.print(graphics);
// Output the `BufferedImage` via `ImageIO`
try {
ImageIO.write(image, "png", new File("Image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果: