java 使用java将HTML转换为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36933054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:01:14  来源:igfitidea点击:

Converting HTML to image using java

java

提问by audrey ruaburo

i'm facing some problem converting html to image using java im using html2image[java]

我在使用 html2image[java] 使用 java im 将 html 转换为图像时遇到了一些问题

it create an image, but the problem is it only create an image on a small part of the html. how can i make it to make an image of the whole html. thank you

它创建了一个图像,但问题是它只在 html 的一小部分创建了一个图像。我怎样才能制作整个 html 的图像。谢谢

this is my code

这是我的代码

import gui.ava.html.image.generator.HtmlImageGenerator;
import java.io.File;


public class test {
    public static void main(String[] args) {
        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        String uri = new File("C:\cover.html").toURI().toString();
        imageGenerator.loadUrl(uri);
        imageGenerator.saveAsImage("hello-world.png");
        imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
    }
}

i also use saveAsHtmlWithMap to save the html file. and that html file written by the program to the harddisk is also a small one.

我还使用 saveAsHtmlWithMap 来保存 html 文件。而程序写入硬盘的那个html文件也是一个小文件。

this is the html code of cover.thml

这是cover.thml的html代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="***">
    <head>
        <title></title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=1200, height=1200"/>
        <link rel="stylesheet" type="text/css" href="main.css"/>
    </head>
    <body id="cover_page">
        <nav id="cover" >
            <ol>
                <li id="nav1">
                    <a>cover</a>
                </li>
            </ol>
        </nav>
    </body>
</html>

回答by flaz14

@Pralay, unfortunately,

@Pralay,不幸的是,

imageGenerator.setSize(new Dimension(1024, 768));

imageGenerator.setSize(new Dimension(1024, 768));

and

imageGenerator.getDefaultSize().setSize(1024, 768);

imageGenerator.getDefaultSize().setSize(1024, 768);

didn't help.

没有帮助。

Anyway, default size in ImageRendererused by html2imageis 1024x768. Look at the excerpt from ImageRendereImplclass:

无论如何,html2imageImageRenderer使用的默认大小是 1024x768。看课文摘录:ImageRendereImpl

public class ImageRendererImpl implements ImageRenderer {
    public static final int DEFAULT_WIDTH = 1024;
    public static final int DEFAULT_HEIGHT = 768;   
    ...
    private int width = DEFAULT_WIDTH;
    private int height = DEFAULT_HEIGHT;
    private boolean autoHeight = true;
    ...

But pay attention to the autoHeightfield. Below inside ImageRendererImplclass you can see:

但要注意autoHeight领域。在ImageRendererImpl课内你可以看到:

if (autoHeight) {
    // do layout with temp buffer
    Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
    renderer.layout(graphics2D, new Dimension(width, height));
    graphics2D.dispose();

    Rectangle size = renderer.getMinimumSize();
    final int autoWidth = (int) size.getWidth();
    final int autoHeight = (int) size.getHeight();
    bufferedImage = new BufferedImage(autoWidth, autoHeight, imageType);
    dimension = new Dimension(autoWidth, autoHeight);

If authHeightis true (actually it's trueby default) getMinimumSize()method of org.xhtmlrenderer.simple.Graphics2DRendererclass will be invoked. As can be concluded from the corresponding Javadocthe minimal possible area will be used. This is why you get too little image.

如果authHeight为真(实际上true是默认)getMinimumSize()org.xhtmlrenderer.simple.Graphics2DRenderer类的方法将被调用。从相应的 Javadoc可以得出结论,将使用尽可能小的区域。这就是为什么你得到的图像太少。

Setting autoHeightto falsesolves the issue:

设置autoHeightfalse解决问题:

public class Test {
    public static void main(String[] args) throws {
        File inputFile = new File("/home/me/Temp/cover.html");
        Html2Image imageGenerator = new Html2Image();
        imageGenerator.getParser().load(inputFile);
        imageGenerator.getImageRenderer().setAutoHeight(false);
        imageGenerator.getImageRenderer().saveImage("/home/me/Temp/hello-world.png");
    }
}

So I've got

所以我有

enter image description here

在此处输入图片说明

PS: I've investigated and overcame the issue with aid of html2imagev. 2.0-SNAPSHOT. As for v. 0.9(which is in Maven Central) you need to modify the source code (v. 0.9is old and not flexible).

PS:我已经在html2imagev. 2.0-SNAPSHOT 的帮助下调查并解决了这个问题。至于 v. 0.9(在 Maven Central 中),您需要修改源代码(v. 0.9旧且不灵活)。

PS2In pure Java you can try something like this:

PS2在纯 Java 中,您可以尝试这样的操作:

public class Example1 {

    private static final int WIDTH = 1204;
    private static final int HEIGHT = 768;

    public static void main(String[] args) throws IOException {
        // open HTML page
        JEditorPane editorPane = new JEditorPane();
        editorPane.setEditable(false);
        URL urlToPage = new File("/home/me/Temp/cover.html").toURI().toURL();
        editorPane.setPage(urlToPage);
        editorPane.setSize(WIDTH, HEIGHT);

        // render the page
        BufferedImage renderedImage = new BufferedImage(640, 480, BufferedImage.TYPE_INT_RGB);
        editorPane.print(renderedImage.getGraphics());

        // write result to file
        ImageIO.write(renderedImage, "PNG", new File("/home/me/Temp/hello-world.png"));
    }
}

PS3As I see html2imageis not maintained now (in order to use to v. 2.0you need to download and compile it by yourself). Perhaps, there are some living forks of this library. Or just try another HTML rendering library.

PS3据我所知 html2image现在没有维护(为了使用 v. 2.0你需要自己下载和编译它)。也许,这个库有一些活的分支。或者只是尝试另一个 HTML 渲染库。

回答by deadpool

HtmlImageGenerator by default creates and sets a java.awt.Dimension object of (800,800). You can pass your own new Dimension(x, y) of your custom size using below setter of HtmlImageGenerator class:

HtmlImageGenerator 默认创建并设置一个 java.awt.Dimension 对象为 (800,800)。您可以使用以下 HtmlImageGenerator 类的 setter 传递您自己的自定义大小的新 Dimension(x, y):

 public void setSize(Dimension dimension);

I hope it helps.

我希望它有帮助。

回答by vzamanillo

I am not experienced with html2image, but maybe it can parse the inline CSS only and that's the reason because the resulting image is not the same as is rendered in the browser.

我对 html2image 没有经验,但也许它只能解析内联 CSS,这就是原因,因为生成的图像与浏览器中呈现的图像不同。

Try adding an inline style with the contens of main.cssto your HTML and save an image again.

尝试main.css在 HTML 中添加包含 的内联样式并再次保存图像。