java html转pdf 无法支持中文_java转pdf(html转为pdf),解决中文乱码,标签不规范等问题...
第一步,下载jar包以及建对应的文件夹。注意pd4ml的jar要选择pro版本。然后建一个pd4fonts.properties
里面对应的字体。
SimSun = simsun.ttf
前面为变量名,后面要对应你下载好的字体。网上都有各种字体下载。相应步骤做完了,做完后的文件夹如图格式都有了!
注意要引入图片中对应的jar下面的三个jar包到项目中去。
以下为从文件读取到数据再作导出功能。
import java.awt.Insets;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.security.InvalidParameterException;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
public class Test {
protected int topValue = 10;
protected int leftValue = 20;
protected int rightValue = 10;
protected int bottomValue = 10;
protected int userSpaceWidth = 1300;
/**
* @param args
*/
public static void main(String[] args) {
try {
Test jt = new Test();
//此处填写你的html文件
String html = readFile("/Users/wangchen/Desktop/370fx2.html", "UTF-8");
//此处填写你下载的地方
jt.doConversion2(html, "/Users/wangchen/Desktop/370fx2.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doConversion2(String htmlDocument, String outputPath)
throws InvalidParameterException, MalformedURLException,
IOException {
PD4ML pd4ml = new PD4ML();
pd4ml.enableDebugInfo();
pd4ml.setHtmlWidth(userSpaceWidth);
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,
rightValue));
//此处的classPath注意一定要获取到你放fonts的文件夹。他需要获取到你下载的字体
String classPath = Test.class.getResource("/")+"fonts";
pd4ml.useTTF(classPath, true);
pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pd4ml.render(new StringReader(htmlDocument), baos);
baos.close();
File output = new File(outputPath);
java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
fos.write(baos.toByteArray());
fos.close();
}
private final static String readFile(String path, String encoding)
throws IOException {
File f = new File(path);
FileInputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
byte buffer[] = new byte[2048];
int read;
do {
read = is.read(buffer, 0, buffer.length);
if (read > 0) {
fos.write(buffer, 0, read);
}
} while (read > -1);
fos.close();
bis.close();
is.close();
return fos.toString(encoding);
}
}
如上你就可以下载将html转为pdf了。任意文本也可以转为pdf,经测试,可用
附件如下:https://pan.baidu.com/s/1wSvBM6Kti4IpI9IlDaycew
以下为浏览器下载pdf的工具类。直接调用红色的方法即可。htmlDocument 为你要导出的数据,response为该次请求的响应体,fileName为下载的名字
package com.ccb.common.utils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.security.InvalidParameterException;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
/**
* @author caihong
* @time 2019/1/28
*/
public class PDFUtil {
private static String PDF_TYPE="application/pdf";
private static String classpath=PDFUtil.class.getResource("/").getPath();
protected static int topValue = 10;
protected static int leftValue = 20;
protected static int rightValue = 10;
protected static int bottomValue = 10;
protected static int userSpaceWidth = 1300;
public static void pdf4htmlToPdf(String htmlDocument,HttpServletResponse response, String filename)throws InvalidParameterException,
IOException {
PD4ML pd4ml = new PD4ML();
pd4ml.enableDebugInfo();
pd4ml.setHtmlWidth(userSpaceWidth);
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,rightValue));
pd4ml.useTTF(classpath+"fonts", true);
pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pd4ml.render(new StringReader(htmlDocument), baos);
baos.close();
renderPdf(response,baos.toByteArray(),filename);
}
public static void renderPdf(HttpServletResponse response, final byte[] bytes, final String filename) {
initResponseHeader(response, PDF_TYPE);
setFileDownloadHeader(response, filename, ".pdf");
if (null != bytes) {
try {
response.getOutputStream().write(bytes);
response.getOutputStream().flush();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* 分析并设置contentType与headers.
*/
private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) {
// 分析headers参数
String encoding = "utf-8";
boolean noCache = true;
for (String header : headers) {
String headerName = StringUtils.substringBefore(header, ":");
String headerValue = StringUtils.substringAfter(header, ":");
if (StringUtils.equalsIgnoreCase(headerName, "utf-8")) {
encoding = headerValue;
} else if (StringUtils.equalsIgnoreCase(headerName, "no-cache")) {
noCache = Boolean.parseBoolean(headerValue);
} else {
throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
}
}
// 设置headers参数
String fullContentType = contentType + ";charset=" + encoding;
response.setContentType(fullContentType);
if (noCache) {
// Http 1.0 header
response.setDateHeader("Expires", 0);
response.addHeader("Pragma", "no-cache");
// Http 1.1 header
response.setHeader("Cache-Control", "no-cache");
}
return response;
}
/**
* 设置让浏览器弹出下载对话框的Header.
* @param
*/
public static void setFileDownloadHeader(HttpServletResponse response, String fileName, String fileType) {
try {
// 中文文件名支持
String encodedfileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + fileType + "\"");
} catch (UnsupportedEncodingException e) {
}
}
private final static String readFile(String path, String encoding)
throws IOException {
File f = new File(path);
FileInputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
java.io.ByteArrayOutputStream fos = new java.io.ByteArrayOutputStream();
byte buffer[] = new byte[2048];
int read;
do {
read = is.read(buffer, 0, buffer.length);
if (read > 0) {
fos.write(buffer, 0, read);
}
} while (read > -1);
fos.close();
bis.close();
is.close();
return fos.toString(encoding);
}
}
自己完成controller,以及mapping映射后,注意要用get请求
http://localhost:8080/api/img/exportPdf?htmlDocument=12%E7%9A%84%E5%8F%91%E9%A1%BA%E4%B8%B0%E9%98%BF%E6%96%AF%E9%A1%BF%E5%8F%91%E9%80%81%E5%88%B0%E5%8F%91%E9%80%81%E5%A4%A7&fileName=123
便可以下载pdf了
java html转pdf 无法支持中文_java转pdf(html转为pdf),解决中文乱码,标签不规范等问题...相关推荐
- java html转pdf 无法支持中文_java项目实现html转pdf的需求(支持中文和CSS样式)
java项目中用到了html转pdf的需求,现在写一个自己认为最优方案的总结,虽然还是有一些小的bug 为了保证中文的支持需要在被转换的html添加body的添加中文字体样式,保持这个字体和后边转换p ...
- java pdf模版的遍历_java使用itext操作填充pdf模板
一.先创建pdf模板 1.先用word做出界面 image.png 2.再转换成pdf格式 image.png image.png 3.用Adobe Acrobat 打开你刚刚用word转换成的pdf ...
- java pdf 转word源码_Java 实现word模板转为pdf
1. pom相关依赖 工具poi-tl (操作word文档模板) + jacob (将操作后的word模板转为pdf) com.deepoove poi-tl 1.9.1 com.jacob jaco ...
- php把excel转换成pdf文件下载,laravel怎么可以把excel文件转为pdf文件?
laravel怎么可以把excel文件转为pdf文件? 尝试用PHPOffice/PhpSpreadsheet转换,写了个函数,如下: 备注:PhpSpreadsheet是PHPExcel的新版,ht ...
- php imagettftext 中文,php的GD库imagettftext函数解决中文乱码问题,_PHP教程
php的GD库imagettftext函数解决中文乱码问题, 本文实例讲述了php的GD库imagettftext函数解决中文乱码问题的方法.分享给大家供大家参考.具体如下: 使用imagettfte ...
- java数字转中文_Java程序:输入数字转换成中文输出
功能看似简单,但真正实现起来也不是易事 现在贴出代码,欢迎各位幕友提出建议!! package test01; import java.util.Scanner; public class Test ...
- java判断字符串有中文_JAVA入门之正则表达式判断字符串包含中文
测试程序运行结果!可以看到,程序可以正确判断出用户输入的信息字符串是否包含中文! 整个程序代码如下: import java.io.BufferedReader; import java.io.IOE ...
- java解压_Java ZIP压缩和解压缩文件(解决中文文件名乱码问题)
JDK中自带的ZipOutputStream在压缩文件时,如果文件名中有中文,则压缩后的 zip文件打开时发现中文文件名变成乱码. 解决的方法是使用apache-ant-zip.jar包(见附件)中的 ...
- java 读取txt乱码_java 逐行读取txt文本如何解决中文乱码
java读取txt文本中如含有中文,可能会出现乱码,解决方案是: 1.要统一编码,java工程的编码,txt文本编码,java工程中的java文本编码都统一为utf-8: 2.利用 InputStre ...
- java 判断是否包含中文_Java中判断字符串中是否包含中文汉字
一般在用户登录时需要判断用户名是否为中文汉字,可以使用正则表达式,来匹配字符是否包含中文,中文通配符为[u4e00-u9fa5]匹配中文,下面为大家分享一下使用Matcher来解决此问题. 代码如下: ...
最新文章
- (附链接)CVPR 2022 | 模型难复现不一定是作者的错,最新研究发现模型架构要背锅...
- 为何把日志打印到控制台很慢?
- Xen与KVM虚拟化技术调研报告
- 常用maven插件总结
- 系统管理员不可错过的6款服务器监控工具
- HDFS权限设置 \ HDFS涉及ACLs的命令
- xtrabackup备份mysql“ib_logfile0 is of different”错误分析
- eShopOnContainers 知多少[9]:Ocelot gateways
- python公式_Python读取excel文件中带公式的值的实现
- 【进阶篇】Vue Devtools——vue开发调试神器
- pytorch是否可以使用CUDA
- 基于角色的访问控制模型(RBAC)——学习笔记
- Python中DataFrame按照行遍历
- 拓端tecdat|基于keras平台CNN神经网络模型的服装识别分析
- 汉诺塔问题(C语言实现)
- 单台服务器百万并发实现 C10K, C1000K, C10M
- 机器人标准DH建模法
- js数组操作的一些方法在面试题的使用
- 移除未排序链表中的重复节点,保留最开始出现的节点
- 桌面应用程序脚本录制