package com.ulic.gis.customerCenter.controller;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
/**
* 生成pdf字节数组
* 将字节数组转成pdf
* 2019年7月12日
*/
@Controller
public class CreatePdfByte {
private static final Logger log = LoggerFactory.getLogger(CreatePdfByte.class);
/**
* 生成pdf的字节数组
*/
@RequestMapping(value="/generatePDF")
public byte[] generatePDF() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();//构建字节输出流
Document doc =null;
try {
doc = new Document(new Rectangle(PageSize.A4));// 可配其余4个参数,如(rectPageSize,60,60,60,60)页面边距
PdfWriter.getInstance(doc,baos);//将PDF文档对象写入到流
doc.open();
doc.add(new Paragraph("Hello World 啦啦啦 success!"));
if(doc != null){
doc.close();
}
}catch(Exception e) {
log.error("PDF异常", e);
}finally{
if(baos != null){
try {
baos.close();
} catch (IOException e) {
log.error("PDF异常", e);
}
}
}
byte[] b = baos.toByteArray();//pdf字节数组
System.out.println("baos.toByteArray().length:"+baos.toByteArray().length);
return b;
}
/**
* 将字节数组转成pdf文件
* @throws IOException
*/
@RequestMapping(value="/array2pdf")
public void array2pdf() throws IOException {
System.out.println("开始生成pdf字节数组");
byte[] b = generatePDF();
String filename = "D:/testpdf/array2pdf.pdf";
FileOutputStream fout = new FileOutputStream(filename);
//将字节写入文件
fout.write(b);
fout.close();
}
}
转自:https://www.cnblogs.com/yinyl/p/11175581.html