您的位置:首页 > Web前端 > HTML

使用flying-saucer-pdf将html转pdf

2016-06-04 22:39 543 查看
直接上代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;

/**
*
* @date 2016年6月4日下午6:01:57
* @author 赵
*
*/
public class ConvertHtmlToPdfWithFly {
public void convert() {
FileOutputStream os = null;
try {
ITextRenderer renderer = new ITextRenderer();
os = new FileOutputStream("D:\\4.pdf");
String path = "D:\\7l3ra1b9ho8np.html";
renderer.setDocument(new File(path).toURI().toURL().toString());
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/SimSun.ttc", BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (os != null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


注意事项:
html文件的顶层的宽度最好设置为80%,这样输出成A4时效果比较好
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  flying-saucer-pdf html pdf