java 导出pdf

package hb.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fr.third.com.lowagie.text.Chunk;
import com.fr.third.com.lowagie.text.Document;
import com.fr.third.com.lowagie.text.DocumentException;
import com.fr.third.com.lowagie.text.Element;
import com.fr.third.com.lowagie.text.Font;
import com.fr.third.com.lowagie.text.Image;
import com.fr.third.com.lowagie.text.PageSize;
import com.fr.third.com.lowagie.text.Paragraph;
import com.fr.third.com.lowagie.text.Phrase;
import com.fr.third.com.lowagie.text.Rectangle;
import com.fr.third.com.lowagie.text.pdf.BaseFont;
import com.fr.third.com.lowagie.text.pdf.ColumnText;
import com.fr.third.com.lowagie.text.pdf.PdfContentByte;
import com.fr.third.com.lowagie.text.pdf.PdfPCell;
import com.fr.third.com.lowagie.text.pdf.PdfPRow;
import com.fr.third.com.lowagie.text.pdf.PdfPTable;
import com.fr.third.com.lowagie.text.pdf.PdfWriter;
import com.fr.third.com.lowagie.text.pdf.draw.LineSeparator;
import hb.entity.OrganizeInformationModel;
import hb.service.ComponentPictureLedgerService;

/**
* 组件图片台账
*
* @author jf
*
*/
@Controller
@RequestMapping("/cplController")
public class ComponentPictureLedgerController {

@Autowired
private ComponentPictureLedgerService pictureLedgerService;

/**
* @author jf
* @param 根据条件查询基础图片台账信息
*/
@RequestMapping(params = "queryComponentPictureLedger")
@ResponseBody
public List<Map<String, Object>> queryComponentPictureLedger(HttpServletRequest request,
HttpServletResponse response) {
try {
String LOCATIONA_CODE = new String(request.getParameter("LOCATIONA_CODE").getBytes("ISO8859-1"), "UTF-8");
String LOCATIONB_CODE = new String(request.getParameter("LOCATIONB_CODE").getBytes("ISO8859-1"), "UTF-8");
String LOCATIONC_CODE = new String(request.getParameter("LOCATIONC_CODE").getBytes("ISO8859-1"), "UTF-8");
String TAG = new String(request.getParameter("TAG").getBytes("ISO8859-1"), "UTF-8");
String DTM = request.getParameter("DTM");
String device_type = new String(request.getParameter("device_type").getBytes("ISO8859-1"), "UTF-8");
String device_type_childer = new String(request.getParameter("device_type_childer").getBytes("ISO8859-1"),
"UTF-8");
String device_medium_state = new String(request.getParameter("device_medium_state").getBytes("ISO8859-1"),
"UTF-8");
String UTM = request.getParameter("UTM");
String poos = request.getParameter("poos");
String ON_REMOVAL_BOX = request.getParameter("ON_REMOVAL_BOX");
String INSPECTION_FREQUENCY_CODE = new String(
request.getParameter("INSPECTION_FREQUENCY_CODE").getBytes("ISO8859-1"), "UTF-8");
OrganizeInformationModel org = new OrganizeInformationModel();
org.setComponentTypeCode(device_type);
org.setSubTypeCode(device_type_childer);
org.setManufacturersCode(device_medium_state);
org.setUtm(UTM);
org.setTag(TAG);
org.setDtm(DTM);
org.setPoos(poos);
org.setLocationaCode(LOCATIONA_CODE);
org.setLocationbCode(LOCATIONB_CODE);
org.setLocationcCode(LOCATIONC_CODE);
org.setOnRemovalBox(ON_REMOVAL_BOX);
org.setInspectionFrequencyCode(INSPECTION_FREQUENCY_CODE);
List<Map<String, Object>> componentFoundationLedgers = pictureLedgerService.findComponentPictureInfo(org);
return componentFoundationLedgers;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 导出excel
*
* @param request
* @param response
*/
@ResponseBody
@RequestMapping(params = "exportExcel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
FileOutputStream fileOut = null;
String strAppRootPath = request.getServletContext().getRealPath("/");

// 基础台账信息list
List<Map<String, Object>> list = this.queryComponentPictureLedger(request, response);
String name = "LDAR组件图片台账";

// 导出文件名
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = formatter.format(System.currentTimeMillis()) + ".xls";

// 创建Excel工作簿对象
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建Excel工作表对象
XSSFSheet sheet = workbook.createSheet(name);

// 无网格线
sheet.setDisplayGridlines(false);

// 表格标题样式
int f = 27;
XSSFCellStyle style1 = this.setTitleStyle(f, workbook);

// 导出人样式
int f1 = 17;
XSSFCellStyle style2 = this.setTitleStyle(f1, workbook);

// 内容样式
int f3 = 11;
XSSFCellStyle style3 = this.setContentStyle(f3, workbook);

// 产生表格标题行
XSSFRow title = sheet.createRow(0);
title.setHeightInPoints(50);
XSSFCell cellTitle = title.createCell(0);
cellTitle.setCellValue(name);
cellTitle.setCellStyle(style1);

XSSFRow interval = sheet.createRow(1);
interval.setHeightInPoints(22);

// 产生导出人行
XSSFRow second = sheet.createRow(2);
second.setHeightInPoints(30);
XSSFCell secondCell = second.createCell(0);
secondCell.setCellValue("导出人:" + ResourceUtil.getSessionUser().getRealName());
secondCell.setCellStyle(style2);

// 标题行,导出人行 合并 参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列
CellRangeAddress rangeAddresst = new CellRangeAddress(0, 0, 0, 11);
sheet.addMergedRegion(rangeAddresst);
CellRangeAddress rangeAddressp = new CellRangeAddress(2, 2, 0, 11);
sheet.addMergedRegion(rangeAddressp);

int index = 3;
String content = null;

for (Map<String, Object> eachVal : list) {

// // 合并
// int firstRow = index / 3 * 6;
// int lastRow = index / 3 * 6;
// int firstCol = index % 3 * 4;
// int lastCol = index % 3 * 4 + 2;
// CellRangeAddress rangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
// sheet.addMergedRegion(rangeAddress);
//
// int firstRow2 = index / 3 * 6 + 1;
// int lastRow2 = index / 3 * 6 + 1;
// int firstCol2 = index % 3 * 4;
// int lastCol2 = index % 3 * 4 + 2;
// CellRangeAddress rangeAddress2 = new CellRangeAddress(firstRow2, lastRow2, firstCol2, lastCol2);
// sheet.addMergedRegion(rangeAddress2);
//
// // 合并
// int firstRow3 = index / 3 * 6 + 2;
// int lastRow3 = index / 3 * 6 + 3;
// int firstCol3 = index % 3 * 4 + 2;
// int lastCol3 = index % 3 * 4 + 2;
// CellRangeAddress rangeAddress3 = new CellRangeAddress(firstRow3, lastRow3, firstCol3, lastCol3);
// sheet.addMergedRegion(rangeAddress3);
//
// // //合并
// // int firstRow4 = index / 3 * 6 + 4;
// // int lastRow4 = index / 3 * 6 + 4;
// // int firstCol4 = index % 3 * 4;
// // int lastCol4 = index % 3 * 4 + 2;
// // CellRangeAddress rangeAddress4 = new CellRangeAddress(firstRow4,
// // lastRow4, firstCol4, lastCol4);
// // sheet.addMergedRegion(rangeAddress4);

// 合并
int firstRow = index / 3 * 6;
int lastRow = index / 3 * 6;
int firstCol = index % 3 * 4;
int lastCol = index % 3 * 4 + 3;
CellRangeAddress rangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.addMergedRegion(rangeAddress);

int firstRow2 = index / 3 * 6 + 1;
int lastRow2 = index / 3 * 6 + 1;
int firstCol2 = index % 3 * 4;
int lastCol2 = index % 3 * 4 + 3;
CellRangeAddress rangeAddress2 = new CellRangeAddress(firstRow2, lastRow2, firstCol2, lastCol2);
sheet.addMergedRegion(rangeAddress2);

// 合并
int firstRow3 = index / 3 * 6 + 2;
int lastRow3 = index / 3 * 6 + 3;
int firstCol3 = index % 3 * 4 + 2;
int lastCol3 = index % 3 * 4 + 3;
CellRangeAddress rangeAddress3 = new CellRangeAddress(firstRow3, lastRow3, firstCol3, lastCol3);
sheet.addMergedRegion(rangeAddress3);

// //合并
// int firstRow4 = index / 3 * 6 + 4;
// int lastRow4 = index / 3 * 6 + 4;
// int firstCol4 = index % 3 * 4;
// int lastCol4 = index % 3 * 4 + 2;
// CellRangeAddress rangeAddress4 = new CellRangeAddress(firstRow4,
// lastRow4, firstCol4, lastCol4);
// sheet.addMergedRegion(rangeAddress4);

// 查询数据所需要的字段
Map<Integer, Map<Integer, String>> dicKey = new HashMap<>();
Map<Integer, String> dic = new HashMap<>();
dic.put(0, "LOCATIONA_CODE");
dic.put(2, "LOCATIONB_CODE");
dicKey.put(0, Collections.singletonMap(0, "TAG"));
dicKey.put(1, Collections.singletonMap(0, "LOCATION_DESCRIPTION"));
dicKey.put(2, dic);
dicKey.put(3, Collections.singletonMap(0, "LOCATIONC_CODE"));
dicKey.put(4, Collections.singletonMap(0, "MARK_PICTURES_ADDRESS"));

for (int eachRowIndex = 0; eachRowIndex < 6; eachRowIndex++) {

Row row = sheet.getRow(index / 3 * 6 + eachRowIndex);
if (null == row) {
row = sheet.createRow(index / 3 * 6 + eachRowIndex);
}
if (eachRowIndex == 4) {
row.setHeight((short) (25 * 160));
}
for (int j = 0; j < 4; j++) {
if (dicKey.containsKey(eachRowIndex) && dicKey.get(eachRowIndex).containsKey(j)) {
Cell cell = row.createCell(index % 3 * 4 + j );

if (eachRowIndex == 0) {
if (null == eachVal.get(dicKey.get(eachRowIndex).get(j))) {
continue;
}
if ("".equals(eachVal.get(dicKey.get(eachRowIndex).get(j)))) {
continue;
}
row.setHeightInPoints(30);
content = "标签号 :" + eachVal.get(dicKey.get(eachRowIndex).get(j)).toString();
cell.setCellValue(content);
cell.setCellStyle(style3);
} else if (eachRowIndex == 1) {
if (null == eachVal.get(dicKey.get(eachRowIndex).get(j))) {
continue;
}
if ("".equals(eachVal.get(dicKey.get(eachRowIndex).get(j)))) {
continue;
}
row.setHeightInPoints(30);
content = "位置描述 :" + eachVal.get(dicKey.get(eachRowIndex).get(j)).toString();
cell.setCellValue(content);
cell.setCellStyle(style3);
} else if (eachRowIndex == 2) {
if (null == eachVal.get(dicKey.get(eachRowIndex).get(j))) {
continue;
}
if ("".equals(eachVal.get(dicKey.get(eachRowIndex).get(j)))) {
continue;
}
if (j == 0) {
row.setHeightInPoints(30);
content = "装置 :" + eachVal.get(dicKey.get(eachRowIndex).get(j)).toString();
cell.setCellValue(content);
cell.setCellStyle(style3);
} else if (j == 2) {
content = "区域 :" + eachVal.get(dicKey.get(eachRowIndex).get(j)).toString();
cell.setCellValue(content);
cell.setCellStyle(style3);
int ro = index / 3 * 6 + eachRowIndex;
sheet.autoSizeColumn(1);
// sheet.setColumnWidth(m,
// content.getBytes().length*2*256);
}
} else if (eachRowIndex == 3) {
if (null == eachVal.get(dicKey.get(eachRowIndex).get(j))) {
continue;
}
if ("".equals(eachVal.get(dicKey.get(eachRowIndex).get(j)))) {
continue;
}
row.setHeightInPoints(30);
content = "设备 :" + eachVal.get(dicKey.get(eachRowIndex).get(j)).toString();
cell.setCellValue(content);
cell.setCellStyle(style3);
} else if (dicKey.get(eachRowIndex).get(j).equals("MARK_PICTURES_ADDRESS")) {
String picPath = eachVal.get(dicKey.get(eachRowIndex).get(j)).toString();
if (picPath == null || picPath.trim().equals("")) {
continue;
}
picPath = picPath.replace("/", File.separator).replace("\\", File.separator);
String type = picPath.substring(picPath.indexOf(".") + 1, picPath.length());
BufferedImage bufferImg = null;
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

try {
bufferImg = ImageIO.read(new File(strAppRootPath + picPath));
ImageIO.write(bufferImg, type, byteArrayOut);

XSSFDrawing patriarch = sheet.createDrawingPatriarch();
int a = index % 3 * 4;
int b = index % 3 * 4 + 2;
int c = index / 3 * 6 + 4;
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 400, 500, (short) (index % 3 * 4),
index / 3 * 6 + 4, (short) (index % 3 * 4 + 3), index / 3 * 6 + 4 + 1);
patriarch.createPicture(anchor,
workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG));
} catch (IOException e) {
e.printStackTrace();
}
continue;
}
}
}
}
index++;
}
try {
String type = "octet-stream";
this.setResponseHeader(response, fileName,type);
OutputStream os = response.getOutputStream();
workbook.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
// JOptionPane.showMessageDialog(null, "导出成功!");
}

/**
* 导出pdf
*
* @param request
* @param response
*/
@ResponseBody
@RequestMapping(params = "exportpdf")
public void exportpdf(HttpServletRequest request, HttpServletResponse response) {
// 基础台账信息list
List<Map<String, Object>> ledgers = this.queryComponentPictureLedger(request, response);
String strAppRootPath = request.getServletContext().getRealPath("/");

// 导出文件名
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = formatter.format(System.currentTimeMillis()) + ".pdf";
// 页面大小
Rectangle rect = new Rectangle(PageSize.B5.rotate());
// 实例化一个document对象
Document document = new Document(rect);
OutputStream out = null;
try {
String type = "pdf";
this.setResponseHeader(response, fileName ,type);
out = response.getOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, out);
// 打开生成的pdf文件
document.open();

// 设置字符
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
Font fontTitle = new Font(bfChinese, 22.0F, 0);
Font font2 = new Font(bfChinese, 14.0F, 0);
Font fontContent = new Font(bfChinese, 12.0F, 0);
Font s = new Font(bfChinese, 10.0F, 0);

//新页面
document.newPage();

//设置logo位置
String logoPath = "upload\\files\\20171012\\logo.png";
logoPath = strAppRootPath = logoPath;
logoPath = logoPath.replace("/", File.separator).replace("\\", File.separator);
Image image = Image.getInstance(logoPath);
// 设置图片位置的x轴和y周
image.setAbsolutePosition(450, 330);
float wid = image.getWidth();
float hei = image.getHeight();
// 设置图片的宽度和高度
image.scaleAbsolute(wid, hei);
document.add(image);

for (int i = 0; i < 9; i++) {
document.add(new Paragraph("\n"));
}

// 标题
String title = "LDAR组件图片台账";
Paragraph tit = new Paragraph(title, fontTitle);
// 设置对齐方式
tit.setAlignment(Element.ALIGN_CENTER);
// 设置行间距
tit.setLeading(1f);
document.add(tit);
document.add(new Paragraph("\n"));

// 导出人
String name = "导出人:" + ResourceUtil.getSessionUser().getRealName();
Paragraph export = new Paragraph(name, font2);
export.setAlignment(Element.ALIGN_CENTER);
tit.setLeading(1f);
document.add(export);
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));

// 查询数据所需要的字段
Map<Integer, String> dic = new HashMap<>();
dic.put(0, "TAG");
dic.put(1, "LOCATION_DESCRIPTION");
dic.put(2, "LOCATIONA_CODE");
dic.put(3, "LOCATIONB_CODE");
dic.put(4, "LOCATIONC_CODE");
dic.put(5, "MARK_PICTURES_ADDRESS");

String content1 = null;
String content2 = null;
String content3 = null;
float lineHeight2 = (float) 30.0;

document.newPage();
for (int i = 0; i < ledgers.size(); i++) {

// 创建table,注意这里的3指的是3列,下面通过table.addCell添加的时候必须添加整行内容的所有列
PdfPTable table = new PdfPTable(3);
// 设置表格宽度
table.setTotalWidth(99);
// 设置列宽
table.setWidths(new float[] { 33f, 33f, 33f });
// 宽度100%填充
table.setWidthPercentage(100.0F);
table.setHeaderRows(1);
table.getDefaultCell().setHorizontalAlignment(1);
table.setSpacingBefore(10f); // 前间距
table.setSpacingAfter(10f); // 后间距
List<PdfPRow> listRow = table.getRows();
for (int j = 0; j < dic.size(); j++) {
if (dic.get(j).equals("TAG")) {
if (null == ledgers.get(i).get(dic.get(j))) {
continue;
}
if ("".equals(ledgers.get(i).get(dic.get(j)))) {
continue;
}

content1 = "标签号:" + ledgers.get(i).get(dic.get(j)).toString();
// PdfPCell cells1[] = new PdfPCell[3];
// PdfPRow row1 = new PdfPRow(cells1);
// content = "标签号:" +
// ledgers.get(i).get(dic.get(j)).toString()+" 位置描述:
// LDAR组件图片台账 ";
// cells1[i] = new PdfPCell(new
// Paragraph(content,fontContent));
// cells1[i].setFixedHeight(lineHeight2);
// cells1[i].setNoWrap(false);
// cells1[i + 1] = new PdfPCell(new Paragraph());
// cells1[i + 2] = new PdfPCell(new Paragraph());
//
// listRow.add(row1);

} else if (dic.get(j).equals("LOCATION_DESCRIPTION")) {
if (null == ledgers.get(i).get(dic.get(j))) {
continue;
}
if ("".equals(ledgers.get(i).get(dic.get(j)))) {
continue;
}
content1 = content1 + "位置描述:" + ledgers.get(i).get(dic.get(j)).toString();
PdfPCell cells2[] = new PdfPCell[3];
PdfPRow row2 = new PdfPRow(cells2);
cells2[i] = new PdfPCell(new Paragraph(content1, fontContent));
cells2[i].setFixedHeight(lineHeight2);
cells2[i].setNoWrap(false);

cells2[i + 1] = new PdfPCell(new Paragraph());
cells2[i + 2] = new PdfPCell(new Paragraph());

listRow.add(row2);

} else if (dic.get(j).equals("LOCATIONA_CODE")) {
if (null == ledgers.get(i).get(dic.get(j))) {
continue;
}
if ("".equals(ledgers.get(i).get(dic.get(j)))) {
continue;
}
content2 = "装置:" + ledgers.get(i).get(dic.get(j)).toString();
// PdfPCell cells3[] = new PdfPCell[3];
// PdfPRow row3 = new PdfPRow(cells3);
// cells3[i] = new PdfPCell(new
// Paragraph(content,fontContent));
// cells3[i].setFixedHeight(lineHeight2);
//
// cells3[i + 1] = new PdfPCell(new Paragraph());
// cells3[i + 2] = new PdfPCell(new Paragraph());
//
// listRow.add(row3);
} else if (dic.get(j).equals("LOCATIONB_CODE")) {
if (null == ledgers.get(i).get(dic.get(j))) {
continue;
}
if ("".equals(ledgers.get(i).get(dic.get(j)))) {
continue;
}
content2 = content2 + " 区域:" + ledgers.get(i).get(dic.get(j)).toString();
// PdfPCell cells4[] = new PdfPCell[3];
// PdfPRow row4 = new PdfPRow(cells4);
// cells4[i] = new PdfPCell(new
// Paragraph(content2,fontContent));
// cells4[i].setFixedHeight(lineHeight2);
//
// cells4[i + 1] = new PdfPCell(new Paragraph());
// cells4[i + 2] = new PdfPCell(new Paragraph());
//
// listRow.add(row4);
} else if (dic.get(j).equals("LOCATIONC_CODE")) {
if (null == ledgers.get(i).get(dic.get(j))) {
continue;
}
if ("".equals(ledgers.get(i).get(dic.get(j)))) {
continue;
}
content2 = content2 + " 设备:" + ledgers.get(i).get(dic.get(j)).toString();
PdfPCell cells5[] = new PdfPCell[3];
PdfPRow row5 = new PdfPRow(cells5);
cells5[i] = new PdfPCell(new Paragraph(content2, fontContent));
cells5[i].setFixedHeight(lineHeight2);

cells5[i + 1] = new PdfPCell(new Paragraph());
cells5[i + 2] = new PdfPCell(new Paragraph());

listRow.add(row5);
} else if (dic.get(j).equals("MARK_PICTURES_ADDRESS")) {
if (null == ledgers.get(i).get(dic.get(j))) {
continue;
}
if ("".equals(ledgers.get(i).get(dic.get(j)))) {
continue;
}
String picPath = ledgers.get(i).get(dic.get(j)).toString();

String path = strAppRootPath + picPath;
path = path.replace("/", File.separator).replace("\\", File.separator);
Image image1 = Image.getInstance(path);
PdfPTable imageTable = new PdfPTable(1);
imageTable.addCell(image1);
PdfPCell cells6[] = new PdfPCell[3];
PdfPRow row6 = new PdfPRow(cells6);
cells6[i] = new PdfPCell(imageTable);// 单元格内容
cells6[i].setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中
cells6[i].setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中

cells6[i + 1] = new PdfPCell(new Paragraph());
cells6[i + 2] = new PdfPCell(new Paragraph());
listRow.add(row6);
}
}
document.add(table);
document.add(new Paragraph("\n"));

// //直线
// Paragraph p1 = new Paragraph(new Chunk(new LineSeparator()));
// document.add(p1);

// 底部表格
PdfPTable foot = new PdfPTable(3);
foot.setTotalWidth(99);
foot.setWidths(new float[] { 33f, 33f, 33f });
foot.setWidthPercentage(100.0F);

// 页数
int page = ledgers.size() + 1;
String total = "第" + i + 2 + "页," + "共" + page + "页";
// 时间
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
String time = fm.format(System.currentTimeMillis());
;
// 打印人
String print = "打印人:" + ResourceUtil.getSessionUser().getRealName();

PdfPCell cell1 = new PdfPCell(new Paragraph(total, s));
cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
cell1.setBorder(Rectangle.LEFT);
this.removeBorder(cell1);

PdfPCell cell2 = new PdfPCell(new Paragraph(time, s));
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setBorder(Rectangle.LEFT);
this.removeBorder(cell2);

PdfPCell cell3 = new PdfPCell(new Paragraph(print, s));
cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell3.setBorder(Rectangle.LEFT);
cell3.setBorder(Rectangle.RIGHT);
this.removeBorder(cell3);

foot.addCell(cell1);
foot.addCell(cell2);
foot.addCell(cell3);

document.add(foot);
}

// 第七步,关闭document
document.close();
} catch (DocumentException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("导出pdf成功~");
}

