package com.lcw.one.util.utils;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import com.lcw.one.util.utils.string.UUID;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* 网页转PDF工具类
*/
public class PdfUtils {
private String fontPath;
public PdfUtils(String fontPath) {
this.fontPath = fontPath;
}
/**
* 将HTML转成PD格式的文件。html文件的格式比较严格
*
* @param html
* @throws Exception
*/
public File html2pdf(String html) throws Exception {
// 生成PDF临时文件目录
String filePath = FileUtils.getTempDirectoryPath() + UUID.randomUUID10() + ".pdf";
File pdfFile = new File(filePath);
OutputStream os = new FileOutputStream(pdfFile);
ITextRenderer renderer = new ITextRenderer();
installFont(renderer); // 初始化字体
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(os);
os.close();
os.close();
return pdfFile;
}
/**
* 初始化字体
* @param renderer
* @throws DocumentException
* @throws IOException
*/
private void installFont(ITextRenderer renderer) throws DocumentException, IOException {
String fontFolderPath = this.fontPath + FileUtils.FILE_SEPARATOR + "font" + FileUtils.FILE_SEPARATOR;
// 解决中文支持
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(fontFolderPath + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
fontResolver.addFont(fontFolderPath + "Arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
public static String getCurrentOperatingSystem() {
String os = System.getProperty("os.name").toLowerCase();
System.out.println("---------当前操作系统是-----------" + os);
return os;
}
}
记录Html转pdf实例工具类
最新推荐文章于 2022-02-11 17:03:13 发布