1.先将字节数组输出流转成的字符串
/**
* @return 先将字节数组输出流转成的字符串
*/
public String generatePDF() {
byte[] result=null;
ByteArrayOutputStream baos = null;
Document doc =null;
PdfWriter.getInstance(document, new FileOutputStream(DEST));
try {
doc = new Document();// 可配其余4个参数,如(rectPageSize,60,60,60,60)页面边距
baos = new ByteArrayOutputStream();//构建字节输出流
PdfWriter.getInstance(doc,baos);//将PDF文档对象写入到流
doc.open();
// 解决中文问题
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
PdfPTable table = new PdfPTable(5)
Font smallTitleFont = new Font(bfChinese, 15, Font.NORMAL);
for (int aw = 0; aw < 10; aw++) {
// 构建每一格
table.addCell("cell");
}
document.add(table);
if(doc != null){
doc.close();
}
String result =new String(baos.toByteArray(), "ISO-8859-1");//转字符串设置编码
result = java.net.URLEncoder.encode(result, "ISO-8859-1");//如果跨域需设置编码
}catch(Exception e) {
log.error("PDF异常", e);
}finally{
if(baos != null){
try {
baos.close();
} catch (IOException e) {
log.error("PDF异常", e);
}
}
}
return result;
}
2.使用response进行下载
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String result= generatePDF();//生成PDF方法,返回字节数组文件流转成的字符串
result = java.net.URLDecoder.decode(result, "ISO-8859-1");//如果跨域需设置解码
ByteArrayInputStream inStream = new ByteArrayInputStream(
result.getBytes("ISO-8859-1"));
// 设置输出的格式
response.setContentType("bin");
response.addHeader("Content-Disposition","attachment; filename=\"" + fileName+ ".zip\"");
// 循环取出流中的数据
byte[] b = new byte[2048];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}