• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

展示小程序生成海报(java后端)

武飞扬头像
PHP中文网
帮助17

学新通技术网

实现方案

前端人员,提供相关的html页面, 后端人员提供接口,前端人员通过参数设置html页面需要渲染的内容, 最后使用wkhtmltoimage或者phantomjs 对html 进行截图生成海报, 个人感觉wkhtmltoiamge 比phantomjs 要快一点,稳定一点我主要说下wkhtmltoimage的实现方案

实现步骤

安装环境

官网地址:https://wkhtmltopdf.org/

windows: 下载安装包安装即可

linux: 下载对应的安装包 ,还需安装对应中文字体(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

相关代码

利用java 执行命令 调用wkhtmltoImage 设置相关参数,具体参数查看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 设置为50 是比较合适的, 默认的94 可能会导致图片文件过大
		ProcessBuilder pb = new ProcessBuilder(htmlToImage, "--crop-w", "800", "--width", "800","--quality", "50",
				sourceFilePath, targetFilePath);
		Process process;
		try {
			process = pb.start();
			//注意,调用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("执行完成");
	}
}

踩坑记录

  • 如果html页面设置的宽高比较小, 这样截出来的图片也会比较小,比较模糊,, 增大html 的宽高,可以使图片更清晰,这样会导致截出来的图片文件更大,这样用户在小程序下载过程会更慢,这里需要自己权衡

  • wkhtmlImage 对 css3 linear-gradient 不支持,不能使用样式下划线,可以考虑使用图片代替

  • 中文字体需要声明引用,才能生效

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tangbikbe
系列文章
更多 icon
同类精品
更多 icon
继续加载