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

Java iText操作PDF文档

2011-11-11 13:16 369 查看
iLife's 博客http://blog.csdn.net/fei1502816





1.Action

//在线打印PDF
String path = servlet.getServletContext().getRealPath("");	//得到项目根目录
CreatePdf checkPdf = new CreatePdf();
String filepath = checkPdf.printImportAndPtExpert(path,"expertBase",importList,putongtList);
request.setAttribute("filepath", path+File.separator+"community"+File.separator+"pdfile"+File.separator+filepath);
return mapping.findForward("downLoad");


2.公用类CreatPDF

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.Watermark;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;

public class CopyOfCreatePdf extends PdfPageEventHelper {

/**
* 打印专家评审基地(重点基地和普通基地)
*
* @param path
*            获得项目根目录 String path =
*            servlet.getServletContext().getRealPath("");
* @param filename
*            文件名
* @param importList
*            重点基地集合
* @param putongList
*            普通基地集合
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public String printImportAndPtExpert(String path, String filename,
List importList, List putongList) throws Exception {
// 创建报表大小,不能够指定页边距。
// Document document = new Document(PageSize.A4, 85, 71, 72, 72);
Document document = new Document(PageSize.A4, 30, 30, 72, 72);
try {
BaseFont bfFS = BaseFont.createFont(path + File.separator
+ "WEB-INF" + File.separator + "classes" + File.separator
+ "fonts" + File.separator + "SIMFANG.TTF",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 华文细黑
BaseFont bfHWXH = BaseFont.createFont(path + File.separator
+ "WEB-INF" + File.separator + "classes" + File.separator
+ "fonts" + File.separator + "STXIHEI.TTF",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 黑体
BaseFont bfHT = BaseFont.createFont(path + File.separator
+ "WEB-INF" + File.separator + "classes" + File.separator
+ "fonts" + File.separator + "SIMHEI.TTF",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

Font htFontB = new Font(bfHT, 14, Font.BOLD);

PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(path + File.separator + "community"
+ File.separator + "pdfile" + File.separator
+ filename + ".pdf"));

// 插入水印
if (new File(path + File.separator + "image006.gif") != null) {
Watermark watermark = new Watermark(Image.getInstance(path
+ File.separator + "image006.gif"), 0f, 0f);
document.add(watermark);
} else {
System.out.println("添加水印失败");
}
com.lowagie.text.Font ST3 = FontFactory.getFont("STSong-Light",
"UniGB-UCS2-H");
ST3.setSize(10f);
HeaderFooter footer = new HeaderFooter(new Phrase("第", ST3),
new Phrase("页", ST3));
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_CENTER);
document.setFooter(footer);
// 加密
writer.setEncryption(PdfWriter.STRENGTH128BITS, null,
"hujichen0928", PdfWriter.AllowPrinting
| PdfWriter.AllowCopy);
// 添加元信息

document.addAuthor("北京科学技术委员会");
document.addSubject("评审基地项目列表");
document.open();

com.lowagie.text.Font ST = FontFactory.getFont("STSong-Light",
"UniGB-UCS2-H");
com.lowagie.text.Font ST22 = FontFactory.getFont("STSong-Light",
"UniGB-UCS2-H");

BaseFont baseFont2 = ST22.getBaseFont();
Font ST2 = new Font(baseFont2, 14, Font.BOLD);
com.lowagie.text.Font cnFont = new Font(bfHWXH);
ST.setSize(10);
ST2.setSize(12);

Table proinfoTab = new Table(8);
proinfoTab.setWidth(100.0f);
float[] twidth = { 6f, 8f, 14f, 14f, 14f, 6f, 6f, 28f };
proinfoTab.setWidths(twidth);
proinfoTab.setCellspacing(4);
// 设置表框属性
Cell proinfoCell = new Cell(new Paragraph("2011年北京市第五批基地申报专家评审表",
ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setColspan(8);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("重点评审项目", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoCell.setColspan(8);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("序号", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("区县", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("基地名称", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("单位名称", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("基地类别", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("分值", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("等级", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

proinfoCell = new Cell(new Paragraph("专家评语", ST2));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

if (importList.size() > 0 && importList != null) {
for (int i = 0; i < importList.size(); i++) {

BBasePoint bbp = (BBasePoint) importList.get(i);
BBaseDocument doc = bbp.getBBaseDocument();

// 序号
proinfoCell = new Cell(new Paragraph(String.valueOf(i + 1),
ST));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 区县
if (doc.getDocCorpSection() == null) {
proinfoCell = new Cell(new Paragraph("无", ST));
} else {
proinfoCell = new Cell(new Paragraph(doc
.getDocCorpSection(), ST));
}
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 基地名称
if (doc.getBaseName() == null) {
proinfoCell = new Cell(new Paragraph("无", ST));
} else {
proinfoCell = new Cell(new Paragraph(doc.getBaseName(),
ST));
}
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 单位名称
if (doc.getDocCorpName() == null) {
proinfoCell = new Cell(new Paragraph("无", ST));
} else {
proinfoCell = new Cell(new Paragraph(doc
.getDocCorpName(), ST));
}
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 基地类型
if (doc.getDocCorpKind().equals("0")) {
proinfoCell = new Cell(new Paragraph("科普教育基地", ST));
} else if (doc.getDocCorpKind().equals("1")) {
proinfoCell = new Cell(new Paragraph("科普培训基地", ST));
} else if (doc.getDocCorpKind().equals("2")) {
proinfoCell = new Cell(new Paragraph("科普传媒基地", ST));
} else if (doc.getDocCorpKind().equals("3")) {
proinfoCell = new Cell(new Paragraph("科普研发基地", ST));
} else {
proinfoCell = new Cell(new Paragraph("无基地类型", ST));
}
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 基地评分
if (bbp.getZongpoint() == null) {
proinfoCell = new Cell(new Paragraph("0", ST));
} else {
proinfoCell = new Cell(new Paragraph(String
.valueOf(Math.round(bbp.getZongpoint())), ST)); // 基地分数
}
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 分数等级
if (bbp.getGrade() == null) {
proinfoCell = new Cell(new Paragraph("无", ST));
} else {
proinfoCell = new Cell(
new Paragraph(bbp.getGrade(), ST));
}
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
proinfoTab.addCell(proinfoCell);

// 专家评语
String opinion = bbp.getOpinion();
if (opinion != null) {
opinion = opinion.replaceAll("<p>", "\r\n");
opinion = opinion.replaceAll("</p>", "\r\n");
opinion = opinion.replaceAll(" ", " ");
} else {
opinion = "无";
}
proinfoCell = new Cell(new Paragraph(opinion, ST));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.LEFT);
proinfoCell.setHorizontalAlignment(Cell.LEFT);
proinfoTab.addCell(proinfoCell);
}
}

proinfoCell = new Cell(
new Paragraph(
"专 家 签 字:\n\n"
+ "                                                                                                                                           年      月     日\n",
ST));
proinfoCell.setUseAscender(true);
proinfoCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
proinfoCell.setHorizontalAlignment(Cell.ALIGN_LEFT);
proinfoCell.setColspan(8);
proinfoTab.addCell(proinfoCell);

document.add(proinfoTab);
} catch (DocumentException de) {
System.err.println(de.getMessage());
de.printStackTrace();
}
document.close();
return filename + ".pdf";
}
}


3.downLoad.jsp

<%@ page contentType="text/html;charset=UTF-8" import="com.jspsmart.upload.*" %>
<%
Object obj = request.getAttribute("filepath");
String filepath = "";
if(obj != null){
filepath = (String)obj;
}else{
filepath = request.getParameter("filepath");
}
System.out.println("**********"+filepath);
//filepath = filepath.replaceAll("/","\\");
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 初始化
su.initialize(pageContext);
su.setContentDisposition(null);
// 下载文件
su.downloadFile(filepath);
out.clear();
%>


下面的是在网上看到的一个例子,与大家分享

package com.thuram.test;

import java.awt.Color;
import java.io.FileOutputStream;

import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;

public class ITextTest ...{
public static void main(String[] args) ...{
try ...{
/** *//**
* 首先,创建一个document。
* document是PDF文档中所有元素的容器。
* 第一个参数表示页的大小,其后的参数分别表示左、右、上、下的边距。
*/
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

/** *//**
* 此处创建的write定义了上面创建的document的类型。
* 除了PdfWriter以为,还有HtmlWriter, RtfWriter, XmlWriter和一些别的类型。
* 第一个参数引用document对象,第二个参数指定了输出文件的绝对路径。
* 接着,我们open这个document往里边写入数据。
*/
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("c:/ITextTest.pdf"));
writer.setViewerPreferences(PdfWriter.HideMenubar
| PdfWriter.HideToolbar); // 隐藏菜单栏和工具栏
document.open();

