富文本转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. qt 定义插件

    定义的接口----------------------------------------------#ifndef REGEXPINTERFACE_H #define REGEXPINTERFACE ...

  2. C# 单元测试,测试资源管理器里面没有需要的单元测试

    已经创建了单元测试,却无法运行,更改引用的程序集,将TestPlatform换位QualityTools.UnitTestFramework.具体原因尚未分析,随笔记录.

  3. The Programmer's Oath程序员的誓言----鲍勃·马丁大叔(Bob Martin)

    In order to defend and preserve the honor of the profession of computer programmers, I Promise that, ...

  4. java web课程设计(简单商城的前后端双系统,基于maven三模块开发)

    1.系统分析 1.1需求分析 实现一个简单但功能完整的商城项目,从设计到实现,规范化完成该项目,锻炼javaweb项目的编写能力,理解软件工程的软件设计思想 1.2编程技术简介 本次课程主要使用的软件 ...

  5. Java程序设计学习笔记(五) — 多线程

    时间:2016-4-15 09:56 --多线程(还有多核编程)     1.进程         进程是一个正在执行中的程序.         每一个进程执行都有一个执行顺序,该顺序是一个执行路径, ...

  6. centos7 查看端口占用情况

    2021-08-02 1. 查看端口占用情况 # 查看 8088 端口占用情况 lsof -i tcp:8088 # 若提示没有 lsof 命令, yum 安装一下 yum -y install ls ...

  7. 基于Linux的系统排错

    1.系统引导过程概述 2.系统异常及恢复 [1]grub系统引导 1)mbr上446字节丢失 模拟问题: dd if=/dev/zero? of=/dev/vda? bs=446? count=1? ...

  8. HCNP Routing&Switching之OSPF LSA更新规则和路由汇总

    前文我们了解了OSPF外部路由类型以及forwarding address字段的作用,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/15225673.html: ...

  9. Powershell免杀从入门到实践

    转载https://www.jianshu.com/p/fb078a99e0d8 前言 文章首发于Freebuf 在之前发布的一篇 渗透技巧之Powershell实战思路 中,学习了powershel ...

  10. 一、Rabbitmq的简单介绍

    以下只是本人从零学习过程的整理 部分内容参考地址:https://www.cnblogs.com/ysocean/p/9240877.html 1.RabbitMQ的概念 RabbitMQ是实现了高级 ...