在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件iText。通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或下载得到生成的报表,这样就很好的解决了B/S系统的报表处理问题。
iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
一、下载jar并导入项目
iText-2.1.5.jar+iTextAsian-1.5.2.jar (密码:5GAp)
iTextAsian-1.5.2.jar主要用于中文的支持,下面实例代码中有注解说明。
二、实例SS代码(亲测可用)
package com.csyor.util;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
public class GeneratePdf {
private void handleText(PdfWriter writer, String content, Color color,
float x, float y, float z)
throws DocumentException, IOException {
PdfContentByte canvas = writer.getDirectContent();
//pdf文档中中文字体的设置,注意一定要添加iTextAsian.jar包
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL,color);
Phrase phrase = new Phrase(content,fontChinese);
ColumnText.showTextAligned(
canvas, Element.ALIGN_UNDEFINED, phrase, x, y, z);
}
public File Pdf(String imagePath, String mOutputPdfFileName) {
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter writer = PdfWriter.getInstance
(doc,new FileOutputStream(mOutputPdfFileName));
doc.open();
doc.newPage();
Image png1 = Image.getInstance(imagePath);
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = this.getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.setAlignment(Image.TEXTWRAP);
png1.scalePercent(percent + 3);
doc.add(png1);
this.handleText(writer, "Csyor.com测试", Color.RED, 400, 725, 0);
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
return mOutputPdfFile;
}
public int getPercent1(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}
private int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
//main()方法测试
public static void main(String[] args) {
GeneratePdf gp = new GeneratePdf();
String pdfUrl = "D:\\pdf.pdf";
File file = gp.Pdf("D:\\csyor.jpg", pdfUrl);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上内容来自于网络,如有侵权联系即删除。
猜你喜欢
发表评论
电子邮件地址不会被公开。 必填项已用*标注