Java导出pdf

package cn.it;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.HtmlParser;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

public class htmltopdf {
public static void main(String[] args) {htmltopdf ih = new htmltopdf();
ih.htmlCodeComeFromFile("D:\\xia\\main.html", "D:\\xia\\iText_3.pdf");
// ih.htmlCodeComeString("Hello中文", "D: \\test\\iText_2.pdf");

}
public void htmlCodeComeFromFile(String filePath, String pdfPath) {
Document document = new Document();
try {
StyleSheet st = new StyleSheet();
st.loadTagStyle("body", "leading", "16,0");
PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
Paragraph t = new Paragraph(filePath, FontChinese);
ArrayList p = HTMLWorker.parseToList(new FileReader(filePath), st);
for(int k = 0; k < p.size(); ++k) {
document.add((Element)p.get(k));
}
document.close();
System.out.println("文档创建成功");
}catch(Exception e) {
e.printStackTrace();
}
}
public void htmlCodeComeString(String htmlCode, String pdfPath) {
Document doc = new Document(PageSize.A4);
try {
PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
doc.open();
// 解决中文问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
Paragraph t = new Paragraph(htmlCode, FontChinese);
doc.add(t);
doc.close();
System.out.println("文档创建成功");
}catch(Exception e) {
e.printStackTrace();
}
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值