html模板转pdf

工具方法:
public void createPdf(String htmlFilePath,SelectParamRequest paramRequest){
if(paramRequest.getProductNamr() == null || paramRequest.getClassificationName() == null){
System.out.println("有空值!!!");
return;
}
//2.读取对应文件位置的html模板
String htmlStr = PDFUtil.readHtmlFileByPath(htmlFilePath);
//3.替换模板html中对应的元素
htmlStr = changeHtmlTemp (htmlStr, paramRequest);
//4.由于jsoup转换html时不是按照xhtml格式,因此需要jtidy进行一次转换
htmlStr = PDFUtil.changeHtmlStrToXhtml(htmlStr);
//5.生成对应路径下的pdf 生成pdf的路径,pdf名字
PDFUtil.createPDFFileByHtmlStrInPath (htmlStr, paramRequest.getPDFPath(),paramRequest.getPDFName());
}

//2.读取对应文件位置的html模板
private static final String ENCODING="UTF-8";

public static String readHtmlFileByPath (String htmlFilePath) {
System.out.println("读取的模板路径:"+ htmlFilePath);
StringBuilder content = new StringBuilder ();
String lineStr;
InputStream fileInputStream = null;
BufferedReader reader = null;
try {
//1.读取对应文件位置的html模板/static/temphtml/product.html
/*
fileInputStream = new FileInputStream("E:\\workspace\\mytest\\alibaba\\src\\main\\resources\\static\\temphtml\\product.html");
*/
fileInputStream = PDFUtil.class.getResourceAsStream (htmlFilePath);

if (fileInputStream==null){
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!1");
}
reader = new BufferedReader(new InputStreamReader(fileInputStream, ENCODING));
while ((lineStr = reader.readLine()) != null) {
content.append (lineStr);
content.append("\n");
}
} catch (FileNotFoundException e) {
throw new MyException("对应路径["+htmlFilePath+"]文件没找到",e.getMessage());
} catch (IOException e) {
throw new MyException("读取对应路径["+htmlFilePath+"]文件错误",e.getMessage());
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close ();
} catch (IOException e) {
throw new MyException("关闭["+htmlFilePath+"]文件流异常",e.getMessage());
}
}
}
return content.toString ();
}
//3.替换模板html中对应的元素
public String changeHtmlTemp (String htmlStr,SelectParamRequest paramRequest) {
Document doc = Jsoup.parse (htmlStr);
Element fenleinameEle = doc.getElementById ("fenlei"); //对应html标签的id值
fenleinameEle.text (paramRequest.getClassificationName());
Element chanpinEle = doc.getElementById ("chanping");
chanpinEle.text(paramRequest.getProductNamr());
Element xinghaoEle = doc.getElementById ("xinghao");
xinghaoEle.text (paramRequest.getSpecifacationName());

return doc.html();
}

public static String changeHtmlStrToXhtml(String htmlStr) {
ByteArrayInputStream inStream = new ByteArrayInputStream(htmlStr.getBytes());
ByteArrayOutputStream tidyOutStream = new ByteArrayOutputStream();
Tidy tidy = new Tidy();
tidy.setInputEncoding(ENCODING);
tidy.setQuiet(true);
tidy.setOutputEncoding(ENCODING);
tidy.setShowWarnings(false); //不显示警告信息
tidy.setIndentContent(true);//
tidy.setSmartIndent(true);
tidy.setIndentAttributes(false);
tidy.setWraplen(1024); //多长换行
//输出为xhtml
tidy.setXHTML(true);
tidy.setErrout(new PrintWriter(System.out));
tidy.parse(inStream, tidyOutStream);
return tidyOutStream.toString();
}
 
  public static void createPDFFileByHtmlStrInPath (String htmlStr, String storagePath,String pdfName){
FileOutputStream fileOutputStream = null;
try {
File path = new File (storagePath);
File file = new File(path,pdfName);

if(! path.exists()) {
path.mkdirs();
}
if ( !file.exists()) {
if(!file.createNewFile ()){
throw new MyException("对应地址["+storagePath+"]文件创建失败");
};
}
fileOutputStream = new FileOutputStream (file);
ITextRenderer renderer = new ITextRenderer ();
// 解决中文支持问题
ITextFontResolver resolver = renderer.getFontResolver ();
resolver.addFont ("/static/font/arialuni.ttf", BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
resolver.addFont ("/static/font/simhei.ttf", BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
resolver.addFont ("/static/font/simsun.ttc", BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString (htmlStr);
// 解决图片的相对路径问题,图片路径必须以file开头
// renderer.getSharedContext().setBaseURL("file:/");
renderer.layout ();
renderer.createPDF (fileOutputStream);
} catch (IOException e) {
throw new MyException("向["+storagePath+"]路径生成pdf流错误",e.getMessage());
} catch (DocumentException e) {
throw new MyException("向["+storagePath+"]路径生成pdf文件流异常",e.getMessage());
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close ();
} catch (IOException e) {
throw new MyException("向["+storagePath+"]路径生成pdfio关闭异常",e.getMessage());
}
}
}
}




html模板:注意要设置
<style type="text/css">
.pdfBody{
margin-left: 2em;
font-size: 1.2em;
font-family: SimSun;
color: #666666;
margin-top: 3em;
}
</style>

<body >

<div class="pdfBody">
分类:<input type="text" id="fenlei"><br>

产品:<input type="text" id="chanping"><br>

型号:<input type="text" id="xinghao"><br>


<div>添加型号tjsx</div>
</div>

</body>


测试:
@RequestMapping("/createPdf.json")
@ResponseBody
public void createPdf(){
SelectParamRequest paramRequest = new SelectParamRequest();
paramRequest.setClassificationName("服装");
paramRequest.setProductNamr("童装");
paramRequest.setSpecifacationName("米老鼠");
paramRequest = initReceiptInfo(paramRequest);
try {
productService.createPdf("/static/temphtml/product.html",paramRequest);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getCause().getLocalizedMessage());
}
}
效果图:





猜你喜欢

转载自www.cnblogs.com/it-yansx666/p/9257394.html