public void setResponseHeader(HttpServletResponse response, String fileName,String type) {
try {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/"+type+";charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 去掉边框
private PdfPCell removeBorder(PdfPCell cell) {
float lineHeight2 = (float) 30.0;
cell.setFixedHeight(lineHeight2);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中
// cell.setBorder(Rectangle.BOTTOM);
cell.setBorder(Rectangle.TOP);
return cell;
}

// excel 标题,导出人样式
private XSSFCellStyle setTitleStyle(int f, XSSFWorkbook workbook) {

// 表格标题样式
XSSFCellStyle style = workbook.createCellStyle();
// 居中
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 设置字体大小
XSSFFont titleFont = workbook.createFont();
titleFont.setFontName("微软雅黑");
titleFont.setFontHeightInPoints((short) f);
// 粗体显示
style.setFont(titleFont);
return style;
}

// excel 内容样式
private XSSFCellStyle setContentStyle(int f, XSSFWorkbook workbook) {

// 表格标题样式
XSSFCellStyle style = workbook.createCellStyle();
// 居中
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 设置字体大小
XSSFFont titleFont = workbook.createFont();
titleFont.setFontName("微软雅黑");
titleFont.setFontHeightInPoints((short) f);
// 粗体显示
style.setFont(titleFont);
return style;
}

}

时间: 2024-10-08 00:15:49

java 导出pdf的相关文章

java导出pdf文档

java导出pdf文档,多是iText实现的,可以创建pdf文档,并向文档写入内容. 1 导入包:itext-2.0.6.jar       itext必须使用的包. iTextAsian.jar      向pdf写入中文必须的包. 2 代码: package com.exp.pdf; import java.awt.Color; import java.io.FileOutputStream; import com.lowagie.text.Document; import com.lowa

Java导出pdf文件数据

提示:导出pdf文件,需要3个jar包iText-2.1.5.jar,iTextAsian.jar,iText-rtf-2.1.4.jar. public boolean outputPdfJhsy(EntityBean data) { try { Global.getInstance().LogApp("导出pdf开始"); String pdfpath = File.get("LEAP/NSESTModule/WRModule/nsjhsyzm.pdf").ge

Java使用IText(VM模版)导出PDF

Java使用IText(VM模版)导出PDF: public String createPDF(ProjectManageBase projectManageBase) { Map map = new HashMap();// velocity模板中的变量 try { //模版vm的路径 String tmPath = ServletActionContext.getServletContext() .getRealPath("/pdf/vm"); String pdfPath = S

Java使用IText(VM模版)导出PDF,IText导出word(二)

===============action=========================== //退款导出word    public void exportWordTk() throws IOException{         Long userId=(Long)ServletActionContext.getContext().getSession().get(Constant.SESSION_USER_ID);        //获取生成Pdf需要的一些路径        Strin

java根据模板导出pdf

在网上看了一些Java生成pdf文件的,写的有点乱,有的不支持写入中文字体,有的不支持模板,有的只是随便把数据放里面生成文件,完全不考虑数据怎样放置的以及以后的维护性,想想还是自己总结一个完全版的导出pdf的工具类吧,总结一下网上的方法,加上自己的完善.具有以下特点: 综合特点: 一对一,点对点的给对应的地方写值,比如模板里面放了个name标识,在程序里把"张三"赋给name,那么输出的pdf里面name的地方就变成了张三,准确方便快捷 支持中文,可以使用自己下载的字体. 支持图片:图

java根据模板文件导出pdf

原文:https://www.cnblogs.com/wangpeng00700/p/8418594.html 在网上看了一些Java生成pdf文件的,写的有点乱,有的不支持写入中文字体,有的不支持模板,有的只是随便把数据放里面生成文件,完全不考虑数据怎样放置的以及以后的维护性,想想还是自己总结一个完全版的导出pdf的工具类吧,总结一下网上的方法,加上自己的完善. 本次完善综合特点: 一对一,点对点的给对应的地方写值,比如模板里面放了个name标识,在程序里把"张三"赋给name,那么

利用iText 组件导出PDF

maven依赖:       <dependency>    <groupId>com.itextpdf</groupId>    <artifactId>itextpdf</artifactId>    <version>5.2.0</version>       </dependency> <!-- PDF输出中文的扩展包 -->       <dependency>    <

Java POI 导出EXCEL经典实现 Java导出Excel弹出下载框

在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者财务系统中用的非常普遍,因为这些系统经常要做一些报表打印的工作.而数据导出的格式一般是EXCEL或者PDF,我这里就用两篇文章分别给大家介绍下.(注意,我们这里说的数据导出可不是数据库中的数据导出!么误会啦^_^) 呵呵,首先我们来导出EXCEL格式的文件吧.现在主流的操作Excel文件的开源工具有很多,用得比较多的就是Apache的POI及JExcelAPI.这里我们用Apache POI!我们先去Apach

iText导出pdf、word、图片

一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或下载得到生成的报表,这样就很好的解决了B/S系统的报表处理问题. 二.iText简介 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转化为PDF文件. iText的