/** *//**
* 现在,我们往document的第一页中加入一些文本内容。
* 所有的文本都要使用com.lowagie.text.Paragraph才能添加。
* 可以创建一个默认的paragraph,使用默认的字体,颜色,尺寸等属性,也可使使用自己定义的字体。
* 下面分别进行了这两种操作。
*/
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph(
"Some more text on the first page with different color and font type.",
FontFactory.getFont(FontFactory.COURIER, 14,
Font.BOLD, new Color(255, 150, 200))));

/** *//**
* 接下来,我们往document中添加一些复杂的元素。
* 让我们从创建一个新的chapter开始。
* chapter是一个特殊的部分,它将从新的一页开始,默认显示数字序号。
*/
Paragraph title1 = new Paragraph("Chapter 1", FontFactory.getFont(
FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0,
255)));
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);

/** *//**
* Section是chapter的一个子元素。
* 在下面的代码中我们创建了一个题为"This is Section 1 in Chapter 1" 的Section。
* 为了在Section下添加文本,我们再创建一个Paragraph对象,将其增加到Section对象中。
*/
Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD,
new Color(255, 0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph(
"This text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);

/** *//**
* 接着,再创建一个表格(table)对象。
* 表格中含有一个行和列的矩阵。
* 一行中的单元格(cell)可以延伸到多列。
* 同样的,一列中的单元格可以延伸到多行。
* 因此,一个3x2的表格不需要6个单元格。
*/
Table t = new Table(3, 2);
//设置边框颜色。如果颜色和背景色一样,则边框不会显示出来
t.setBorderColor(Color.white);
//设置单元格内文本的间距
t.setPadding(5);
//设置相邻单元格的间距
t.setSpacing(5);
t.setBorderWidth(1);

/** *//**
* 然后,创建3个单元格对象,包含不同的内容。
* 依次将其放入表格中。
* 先放在第一行第一列,再放在同一行的下一列中,……
* 当一行填满之后,下一个单元格将放在下一行的第一列中。
* 只给定单元格的内容(不新建单元格)也可以新增一个单元格,比如t.addCell("1.1");。
* 最后,将表格添加到Section对象中。
*/
Cell c1 = new Cell("Header1");
//设置单元格边框颜色,设置方法和表格边框一样
c1.setBorderColor(Color.WHITE);
t.addCell(c1);
c1 = new Cell("Header2");
t.addCell(c1);
c1 = new Cell("Header3");
t.addCell(c1);
t.addCell("1.1");
t.addCell("1.2");
t.addCell("1.3");
section1.add(t);

/** *//**
* 接下来,往PDF文档中添加一个列表(List)。
* 一个列表包含许多列表项(ListItem)。
* 列表可以编号也可以不编号。
* 将List的第一个参数置true表示创建的是一个编号的列表;
* 第二个参数表示是否使用字母编号,true为使用字母,false为使用数字
* 第三个参数为缩进值。
*/
List l = new List(true, false, 10);
l.add(new ListItem("First item of list"));
l.add(new ListItem("Second item of list"));
section1.add(l);

/** *//**
* 将chapter放入document中。
* 关闭document。
*/
document.add(chapter1);
document.close();
} catch (Exception e) ...{
System.out.println(e.getMessage());
}
}
}


iLife's 博客http://blog.csdn.net/fei1502816
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: