使用java 的本地浏览器JWebBrowser 实现html 转图片的功能

需要下载的包
两个lib

https://sourceforge.net/projects/djproject/files/DJ%20Native%20Swing/1.0.3%20preview/

还有eclipse的plugin里面的swt,可以版本不一样,略有区别

org.eclipse.swt.win32.win32.x86_64_3.106.0.v20170608-0516.jar

代码如下,这个是命令行的工具,可以再用java调用命令行,实现批量转换,目前只能支持文件与文件的格式转换..

package djnativeswing;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

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 MainView extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    final static StringBuffer jsDimension;
    static {
        jsDimension = new StringBuffer();
        jsDimension.append("var width = 0;");
        jsDimension.append("var height = 0;");
        jsDimension.append("if(document.body.scrollWidth) {");
        jsDimension.append("  width = Math.max(width, document.body.scrollWidth);");
        jsDimension.append("  height = Math.max(height, document.body.scrollHeight);");
        jsDimension.append("}");
        jsDimension.append("return width + ':' + height;");
    }

    public MainView(String htmlFileName, String pngFileName) throws UnsupportedEncodingException, IOException {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1024, 768);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        JWebBrowser webbrowser = new JWebBrowser();
        webbrowser.setBounds(0, 0, 1024, 768);
        String html=new String(Files.readAllBytes(Paths.get(htmlFileName)),"utf-8");
        webbrowser.setHTMLContent(html);
        //webbrowser.navigate("https://blog.csdn.net/redlevin");
        webbrowser.setButtonBarVisible(false);
        webbrowser.setMenuBarVisible(false);
        webbrowser.setBarsVisible(false);
        webbrowser.setStatusBarVisible(false);
        webbrowser.addWebBrowserListener(new WebBrowserAdapter() {
            public void loadingProgressChanged(WebBrowserEvent e) {
                JWebBrowser b = e.getWebBrowser();
                if (b.getLoadingProgress() == 100) {
                    String result = (String) b.executeJavascriptWithResult(jsDimension.toString());
                    String[] resultWidthHeight = result.split(":");
                    NativeComponent nativeComponent = b.getNativeComponent();
                    Dimension imageSize = new Dimension(Integer.parseInt(resultWidthHeight[0]),
                            Integer.parseInt(resultWidthHeight[1]));
                    nativeComponent.setSize(imageSize);
                    BufferedImage image = new BufferedImage(imageSize.width, imageSize.height,
                            BufferedImage.TYPE_INT_RGB);
                    nativeComponent.paintComponent(image);
                    try {
                        ImageIO.write(image, "png", new File(pngFileName));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    System.exit(0);
                }
            }
        });
        contentPane.add(webbrowser);
    }

    public static void main(String[] args) {
        if(args.length>=2) {
            NativeInterface.open();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        MainView frame = new MainView(args[0], args[1]);
                        frame.invalidate();
                        frame.pack();
                        frame.setVisible(false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            NativeInterface.runEventPump();
        }

    }
}

参考了一些内容

https://blog.csdn.net/ltllml44/article/details/72910295

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用html2canvas插件实现Javahtml图片的示例代码: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutionException; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.Augmenter; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import com.google.common.base.Function; import io.github.bonigarcia.wdm.WebDriverManager; import net.sf.image4j.codec.ico.ICODecoder; public class HtmlToImage { public static void main(String[] args) throws IOException, InterruptedException, ExecutionException { // 设置ChromeDriver路径 WebDriverManager.chromedriver().setup(); // 创建ChromeDriver实例 ChromeOptions options = new ChromeOptions(); options.addArguments("--headless", "--disable-gpu", "--no-sandbox"); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, options); WebDriver driver = new ChromeDriver(capabilities); // 打开html页面 driver.get("http://www.example.com"); // 等待页面加载完成 WebDriverWait wait = new WebDriverWait(driver, 30); wait.until((Function<WebDriver, Boolean>) d -> ((JavascriptExecutor) d).executeScript("return document.readyState").equals("complete")); // 调用html2canvas插件生成图片 WebElement element = driver.findElement(By.tagName("body")); File screenshot = ((TakesScreenshot) new Augmenter().augment(driver)).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("screenshot.png")); // 关闭ChromeDriver实例 driver.quit(); } } ``` 上述代码使用了Selenium WebDriver和html2canvas插件来实现Javahtml图片功能。其中,Selenium WebDriver用于打开html页面和截取屏幕截图,html2canvas插件用于将html页面换为图片。具体实现过程如下: 1. 首先,需要设置ChromeDriver的路径,并创建ChromeDriver实例。 2. 然后,使用ChromeDriver打开html页面,并等待页面加载完成。 3. 接着,使用html2canvas插件生成图片。这里使用了Selenium WebDriver的截图功能,将页面截图保存为文件。 4. 最后,关闭ChromeDriver实例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值