How to use PhantomJS in Java to implement HTML page screenshot function?
I. Background
How to generate a picture in the mini program and share it with friends? At present, there seems to be no good solution for the front end, so it can only be supported by the back end. So how can it be played?
Generating pictures is relatively simple
Simple scenes can be supported directly using jdk. Generally speaking, there is not too complicated logic
I have written a picture synthesis before Logic, implemented using awt: Image synthesis
General and complex templates
Simple ones can be directly supported, but for more complex ones, it is undoubtedly more disgusting to let the backend support it, and it is also available on github I searched some open source libraries for rendering HTML, but I don’t know if it’s because of the wrong posture or something, but I didn’t get very satisfactory results
Now, how can we support complex templates?
This is the guide of this article, using phantomjs to implement html rendering, supporting the generation of pdf, image generation, and dom parsing. Next, we will demonstrate how to combine phantomjs to build a service that renders web pages into images
II. Prerequisite preparation
1. Install phantom.js
# 1. 下载 ## mac 系统 wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-macosx.zip ## linux 系统 wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 ## windows 系统 ## 就不要玩了,没啥意思 # 2. 解压 sudo su tar -jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2 # 如果解压报错,则安装下面的 # yum -y install bzip2 # 3. 安装 ## 简单点,移动到bin目录下 cp phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin # 4. 验证是否ok phantomjs --version # 输出版本号,则表示ok
2. Java dependency configuration
maven configuration to add dependencies
<!--phantomjs --> <dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>2.53.1</version> </dependency> <dependency> <groupid>com.github.detro</groupid> <artifactid>ghostdriver</artifactid> <version>2.1.0</version> </dependency> <repositories> <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> </repositories>
Start
The logic of mainly calling phantomjs to realize html rendering pictures is as follows
public class Html2ImageByJsWrapper { private static PhantomJSDriver webDriver = getPhantomJs(); private static PhantomJSDriver getPhantomJs() { //设置必要参数 DesiredCapabilities dcaps = new DesiredCapabilities(); //ssl证书支持 dcaps.setCapability("acceptSslCerts", true); //截屏支持 dcaps.setCapability("takesScreenshot", true); //css搜索支持 dcaps.setCapability("cssSelectorsEnabled", true); //js支持 dcaps.setJavascriptEnabled(true); //驱动支持(第二参数表明的是你的phantomjs引擎所在的路径,which/whereis phantomjs可以查看) // fixme 这里写了执行, 可以考虑判断系统是否有安装,并获取对应的路径 or 开放出来指定路径 dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/usr/local/bin/phantomjs"); //创建无界面浏览器对象 return new PhantomJSDriver(dcaps); } public static BufferedImage renderHtml2Image(String url) throws IOException { webDriver.get(url); File file = webDriver.getScreenshotAs(OutputType.FILE); return ImageIO.read(file); } }
Test case
public class Base64Util { public static String encode(BufferedImage bufferedImage, String imgType) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, imgType, outputStream); return encode(outputStream); } public static String encode(ByteArrayOutputStream outputStream) { return Base64.getEncoder().encodeToString(outputStream.toByteArray()); } } @Test public void testRender() throws IOException { BufferedImage img = null; for (int i = 0; i <p><strong>III. Network test</strong> </p><p>Operation demonstration:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/465/014/168230743789738.gif" class="lazy" alt="How to use PhantomJS in Java to implement HTML page screenshot function?"></p>
The above is the detailed content of How to use PhantomJS in Java to implement HTML page screenshot function?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

HTML5 Interview Questions 1. What are HTML5 multimedia elements 2. What is canvas element 3. What is geolocation API 4. What are Web Workers

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
