一、什么是PDF
PDF全称Portable Document Format,是Adobe公司开发的电子文件格式。这种文件格式与操作系统平台无关,也就是说,PDF文件不管是在Windows,Unix还是在苹果公司的Mac OS操作系统中都是通用的。这一特点使它成为在Internet上进行电子文档发行和数字化信息传播的理想文档格式。越来越多的电子图书、产品说明、公司文告、网络资料、电子邮件开始使用PDF格式文件。PDF格式文件目前已成为数字化信息事实上的一个工业标准。
PDF文件格式可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中。一般pdf的纸张默认是A4型号。
二、项目运用
1.Maven项目需要添加以下依赖:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.8</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.定义抽象类CreatePdf
package cn.sh.sstic.exp.pdf;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.log4j.Logger;
import cn.sh.sstic.exp.comm.base.util.ConfigUtil;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
public abstract class CreatePdf
{
protected Logger log = Logger.getLogger(getClass());
protected String outfile;
private String imgPath;
protected void setOutfile(String outfile) {
this.outfile = outfile;
}
protected void setImgPath(String imgPath){
this.imgPath = imgPath;
}
/**
* 生成水印的内部类,itext推荐采用内部类使用
*
*/
protected class Watermark extends PdfPageEventHelper{
private Image image = null;
private PdfTemplate total = null;
private Font f = null;
private String header = "";
/**
* 生成水印图片,图片只生成一次,
*/
public void onOpenDocument(PdfWriter writer,Document document){
f = createFont(8F, Font.NORMAL, BaseColor.BLACK);
total = writer.getDirectContent().createTemplate(8, 12);
if(imgPath==null){
imgPath = ConfigUtil.getProperty("mark");
log.warn(String.format("未设置PDF水印地点,已配置文件地址[%s]地址为准", imgPath));
}
try {
image = Image.getInstance(imgPath);
image.setAbsolutePosition(87.5F, 230F);
image.scaleAbsolute(400F, 400F);
} catch (BadElementException e) {
log.error("生成水印文件出现BadElementException异常",e);
} catch (MalformedURLException e) {
log.error("生成水印文件出现MalformedURLException异常",e);
} catch (IOException e) {
log.error("生成水印文件出现IOException异常",e);
}
}
public void onEndPage(PdfWriter writer,Document document){
PdfContentByte contentByte = writer.getDirectContentUnder();
try {
contentByte.addImage(image);
} catch (DocumentException e) {
log.error("生成水印向PDF中添加时发生DocumentException异常",e);
}
ColumnText.showTextAligned(contentByte, Element.ALIGN_CENTER, null, 50f, 50f,0f);
PdfPTable table = new PdfPTable(new float[]{100F});
table.setTotalWidth(465F);
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(20F);
table.getDefaultCell().setBorder(Rectangle.TOP);
table.addCell(header);
PdfPTable tablef = new PdfPTable(new float[]{22f,8f,15f,8f,47f});
tablef.setTotalWidth(150f);
PdfPCell pcf = new PdfPCell(new Phrase("第",f));
pcf.setVerticalAlignment(Element.ALIGN_TOP);
pcf.setHorizontalAlignment(Element.ALIGN_RIGHT);
pcf.setBorderWidth(Rectangle.NO_BORDER);
tablef.addCell(pcf);
pcf = new PdfPCell(new Phrase(Integer.toString(writer.getPageNumber()),f));
pcf.setVerticalAlignment(Element.ALIGN_TOP);
pcf.setHorizontalAlignment(Element.ALIGN_CENTER);
pcf.setBorderWidth(Rectangle.NO_BORDER);
tablef.addCell(pcf);
pcf = new PdfPCell(new Phrase("页 共",f));
pcf.setVerticalAlignment(Element.ALIGN_TOP);
pcf.setHorizontalAlignment(Element.ALIGN_RIGHT);
pcf.setBorderWidth(Rectangle.NO_BORDER);
tablef.addCell(pcf);
try {
pcf = new PdfPCell(Image.getInstance(total));
} catch (BadElementException e) {
log.error("添加总页数时出现异常",e);
}
pcf.setVerticalAlignment(Element.ALIGN_TOP);
pcf.setHorizontalAlignment(Element.ALIGN_CENTER);
pcf.setBorderWidth(Rectangle.NO_BORDER);
tablef.addCell(pcf);
pcf = new PdfPCell(new Phrase("页",f));
pcf.setVerticalAlignment(Element.ALIGN_TOP);
pcf.setHorizontalAlignment(Element.ALIGN_LEFT);
pcf.setBorderWidth(Rectangle.NO_BORDER);
tablef.addCell(pcf);
table.writeSelectedRows(0, -1, 65, 40, writer.getDirectContent());
tablef.writeSelectedRows(0, -1, 250, 40, writer.getDirectContent());
}
public void onCloseDocument(PdfWriter writer,Document document){
ColumnText.showTextAligned(total, Element.ALIGN_LEFT,
new Phrase(String.valueOf(writer.getPageNumber()-1),f),
2, 2, 0);
}
}
/**
* 中文宋体,可以设置字体颜色、大小、样式
* @param size 字体大小
* @param style 字体样式,推荐FontStyle注入
* @param color 字体色彩,推荐BaseColor注入
* @return
*/
public Font createFont(final float size,final int style,final BaseColor color){
BaseFont bf = null;
Font f = null;
try {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED);
f = new Font(bf);
f.setStyle(style);
f.setSize(size);
f.setColor(color);
} catch (DocumentException e) {
log.error("生成baseFont时出现DocumentException异常",e);
} catch (IOException e) {
log.error("生成baseFont时出现IOException异常",e);
}
return f;
}
}
3.定义工具类ProjectPdf
package cn.sh.sstic.exp.pdf;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class ProjectPdf extends CreatePdf
{
private final String HEADER="某某委员会\n某某邀请函";
private final float[][] COLUMNS = {{65F,80F,530F,790F},{65F,80F,530F,790F}};
private Map<String, Object> map;
public void setOutFile(String outfile){
setOutfile(outfile);
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
setImgPath(String.valueOf(map.get("purl")));
}
public void createPdf(){
OutputStream os = null;
Document document = null;
PdfWriter writer = null;
try{
os = new FileOutputStream(outfile);
document = new Document(PageSize.A4);
writer = PdfWriter.getInstance(document, os);
writer.setPageEvent(new Watermark());
document.open();
ColumnText columnText = new ColumnText(writer.getDirectContent());
columnText.addElement(createHeader());
columnText.addElement(createHello());
columnText.addElement(create_1());
columnText.addElement(create_2());
columnText.addElement(create_3());
columnText.addElement(create_4());
columnText.addElement(create_5());
columnText.addElement(create_6());
columnText.addElement(create_7());
columnText.addElement(create_8());
columnText.addElement(create_9());
columnText.addElement(create_10());
columnText.addElement(create_11());
int status = ColumnText.START_COLUMN;
int column = 0;
while(ColumnText.hasMoreText(status)){
columnText.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]);
status = columnText.go();
if(column==0){
document.newPage();
}
columnText.setYLine(COLUMNS[0][3]);
}
}catch(DocumentException e){
log.error("生成PDF时发生DocumentException异常",e);
}catch(IOException e){
log.error("生成PDF时发生IOException异常",e);
}finally{
if(document!=null){
document.close();
}
if(writer!=null){
writer.close();
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
log.error("关闭OutputStream时发生IOException异常",e);
}
}
}
}
private Paragraph createHeader(){
Font f = createFont(22F, Font.BOLD, BaseColor.BLACK);
Paragraph p=new Paragraph();
p.setAlignment(Element.ALIGN_CENTER);
p.setFont(f);
p.setLeading(24F);
p.setSpacingAfter(20f);
p.add(HEADER);
return p;
}
private Paragraph createHello(){
String hello=String.format("%s 专家:\n 您好!", map.get("userName"));
Paragraph p = createParaWithoutFirstIndent(hello);
p.setSpacingAfter(6F);
return p;
}
private Paragraph create_1(){
String str = String.format("%s中小企业技术创新资金财务预" +
"评已经开始了,某某委员会特聘请您作为%s的财务预评专家,参与项目评审工作。此次项目预评以网上评审的形式进行,请在" +
"%s到%s期间登录%s网站评审您所负责的项目。如 果您网上评审有困难,请及早与我们联系,以免耽误评审工作,感谢您对我们工作的支持。有关说明具" +
"体如下: ", map.get("nowYear"),map.get("proName"),map.get("startDt"),map.get("endDt"),map.get("webUrl"));
Paragraph p = createParaWithFirstIndent(str);
p.setSpacingAfter(11F);
return p;
}
private Paragraph create_2(){
String str = "一、评审信息:";
Paragraph p = createParaWithoutFirstIndent(str);
p.setSpacingAfter(11F);
return p;
}
private PdfPTable create_3(){
PdfPTable table = new PdfPTable(new float[]{12.5F,27.1F,28.7F,4F,27.7F});
table.setWidthPercentage(93F);
table.setHorizontalAlignment(Element.ALIGN_LEFT);
table.setSpacingAfter(11F);
PdfPCell cell = buildCell_1("专家登录:");
cell.setRowspan(3);
table.addCell(cell);
cell = buildCell_2("证件号:");
table.addCell(cell);
cell = buildCell_3(" "+map.get("cert"));
cell.setColspan(3);
table.addCell(cell);
cell = buildCell_2("登录密码: ");
table.addCell(cell);
cell = buildCell_3(" "+map.get("passWd"));
cell.setColspan(3);
table.addCell(cell);
cell = buildCell_2("账号有效期: ");
table.addCell(cell);
cell = buildCell_3(" "+map.get("startDt"));
table.addCell(cell);
cell = buildCell_2("至");
table.addCell(cell);
cell = buildCell_3(" "+map.get("endDt"));
table.addCell(cell);
cell = buildCell_2("联系方式:");
table.addCell(cell);
cell = buildCell_3(" "+map.get("relation"));
cell.setColspan(4);
table.addCell(cell);
cell = buildCell_2("评审说明:");
table.addCell(cell);
cell = buildCell_3(" "+map.get("review"));
cell.setColspan(4);
table.addCell(cell);
return table;
}
private PdfPCell buildCell_1(String str){
Font f = createFont(9.5F, Font.NORMAL, BaseColor.BLACK);
Phrase p = new Phrase();
p.setFont(f);
p.add(str);
PdfPCell cell = new PdfPCell(p);
cell.setVerticalAlignment(Element.ALIGN_TOP);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
return cell;
}
private PdfPCell buildCell_2(String str){
Font f = createFont(9.5F, Font.NORMAL, BaseColor.BLACK);
Phrase p = new Phrase();
p.setFont(f);
p.add(str);
PdfPCell cell = new PdfPCell(p);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
return cell;
}
private PdfPCell buildCell_3(String str){
Font f = createFont(9.5F, Font.NORMAL, BaseColor.BLACK);
Phrase p = new Phrase();
p.setFont(f);
p.add(str);
PdfPCell cell = new PdfPCell(p);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
return cell;
}
private Paragraph createParaWithFirstIndent(String str){
Font f = createFont(9.8F, Font.NORMAL, BaseColor.BLACK);
Paragraph p = new Paragraph();
p.setAlignment(Element.ALIGN_LEFT);
p.setFont(f);
p.setFirstLineIndent(22F);
p.setLeading(15F);
p.add(str);
return p;
}
private Paragraph createParaWithoutFirstIndent(String str){
Font f = createFont(9.8F, Font.NORMAL, BaseColor.BLACK);
Paragraph p = new Paragraph();
p.setAlignment(Element.ALIGN_LEFT);
p.setFont(f);
p.setLeading(15F);
p.add(str);
return p;
}
private Paragraph createParaRight(String str){
Font f = createFont(9.5F, Font.NORMAL, BaseColor.BLACK);
Paragraph p = new Paragraph();
p.setAlignment(Element.ALIGN_RIGHT);
p.setIndentationRight(20F);
p.setFont(f);
p.setLeading(15F);
p.add(str);
return p;
}
}