1. 程式人生 > >java 導出pdf

java 導出pdf

horizon chunk setborder frequency utf ann 組件 ane simple

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;
}

}

java 導出pdf