html转pdf原理,HTML转PDF

public static void main(String[] args) {

StringBuffer sb = new StringBuffer();

String path = "C:\Windows\Fonts\simsun.ttc";//字体文件。必须要。不然无法显示中文

try {

BufferedReader reader = new BufferedReader(new FileReader(new File("D:\123\abc.html")));//需要生成pdf的html文件

String line = null;

while((line = reader.readLine()) != null){

sb.append(line).append("

");

}

ITextRenderer render = new ITextRenderer();

ITextFontResolver font = render.getFontResolver();

font.addFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

OutputStream out = new FileOutputStream(new File("D:\wasapp\miclm\photo\20140110\700029151\cache\outCache103.pdf"));//生成后的pdf文件

render.setDocumentFromString(sb.toString());

render.getSharedContext().setBaseURL("file:\D:\123\");//设置图片html文件中图片的路径。需要在“123”文件夹下有html文件中需要的图片

render.layout();

render.createPDF(out);

out.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (DocumentException e) {

e.printStackTrace();

}

}

在html文件头部需要指定字体:

body {font-family:SimSun;}//字体

@page{size: 11.69in 8.27in;}//字体及页面大小

注:生成pdf文件的html文件必须遵循严格的html格式。有开始标签就必须有相应的闭合标签!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值