要使用itext创建pdf首先要去下载到相关支持的jar包,本文使用的itext5.5的版本。
1.产生一个简单的简单的pdf文件
package org.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class SimpleDemo {
public static void createPdf(){
try {
//创建document 对象
Document document = new Document();
FileOutputStream outst = new FileOutputStream("D:\\123.pdf");
PdfWriter pdfwriter = PdfWriter.getInstance(document, outst);
//打开文档
document.open();
//向文档添加内容
document.add(new Paragraph("Hi!this is my first page"));
//关闭文档
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
createPdf();
}
}
2.产生一个复杂一点的PDF文档,并提供下载
jsp页面
<script type="text/javascript">
function upload_pdf(){
location.href="/itextPdf/servlet/UploadPdfServlet?method=upload";
}
</script>
</head>
<body>
<div style="margin: 30px;">
<input type="button" value="导出PDF" onclick="upload_pdf();" id="upload_pdf">
</div>
</body>
servlet控制类
package org.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UploadPdfServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("method");
if(method.equals("upload")){
doUpload( request, response);
}
}
public void doUpload(HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
String filename = "导出2015.pdf";
try {
//解决文件名乱码问题
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {//IE浏览器
filename = URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}
response.setHeader("Content-Disposition", "attachment;fileName="
+ filename);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//产生PDF
CreatePdfTools pdftool = new CreatePdfTools();
pdftool.CreatePdf(request, filename);
try {
String path = request.getSession().getServletContext().getRealPath("/upload/"+filename);
File file = new File(path);
FileInputStream fileIput = new FileInputStream(file);
OutputStream output = response.getOutputStream();
byte[] buf = new byte[1024];
int r = 0;
while((r=fileIput.read(buf,0,buf.length))!=-1){
output.write(buf, 0, r);
}
output.flush();
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
pdf工具类
package org.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
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.PdfWriter;
public class CreatePdfTools{
private final int CELLHIGHT = 30;
public void CreatePdf(HttpServletRequest request,String FileName) {
String Filepath = request.getSession().getServletContext().getRealPath("/upload/"+FileName);
File file = new File(Filepath);
FileOutputStream out = null;
try {
Document document = new Document(PageSize.A4,50,50,50,50);
out = new FileOutputStream(file);
PdfWriter write = PdfWriter.getInstance(document, out);
document.open();
BaseColor color = new BaseColor(0, 0, 0);
Font font = FontFactory.getFont(FontFactory.HELVETICA, 18);
BaseFont bfChinese;
//注意这里需要指定字体文件
String fontPath = request.getSession().getServletContext().getRealPath("/resource/fzt.ttf");
bfChinese = BaseFont.createFont(fontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);//设置中文字体
//中文大小为20,加粗
font = new Font(bfChinese, 20, Font.BOLD);
Font font1 = new Font(bfChinese,15,Font.NORMAL);
//设置标题
Paragraph title = new Paragraph("xx公司业务审批表",font);
title.setAlignment(Element.ALIGN_CENTER);
title.setSpacingAfter(30f);
document.add(title);
//业务类型
Paragraph businessType = new Paragraph();
// 定义选中时的复选框按钮的路径
String checkboxChecked_path = request.getSession().getServletContext().getRealPath("\\images\\checkedBox.png");
Image checkboxChecked_image = Image.getInstance(checkboxChecked_path);
checkboxChecked_image.scaleAbsolute(13, 13);
//插入图片,设置图片的位置
Chunk checkboxChecked = new Chunk(checkboxChecked_image,0,-2);
businessType.add(checkboxChecked);
businessType.add(new Chunk(" 审批业务1",font1));
// 定义没选中时的复选框按钮的路径
String checkboxNotChecked_path = request.getSession().getServletContext().getRealPath("\\images\\notCheckBox.png");
Image checkboxNotChecked_image = Image.getInstance(checkboxNotChecked_path);
checkboxNotChecked_image.scaleAbsolute(13, 13);
//插入图片,设置图片的位置
Chunk checkboxNotChecked = new Chunk(checkboxNotChecked_image,0,-2);
businessType.add(" ");
businessType.add(checkboxNotChecked);
businessType.add(new Chunk(" 审批业务2",font1));
//设置与下一个元素的间距
businessType.setSpacingAfter(10f);
document.add(businessType);
//创建一个六列的表格
PdfPTable table = new PdfPTable(4);
//设置表格每列的宽度的百分比
int[] cellWidth = {25,25,25,25};
table.setWidths(cellWidth);
//表格宽度
table.setTotalWidth(500);
//锁定宽度
table.setLockedWidth(true);
//设置表格水平居中
table.setHorizontalAlignment(Element.ALIGN_CENTER);
//水平居中
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
//设置固表格定高度
table.getDefaultCell().setFixedHeight(CELLHIGHT);
//设置表格边框颜色
table.getDefaultCell().setBackgroundColor(color);
//设置单元格的边距间隔
table.getDefaultCell().setPadding(0);
table.getDefaultCell().setBorderWidth(0);
//单元格对象
PdfPCell cell = new PdfPCell();
Paragraph para = new Paragraph("作品名称:",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
//设置cell高度
cell.setMinimumHeight(30f);
//设置内容水平居中
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
//设置内容垂直居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("PDF Hello World",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("作品类别:",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("类别1",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("作者:",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setMinimumHeight(30f);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("张三",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("著作权人:",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
para = new Paragraph("张三",font1);
para.setAlignment(Element.ALIGN_CENTER);
cell = new PdfPCell(para);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setBorder(1);
table.addCell(cell);
Paragraph para2 = new Paragraph("受理意见",font1);
//设置字体居中
PdfPCell cell2 = new PdfPCell(para2);
//设置cell的高度
cell2.setMinimumHeight(100);
//水平居中
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell2);
Paragraph para3 = new Paragraph("同意受理,请上级领导审批。",font1);
SimpleDateFormat format = new SimpleDateFormat("yyyy 年 MM 月 dd 日");
String date = format.format(new Date());
Paragraph para4 = new Paragraph("受理人: "+date,font1);
//设置与上一个元素的间距
para4.setSpacingBefore(30f);
//设置首行缩进
para4.setFirstLineIndent(50f);
PdfPCell cell3 = new PdfPCell();
cell3.addElement(para3);
cell3.addElement(para4);
cell3.setColspan(3);
table.addCell(cell3);
//审批
Paragraph sp_para1 = new Paragraph("审批意见",font1);
//设置字体居中
PdfPCell sp_cell1 = new PdfPCell(sp_para1);
//设置cell的高度
sp_cell1.setMinimumHeight(100);
//水平居中
sp_cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
sp_cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(sp_cell1);
Paragraph sp_para2 = new Paragraph("审批通过。",font1);
Paragraph sp_para3 = new Paragraph("受理人: "+date,font1);
//设置与上一个元素的间距
sp_para3.setSpacingBefore(30f);
//设置首行缩进
sp_para3.setFirstLineIndent(50f);
PdfPCell sp_cell2 = new PdfPCell();
sp_cell2.addElement(sp_para2);
sp_cell2.addElement(sp_para3);
sp_cell2.setColspan(3);
table.addCell(sp_cell2);
//文档左右文字(上)
PdfContentByte canvas = write.getDirectContent();
Phrase phrase1 = new Phrase("装|",font1);
Phrase phrase2 = new Phrase("订|",font1);
Phrase phrase3 = new Phrase("处|",font1);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 10, 680, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase2, 10, 665, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase3, 10, 650, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase1, 10, 480, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase2, 10, 465, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase3, 10, 450, 0);
//页脚信息
Phrase phrase4 = new Phrase("xxx信息有限公司(印)",font1);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase4, document.right(), document.bottom() - 20, 0);
document.add(table);
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out !=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
CreatePdfTools pdftool = new CreatePdfTools();
// pdftool.CreatePdf();
}
}
这里是项目下载地址http://pan.baidu.com/s/1hqCfxQW