81,091
社区成员
发帖
与我相关
我的任务
分享
import java.awt.Color;
import java.io.FileOutputStream;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
/**
* iText5的入门学习文档,这个demo已经提供了自己想要的最为常见的实现
*
* 这个文档主要学习利用itext实现创建PDF文档
* 我需要学习利用itext实现读取PDF文档的内容
* @author http://www.coderanch.com/how-to/java/ItextExample
*
*/
public class Demo {
public static void main (String[] args) {
// creation of the document with a certain size and certain margins
// may want to use PageSize.LETTER instead
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("etc/demo.pdf"));
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
HeaderFooter event = new HeaderFooter();
writer.setPageEvent(event);
// various fonts
BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);
int y_line1 = 650;
int y_line2 = y_line1 - 50;
int y_line3 = y_line2 - 50;
document.open();
PdfContentByte cb = writer.getDirectContent();
cb.setLineWidth(0f);
cb.moveTo(250, y_line3 - 100);
cb.lineTo(250, y_line1 + 100);
cb.moveTo(50, y_line1);
cb.lineTo(400, y_line1);
cb.moveTo(50, y_line2);
cb.lineTo(400, y_line2);
cb.moveTo(50, y_line3);
cb.lineTo(400, y_line3);
cb.stroke();
cb.beginText();
cb.setFontAndSize(bf_helv, 12);
String text = "Sample text for alignment";
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, y_line1, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, y_line2, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, y_line3, 0);
cb.endText();
document.newPage();
// add text in two paragraphs from top to bottom
Paragraph par = new Paragraph("bold paragraph");
par.getFont().setStyle(Font.BOLD);
document.add(par);
par = new Paragraph("italic paragraph");
par.getFont().setStyle(Font.ITALIC);
document.add(par);
par = new Paragraph("underlined and strike-through paragraph");
par.getFont().setStyle(Font.UNDERLINE | Font.STRIKETHRU);
document.add(par);
// demonstrate some table features
PdfPTable table = new PdfPTable(3);
table.setSpacingBefore(20);
table.getDefaultCell().setPadding(5);
PdfPCell cell = new PdfPCell(new Phrase("header"));
cell.setPadding(5);
cell.setColspan(3);
table.addCell(cell);
table.setHeaderRows(1);
cell = new PdfPCell(new Phrase("example cell with rowspan 2 and red border"));
cell.setPadding(5);
cell.setRowspan(2);
cell.setBorderColor(new BaseColor(new Color(255, 0, 0)));
table.addCell(cell);
table.addCell("中文");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
cell = new PdfPCell(new Phrase("align center"));
cell.setPadding(5);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("rotated cell"));
cell.setPadding(5);
cell.setRowspan(2);
cell.setColspan(2);
// PdfPCell content can be rotated
cell.setRotation(90);
table.addCell(cell);
cell = new PdfPCell(new Phrase("align right"));
cell.setPadding(5);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(cell);
document.add(table);
// add text at an absolute position
cb.beginText();
cb.setFontAndSize(bf_times, 14);
cb.setTextMatrix(100, 300);
cb.showText("Text at position 100, 300.");
cb.endText();
// rotated text at an absolute position
PdfTemplate template = cb.createTemplate(300, 300);
template.beginText();
template.setFontAndSize(bf_times, 14);
template.showText("Rotated text at position 400, 200.");
template.endText();
float rotate = 90;
float x = 400;
float y = 200;
float angle = (float) (-rotate * (Math.PI / 180));
float xScale = (float) Math.cos(angle);
float yScale = (float) Math.cos(angle);
float xRot = (float) -Math.sin(angle);
float yRot = (float) Math.sin(angle);
cb.addTemplate(template, xScale, xRot, yRot, yScale, x, y);
document.close();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
/** Inner class to add a header and a footer. */
static class HeaderFooter extends PdfPageEventHelper {
public void onEndPage (PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("art");
switch(writer.getPageNumber() % 2) {
case 0:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, new Phrase("even header"),
rect.getRight(), rect.getTop(), 0);
break;
case 1:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase("odd header"),
rect.getLeft(), rect.getTop(), 0);
break;
}
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(String.format("page %d", writer.getPageNumber())),
(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
}
}
}
Workbook book = null;
try {
book = new HSSFWorkbook(in);
}
catch(OutOfMemoryError e) {
String msg = "The file " + excel.getName()
+ " data is error, please delete invalid data!";
if(log.isDebugEnabled()) {
log.debug(msg);
}
throw new Exception(msg);
}
catch(OfficeXmlFileException e) {
in = new FileInputStream(excel);
book = new XSSFWorkbook(in);
//throw new Exception(e.getMessage());
}
if(book == null || book.getNumberOfSheets() == 0) {
return null;
}
<%@ page language="java" contentType="text/html;charset=UTF-8" import="java.util.*,java.io.*,java.sql.*,org.apache.poi.hssf.usermodel.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>数据库导出成Excel文件测试</title>
</head>
<body>
<br><br><br><br>
<center>
<%
String driverName = "com.mysql.jdbc.Driver"; // 驱动名称
String userName = "root"; // 用户名
String password = "318404"; // 密码
String dbName = "test"; // 数据库名字
String tableName = "userinfo"; // 表名
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+password;
Class.forName(driverName).newInstance();
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT userName,passWord,age,email,address FROM userinfo ");
%>
<%
HSSFWorkbook workbook = new HSSFWorkbook(); //创建新的Excel工作薄
HSSFSheet sheet = workbook.createSheet("userInfo"); //在Excel工作薄中建工作表,名为缺省
HSSFRow row = sheet.createRow((short)0); //在索引0的位置建行(最顶端的行)
//
HSSFCell cell = row.createCell((short)0); //在索引0的位置建单元格
// cell.setEncoding(HSSFCell.ENCODING_UTF_16); //定义单元格为字符串类型
cell.setCellValue("编号"); //在单元格输入一些内容
cell = row.createCell((short)1);
cell.setCellValue("姓名"); //在单元格输入一些内容
cell = row.createCell((short)2);
cell.setCellValue("密码");
cell = row.createCell((short)3);
cell.setCellValue("年龄");
cell = row.createCell((short)4);
cell.setCellValue("邮箱");
cell = row.createCell((short)5);
cell.setCellValue("地址");
int i = 1;
while(rs.next()){
row = sheet.createRow((short)i); //在索引1的位置创建行(最顶端的行)
cell = row.createCell((short)0); //在索引0的位置创建单元格(左上端)
cell.setCellValue(i); //在单元格输入一些内容
cell = row.createCell((short)1);
cell.setCellValue(rs.getString(1)); //在单元格输入一些内容
cell = row.createCell((short)2);
cell.setCellValue(rs.getString(2));
cell = row.createCell((short)3);
cell.setCellValue(rs.getString(3));
cell = row.createCell((short)4);
cell.setCellValue(rs.getString(4));
cell = row.createCell((short)5);
cell.setCellValue(rs.getString(5));
i++;
}
String filename = application.getRealPath("/") + "test.xls"; //filename是工作薄的存放位置,存放在当前应用程序的根目录下
FileOutputStream fOut = new FileOutputStream(filename); //新建输出文件流
workbook.write(fOut); //把相应的Excel工作薄存盘
fOut.flush();
fOut.close(); //操作结束,关闭文件
out.println("excel文件已经生成,存放在 <font color=red>" + filename + "</font>");
%>
<fieldset style="height:auto;width: 80%;">
<legend>数据库导出成Excel文件测试</legend>
<table align="center" border="1" width="80%">
<tr align="center">
<td colspan="6">纯JSP页面的分页测试数据</td>
</tr>
<tr align="center">
<td>编号</td>
<td>姓名</td>
<td>密码</td>
<td>年龄</td>
<td>邮箱</td>
<td>地址</td>
</tr>
<%
ResultSet result = statement.executeQuery("SELECT userName,passWord,age,email,address FROM userinfo ORDER BY id DESC");
int j = 1;
while (result.next()) {
// int bil = j + (PageNo-1)*PageSize;
%>
<tr align="center">
<td><%=j %></td>
<td><%=result.getString(1)%></td>
<td><%=result.getString(2) %></td>
<td><%=result.getString(3) %></td>
<td><%=result.getString(4) %></td>
<td><%=result.getString(5) %></td>
</tr>
<%
j++;
}
rs.close();
result.close();
statement.close();
connection.close();
%>
</fieldset>
</center>
</body>
</html>