富文本转pdf :

注意:simsun.ttc 可以百度下载:http://www.pc6.com/softview/SoftView_100415.html

package com.orangecds.officeconvert.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.lowagie.text.pdf.BaseFont;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @program: office-convert
* @ClassName PdfUtilsTest
* @description:
* @author: xiyun.zhao
* @create: 2021-09-27 14:17
**/
public class PdfUtilsTest {
/**
* @description: 将HTML转成PD格式的文件html文件的格式比较严格
* @author xiyun.zhao
* @param: htmlFile
* @param: pdfFile
* @return:
* @date: 2021/9/27 18:50
*/
// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
public static void html2pdf(String htmlFile, String pdfFile) throws Exception {
// step 1
String url = new File(htmlFile).toURI().toURL().toString();
System.out.println(url);
// step 2
OutputStream os = new FileOutputStream(pdfFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);

// step 3 解决中文支持
ITextFontResolver fontResolver = renderer.getFontResolver();
if("linux".equals(getCurrentOperatingSystem())){
//Linux下的和Windows的不一样,要自己下载,不要拷贝Windows的到Linux
fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}else{
fontResolver.addFont("src/main/resources/dev/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}

renderer.layout();
renderer.createPDF(os);
os.close();

System.out.println("create pdf done!!");

}
/**
* html转换成pdf文件
*
* @param htmlContent
* @throws Exception
*/
protected static void htmlToPdf(String htmlContent,String pdfFile) throws Exception {
//1 打开文件流
Document document = new Document();
FileOutputStream fos = new FileOutputStream(pdfFile);
InputStream is = new ByteArrayInputStream(htmlContent.getBytes(Charset.forName("UTF-8")));
// InputStream cssIs = new ByteArrayInputStream(getCssFile());
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, fos);
//3. 设置字体
XMLWorkerFontProvider fontProvider1 = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider1.register("D:\\hjf\\simsunttc\\simsun.ttc");
//3 打开文档
document.open();
//4 html转为pdf
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is, Charset.forName("UTF-8"), fontProvider1);

} catch (DocumentException | IOException e) {
throw new RuntimeException("转pdf失败罗~");
} finally {
if (null != writer) {
writer.flush();
}
//5 关闭文档
document.close();
fos.close();
is.close();
writer.close();
}
}

public static String getCurrentOperatingSystem(){
String os = System.getProperty("os.name").toLowerCase();
System.out.println("---------当前操作系统是-----------" + os);
return os;
}
/**
* 获取html
*
* @return
*/
protected static String content2Html() {
String content = COMPLETE_CONTENT;
content = content.replace("<br>", "<br/>");
String repContent = content.replaceAll("<img(.+?)>", "<img$1/>");
System.out.println(""+repContent);
return repContent;
}
/**
* 获取样式文件
*
* @return
* @throws Exception
*/
protected byte[] getCssFile() throws Exception {
FileInputStream fileInputStream = new FileInputStream("src/main/resources/css/editor.css");
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1204];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
fileInputStream.close();
return outStream.toByteArray();
}
/**
* 拼接CONTENT 使成为完整的html,\"font-family: SimSun;\"
*/
private static final String COMPLETE_CONTENT = "<html><head></head><body style=\"font-family: SimSun;\"><p class=\"ql-align-center\"><strong>合同内容测试</strong></p><p><strong>甲方(出租方) :</strong></p><p><strong>乙方(承租方) :</strong></p><p>甲乙双方就乙方租赁甲方电梯轿厢设置看板媒体(以下简称“看板”)、刊发广告一</p><p>事进行友好协商,达成以下条款,双方共同执行:</p><p class=\"ql-align-center\"><strong>第一条租赁地点</strong></p><p>甲方同意将市区花园(大厦/小区)共部电梯租赁给乙方设置看板,刊发广告。</p><p class=\"ql-align-center\"><strong>第二条设置方式和范围</strong></p><p>1、看板设置于电梯轿厢壁上(超薄型,厚度不超过2cm、长度:、宽度: ;),用</p><p>粘贴或敷膜方式贴在轿厢壁上,共三面(左、中、右),</p><p>2、采用进口美国3m技术贴敷在电梯厅门上; (学生打架调解协议书)</p><p>3、电梯轿厢(面向电梯i ]及出梯门时目光所能触及的轿厢壁)。</p>" +
"<p class=\"ql-align-center\"><strong>第三条设置内容</strong></p><p>1、公益广告(包括社区文化建设、公民道德规范、防火、防盗知识、保健小常识、</p><p>生活小窍门等) ;</p>" +
"<p>2、商业广告(广告内容必须符合国家广告法的规定,不得发布不宜单位、社区和家<img src=\"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic16.nipic.com%2F20111008%2F5203963_093910733000_2.jpg&refer=http%3A%2F%2Fpic16.nipic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1635329488&t=9d73780cedba58d89b052512d894955c\" style=\"max-width:100%;\"></p><p>庭的广告,更不得发布影响少年儿童身心健康的广告) ;</p><p class=\"ql-align-right\"><br></p></body></html>";

public static void main(String[] args) {

String htmlFile = "D:\\hjf\\u.html";
String pdfFile = "D:/hjf/z.pdf";
try {
//html以文件形式转pdf
// PdfUtilsTest.html2pdf(htmlFile, pdfFile);
//以字符串形式转pdf
PdfUtilsTest.htmlToPdf(content2Html(),pdfFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

}

使用jacob调用Windows的com对象,进行word、ppt等转换成ptf、html(二)的更多相关文章

  1. java中将数组、对象、Map、List转换成JSON数据

    如果要将数组.对象.Map.List转换成JSON数据,那我们需要一些jar包: json-lib-2.4-jdk15.jar ezmorph-1.0.6.jar commons-logging.ja ...

  2. JS中JSON.stringify()方法,将js对象(json串)转换成字符串,传入服务器

    JSON 通常用于与服务端交换数据. 在向服务器发送数据时一般是字符串. 我们可以使用 JSON.stringify() 方法将 JavaScript 对象转换为字符串. 语法 JSON.string ...

  3. 调用get_str_time(时间), 就能把毫秒的时间转换成格式化的 ,转化时间戳的方法

    function get_str_time(time){ var datetime = new Date(); datetime.setTime(time); var year = datetime. ...

  4. 使用springcloud的feign调用服务时出现的错误:关于实体转换成json错误的介绍

    http://blog.csdn.net/java_huashan/article/details/46428971 原因:实体中没有添加无参的构造函数 fastjson的解释: http://www ...

  5. JavaScript 系列--JavaScript一些奇淫技巧的实现方法(二)数字格式化 1234567890转1,234,567,890;argruments 对象(类数组)转换成数组

    一.前言 之前写了一篇文章:JavaScript 系列--JavaScript一些奇淫技巧的实现方法(一)简短的sleep函数,获取时间戳 https://www.mwcxs.top/page/746 ...

  6. python class对象转换成json/字典

    # -*- encoding: UTF-8 -*- class Student: name = '' age = 0 def __init__(self, name, age): self.name ...

  7. 将Xml字符串转换成(DataTable || DataSet || XML)对象

    今天用到一个功能:就是把从数据库读出来的内容转换成XML字符串流格式,并输出给一个功能函数.在写的过程,为方便以后的使用,我对这一功能进行分装.该类的具体格式如下:XmlConvert类命名空间:Ni ...

  8. 分享:根据svg节点对象类型和路径值转换坐标值

    功能用处: 对svg文件的路径节点填充时会使用(相邻两个坐标区域内的四边形的填充颜色不重复). 需要对svg文件中的Path节点或者 Polyline 节点做颜色填充.并且相邻的两个区域之间的颜色不允 ...

  9. JSON对象转换成JSON字符串

    1.问题背景 有一个json对象,需要将其转换成json字符串 JSON.stringify(obj) 2.实现源码 <!DOCTYPE html PUBLIC "-//W3C//DT ...

随机推荐

  1. 【SpringMVC】@RequestMapping注解

    @RequestMapping注解的源码 @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNT ...

  2. C# 如何在编译时将 dll 复制到 bin\Release 目录下

    下面假设 Project 名为 Gamma4RTD,需要调用的 dll 文件为 rtddll.dll.IDE 是 Visual Studio 2015 打开 Visual Studio 2015 -& ...

  3. C#异步编程2

  4. 【多线程】不懂什么是 Java 中的锁?看看这篇你就明白了!

    本文来源:Java建设者 原文地址:https://mp.weixin.qq.com/s/GU42BjM5jY2CEMVD_PAZBQ Java 锁分类 Java 中的锁有很多,可以按照不同的功能.种 ...

  5. Mybatis轻松入门(仅要求会用看着一个就够了,略过源码分析部分即可)

    文章目录 ==一.概念== 二.快速入门 1.开发步骤 2.环境搭建 2.1.导入Mybatis的坐标和其他坐标 2.2.创建User表 2.3.编写实体 2.4.编写UserMapper配置文件 2 ...

  6. Linux下用gdb 调试、查看代码堆栈

      Linux中用gdb 查看代码堆栈的信息 core dump 一般是在segmentation fault(段错误)的情况下产生的文件,需要通过ulimit来设置才会得到的. 调试的话输入: gd ...

  7. tomcat Debug 启动

    eclipse有web工程,将打包为war包(export -> War file) 将打包好的war 包放在tomcat 的webapps下面: 配置debug: 参考来自 http://bl ...

  8. 使用Operator State方式

    使用 operator state的方式有以下几种: 方式一: stateful function(RichFunction) 实现 CheckpointFunction 接口 必须实现两个方法:Vo ...

  9. C语言编译步骤

    C语言编译步骤:   1.预处理(hello.i ):宏定义展开.条件编译等,同是将代码中的注释删除,这里并不会检查语法 2.编译(hello.s):检查语法,将预处理后文件编译生成汇编文件. 3.汇 ...

  10. RHCS集群架构之mysql及共享存储iscsi

    server1 172.25.7.1(配置Nginx.ricci和luci) server2 172.25.7.2(Apache.iscsi) server3 172.25.7.3(Apache) s ...