您的位置:首页 > 编程语言 > Java开发

java中用itext写PDF文件并输出下载

2010-09-12 14:53 375 查看
在Playframework中,通过浏览器弹出窗口的方式下载PDF文件。

PDF文件是用iText生成的,支持中文。

获取中文自己的一段配置文件的代码:

private static final String pdfFont = Play.configuration.getProperty("pdf.font");
配置文件
pdf.font=c:/windows/fonts/simsun.ttc,1


创建文件并下载

List<Dailylog> logs = Dailylog.find("userid = ? order by pubtime desc", Long.parseLong(session.get("USERID"))).fetch();
response.contentType = "application/pdf";
//A4纸大小,到各个边框的距离为36
document = new Document(PageSize.A4, 36, 36, 36, 36);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {

//增加对中文的支持
BaseFont baseFont = BaseFont.createFont(pdfFont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(baseFont, 12, Font.NORMAL);
PdfWriter.getInstance(document, buffer);

//设置表格为2列,第一列宽度为20%,第二列宽度为80%
float[] widths = { 0.2f, 0.8f};
PdfPTable table = new PdfPTable(widths);

for(Integer i = 0 ; i < logs.size() ; i ++){
PdfPCell cell = new PdfPCell(new Paragraph(logs.get(i).user.truename, fontChinese));
//单元格合并
cell.setColspan(2);
table.addCell(cell);

cell.setBorderWidth(50F);
cell = new PdfPCell(new Paragraph(logs.get(i).pubtime.toString(), fontChinese));
table.addCell(cell);
cell = new PdfPCell(new Paragraph(logs.get(i).content, fontChinese));
table.addCell(cell);
}
document.open();
document.add(table);
document.close();
DataOutput output = new DataOutputStream(response.out);
byte[] bytes = buffer.toByteArray();
response.setHeader("Content-Disposition", "attachment; filename=" + simpleDateFormat.format(new Date()) + ".pdf");
response.setHeader("Content-Length", "" + bytes.length);
for(Integer i = 0; i < bytes.length ; i ++){
output.write(bytes[i]);
}


输出PDF的格式为

------------------------ 一行一列

----|------------------- 一行两列
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: