需要:itext-2.1.7.jar 和 iTextAsian.jar (*版本要匹配) 和 javabase64-1.3.1.jar 。還要echarts的包。
一、頁面
<a class="link search" id="btnPDF" onclick="exportPDF();" ><span></span>導出PDF</a>
<form id="chartForm" style="display:none">
<input id="imageValue" name="base64Info" type="hidden" maxlength="50000"/>
</form>
<div id="tu" style="height:350px"> </div>
二、js
<script type="text/javascript">
var thisChart ;
$(function(){
thisChart = echarts.init(document.getElementById('tu'));
// 以此 示例圖 為例子
option = {
title: {
text: 'ECharts 入門示例'
},
tooltip: {},
legend: {
data:['銷量']
},
xAxis: {
data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
thisChart.setOption(option);
});
function exportPDF(){
var chartExportUrl = 'exportPDF.htm';
var picBase64Info = thisChart.getDataURL();//獲取echarts圖的base64編碼,為png格式。
$('#chartForm').find('input[name="base64Info"]').val(picBase64Info);//將編碼賦值給隱藏域或輸入框
$('#chartForm').attr('action',chartExportUrl).attr('method', 'post');//設置提交到的url地址 ,提交方式為post
$('#chartForm').submit();
}
</script>
三、action (SpringMVC框架)
/**
* 導出PDF start
*/
@RequestMapping("exportPDF")
public void exportPDF(HttpServletRequest request,HttpServletResponse response,String base64Info) throws MalformedURLException, IOException, DocumentException{
String urlAdress =request.getSession().getServletContext().getRealPath("/") //獲取項目web根目錄 如要保存在項目里exportFilePath=urlAdress
ResultMessage message=null;
String newFileName;
String num = String.valueOf(System.currentTimeMillis());
newFileName = "xx" + num + ".pdf";
String newPngName = newFileName.replaceFirst(".pdf", ".png");
String exportFilePath = "d:/export";
base64Info = base64Info.replaceAll(" ", "+");
BASE64Decoder decoder = new BASE64Decoder();
String[] arr = base64Info.split("base64,");
byte[] buffer;
try {
buffer = decoder.decodeBuffer(arr[1]);
} catch (IOException e) {
throw new RuntimeException();
}
OutputStream output = null;
try {
output = new FileOutputStream(new File(exportFilePath+newPngName));//生成png文件
output.write(buffer);
output.flush();
output.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
message=new ResultMessage(ResultMessage.Fail, "導出失敗");
}
Pdf(exportFilePath+newPngName,exportFilePath+newFileName);
File f = new File(exportFilePath+newPngName);
if(f.exists()){
f.delete();
}
File file = new File("d:/export"+num+".pdf");
Desktop.getDesktop().open(file); //文件自動打開預覽
/* 如要下載到本地 執行下面代碼。(提交方式不能用ajax,否則不報錯不彈出下載框。)
String urlss=urlAdress+num+".pdf"; //下載文件地址
String path=urlss;
File file = new File(path);// path是根據日志路徑和文件名拼接出來的
String filename = file.getName();// 獲取日志文件名稱
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffers = new byte[fis.available()];
fis.read(buffers);
fis.close();
response.reset();
// 先去掉文件名稱中的空格,然后轉換編碼格式為utf-8,保證不出現亂碼,這個文件名稱用於瀏覽器的下載框中自動顯示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffers);// 輸出文件
os.flush();
os.close();
*/
message=new ResultMessage(ResultMessage.Success, "成功導出到D盤根目錄");
addMessage(message, request);
response.sendRedirect(request.getContextPath()+"/platform/report/alertReport/list.htm");
JOptionPane.showMessageDialog(null, "導出成功"); //這種彈窗linux可能不支持。
}
//通過png文件來生成pdf文件
public File Pdf(String imagePath, String mOutputPdfFileName) throws com.lowagie.text.DocumentException, MalformedURLException, IOException {
//建立com.lowagie.text.Document對象的實例。(A4紙,左右上下邊距)
Document document = new Document(PageSize.A4, 10, 10, 20, 20);
//add Chinese font 需要 下載遠東字體包iTextAsian.jar
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 10, com.lowagie.text.Font.NORMAL);
//Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.GREEN);
try {
//建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁盤中。
PdfWriter.getInstance(document, new FileOutputStream(mOutputPdfFileName));
//打開文檔。
document.addTitle("標題");
document.open();
document.newPage();
Image png = Image.getInstance(imagePath);
float heigth = png.getHeight();
float width = png.getWidth();
int percent = this.getPercent2(heigth, width);
png.setAlignment(Image.MIDDLE);
png.setAlignment(Image.TEXTWRAP);
png.scalePercent(percent + 3);
png.setAlignment(Image.MIDDLE); //圖片居中顯示
document.add(new Paragraph("zzzzzzzzzzzz"));
document.add(new Paragraph("Hello World"));
document.add(png);
document.add(new Paragraph("zzzzzzzzzzzz"));
document.add(new Paragraph("Hello World"));
//添加表格 start
PdfPTable table = new PdfPTable(6);
table.setWidthPercentage(90); //表格寬度比 默認為80
Paragraph p=new Paragraph("表頭",FontChinese);
PdfPCell cell = new PdfPCell(p); //表頭
cell.setMinimumHeight(23f);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
cell.setColspan(6); //合並6列
cell.setBackgroundColor(new Color(235, 235, 235));
table.addCell(cell);
PdfPCell cell2 = new PdfPCell(new Paragraph("1列",FontChinese)); //中文要放在Paragraph()里面才會顯示出來
PdfPCell cell3 = new PdfPCell(new Paragraph("2列",FontChinese));
PdfPCell cell4 = new PdfPCell(new Paragraph("3列",FontChinese));
PdfPCell cell5 = new PdfPCell(new Paragraph("4列",FontChinese));
PdfPCell cell6 = new PdfPCell(new Paragraph("5列",FontChinese));
PdfPCell cell7 = new PdfPCell(new Paragraph("6列",FontChinese));
cell2.setBackgroundColor(new Color(235, 235, 235));
cell3.setBackgroundColor(new Color(235, 235, 235));
cell4.setBackgroundColor(new Color(235, 235, 235));
cell5.setBackgroundColor(new Color(235, 235, 235));
cell6.setBackgroundColor(new Color(235, 235, 235));
cell7.setBackgroundColor(new Color(235, 235, 235));
table.addCell(cell2);table.addCell(cell3);
table.addCell(cell4);table.addCell(cell5);
table.addCell(cell6);table.addCell(cell7);
//增加每行列數
for(int i=0;i<5;i++){
table.addCell("1.1我");
table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell("cell test1");
}
//cell.setRowspan(2); //合並行
//cell.setColspan(2); //合並列
document.add(table);
//添加表格 end
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
return mOutputPdfFile;
}
//統一按照寬度壓縮 這樣來的效果是,所有圖片的寬度是相等的
private int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
/**
* 導出PDF end
*/
效果圖:注:先讓效果出來,再根據實際需求修改。
參照出處:
http://www.open-open.com/doc/view/8d8f3fc183584f7ca52c8a4ed3a0164e PDFPTable幫助文檔。
http://www.cnblogs.com/crazyjava/p/3199936.html Java生成PDF報表
http://blog.csdn.net/zwx19921215/article/details/34439851 Java通過IText導出word和pdf
http://blog.csdn.net/qq_22778121/article/details/54175358 Echarts導出為pdf