【相關(guān)學(xué)習(xí)推薦:小程序開發(fā)教程】
實(shí)現(xiàn)方案
前端人員,提供相關(guān)的html頁面, 后端人員提供接口,前端人員通過參數(shù)設(shè)置html頁面需要渲染的內(nèi)容, 最后使用wkhtmltoimage或者phantomjs 對html 進(jìn)行截圖生成海報, 個人感覺wkhtmltoiamge 比phantomjs 要快一點(diǎn),穩(wěn)定一點(diǎn)我主要說下wkhtmltoimage的實(shí)現(xiàn)方案
實(shí)現(xiàn)步驟
安裝環(huán)境
官網(wǎng)地址:https://wkhtmltopdf.org/
windows: 下載安裝包安裝即可
linux: 下載對應(yīng)的安裝包 ,還需安裝對應(yīng)中文字體(phantomjs 也需要安裝字體),html中需要聲明引用
yum install libjpeg libXrender libXext xorg-x11-fonts-75dpi.noarch xorg-x11-fonts-Type1 bitmap-fonts-cjk
rpm -ivh wkhtmltox-0.12.6-1.centos7.x86_64.rpm
安裝字體
yum install bitmap-fonts-cjk
mkdir /usr/share/fonts/win
拷貝字體到 /usr/share/fonts/win下
cd /usr/share/fonts/win
mkfontscale
mkfontdir
fc-cache
相關(guān)代碼
利用java 執(zhí)行命令 調(diào)用wkhtmltoImage 設(shè)置相關(guān)參數(shù),具體參數(shù)查看wkhtmltoImage 命令提示
package com.yumingzhu.wxweb.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @Description * @Author yumigzhu * @Date 2020/7/22 20:12 */ public class CustomWKHtmlToPdfUtil { private static String tempPath = "C:/apps/tmpFile";// 圖片保存目錄 public static String getCommand(String htmlToImage, String sourceFilePath, String targetFilePath) { //--quality 設(shè)置為50 是比較合適的, 默認(rèn)的94 可能會導(dǎo)致圖片文件過大 ProcessBuilder pb = new ProcessBuilder(htmlToImage, "--crop-w", "800", "--width", "800","--quality", "50", sourceFilePath, targetFilePath); Process process; try { process = pb.start(); //注意,調(diào)用process.getErrorStream()而不是process.getInputStream() BufferedReader errStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); System.out.println("read errstreamreader"); String line = null; line = errStreamReader.readLine(); while (line != null) { System.out.println(line); line = errStreamReader.readLine(); } process.destroy(); System.out.println("destroyed process"); } catch (IOException e) { e.printStackTrace(); } return targetFilePath; } public static void main(String[] args) throws Exception { String imagePath = tempPath + "/" + System.currentTimeMillis() + ".png";//圖片路徑 System.out.println(imagePath); String htmlToImage = "E:\softwareAPP\wkhtmltopdf\bin\wkhtmltoimage.exe"; CustomWKHtmlToPdfUtil.getCommand(htmlToImage, "file:///G:/share/text_none_title_share/index.html", imagePath); System.out.println("執(zhí)行完成"); } }
踩坑記錄
-
如果html頁面設(shè)置的寬高比較小, 這樣截出來的圖片也會比較小,比較模糊,, 增大html 的寬高,可以使圖片更清晰,這樣會導(dǎo)致截出來的圖片文件更大,這樣用戶在小程序下載過程會更慢,這里需要自己權(quán)衡
-
wkhtmlImage 對 css3 linear-gradient 不支持,不能使用樣式下劃線,可以考慮使用圖片代替
-
中文字體需要聲明引用,才能生效
相關(guān)學(xué)習(xí)推薦:java基礎(chǔ)教程