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

富文本转pdf :

注意:simsun.ttc 可以百度下载://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" "//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=\"//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();
}
}


}

 

Tags: