关于jasperReport excel图像输出 pdf中文
package net.isone.vm.comm.util;
import java.awt.Color;
import java.awt.font.TextAttribute;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRBox;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRElement;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRFont;
import net.sf.jasperreports.engine.JRGraphicElement;
import net.sf.jasperreports.engine.JRPrintGraphicElement;
import net.sf.jasperreports.engine.JRPrintImage;
import net.sf.jasperreports.engine.JRRenderable;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.base.JRBaseFont;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.export.FontKey;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRExporterGridCell;
import net.sf.jasperreports.engine.export.JRGridLayout;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.export.JRXmlExporterParameter;
import net.sf.jasperreports.engine.export.PdfFont;
import net.sf.jasperreports.engine.export.JRGridLayout.ExporterElements;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.lowagie.text.Chunk;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.pdf.BaseFont;
/** */ /**
* for using chinese in pdf ,in the jrxml,set
* pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"
* @author shen
*/
public class JasperUtil {
static private Map reportMap = new HashMap();
/** */ /**
* using a tempMap to cache the report
* @param filePath
* @return
* @throws JRException
*/
private static JasperReport getReport(String filePath) throws JRException {
JasperReport report = (JasperReport) reportMap.get(filePath);
if (( true ) || (report == null )) {
// System.setProperty("jasper.reports.compile.class.path", "/WEB-INF/lib/jasperreports-1.2.3.jar");
System.out.println( " compile " );
/**/ /*
String resourceFile = "/report/" + filePath + ".xml";
InputStream input = JasperUtil.class
.getResourceAsStream(resourceFile);
*/
String resourceFile = " D:/eclipse/workspace/vm/src/report/ "
+ filePath + " .xml " ;
InputStream input = null ;
try {
input = new FileInputStream(resourceFile);
} catch (Exception e) {
e.printStackTrace();
}
if (input == null )
System.out.println(resourceFile + " not found " );
report = JasperCompileManager.compileReport(input);
reportMap.put(filePath, report);
}
return report;
}
/** */ /** Convenient exporting generated reports
* @param reportFile filepath of the report
* @param type pdf|rtf|htm|xml|csv|xls
* @param dataSource Collection of Map
* @param param a map include parameters using in report.
* @param out the outputStream to output,set null if saving to file.
* @param fileName set null if using outputStream
* @throws JRException
*/
public static void export(String reportFile, String type,
Collection dataCol, Map param, OutputStream out, String fileName)
throws JRException {
JasperReport report = getReport(reportFile);
JRDataSource dataSource = new ColDataSource(dataCol);
export(report, type, dataSource, param, out, fileName);
}
/** */ /**
* for exporting generated reports
* example: JasperUtil.export(jasperReport, "pdf", new ColDataSource(col), param, null, "reports/1.pdf");
* @param report
* @param type pdf|rtf|htm|xml|csv|xls
* @param dataSource if null auto set JREmptyDataSource
* @param param
* @param out set null if save to file.
* @param fileName set null if using outputStream
* @throws JRException
*/
public static void export(JasperReport report, String type,
JRDataSource dataSource, Map param, OutputStream out,
String fileName) throws JRException {
if (dataSource == null )
dataSource = new JREmptyDataSource();
JasperPrint jasperPrint = JasperFillManager.fillReport(report, param,
dataSource);
JRAbstractExporter exporter = null ;
if (type.equals( " pdf " )) {
exporter = new AdvPdfExporter();
} else if (type.equals( " rtf " )) {
exporter = new AdvRtfExporter();
} else if (type.equals( " htm " )) {
exporter = new JRHtmlExporter();
} else if (type.equals( " xml " )) {
exporter = new JRXmlExporter();
exporter.setParameter(JRXmlExporterParameter.IS_EMBEDDING_IMAGES,
Boolean.TRUE);
} else if (type.equals( " csv " )) {
exporter = new JRCsvExporter();
exporter
.setParameter(JRExporterParameter.CHARACTER_ENCODING, " GBK " );
} else if (type.equals( " xls " )) {
exporter = new AdvXlsExporter();
exporter.setParameter(
JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);
exporter.setParameter(
JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE,
Boolean.TRUE);
exporter.setParameter(
JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
Boolean.FALSE);
exporter.setParameter(
JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE);
try { // 把页数设的非常大,防止分页
java.lang.reflect.Field pageHeight;
pageHeight = JRBaseReport. class .getDeclaredField( " pageHeight " );
pageHeight.setAccessible( true );
pageHeight.setInt(report, Integer.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}
}
if (exporter != null ) {
exporter
.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
if (out != null )
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
else
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
fileName);
exporter.exportReport();
}
}
/** */ /**
* help to add Param ,build parameter as t1,t2,t3
* @param paramMap the origin map
* @param prefix
* @param values
*/
public static void setParam(Map paramMap, String prefix, String[] values) {
for ( int i = 0 ; i < values.length; i ++ ) {
paramMap.put(prefix + (i + 1 ), values[i]);
}
}
/** */ /**
* build Collection as t1,t2,t3
* @param paramMap the origin map
* @param prefix
* @param values
*/
public static Collection setCol(Collection col, String prefix, String[] keys) {
if (col == null )
return null ;
Collection result = new ArrayList();
for (Iterator iter = col.iterator(); iter.hasNext();) {
Map line = (Map) iter.next();
Map newLine = new HashMap();
for ( int i = 0 ; i < keys.length; i ++ ) {
newLine.put(prefix + (i + 1 ), line.get(keys[i]));
}
result.add(newLine);
}
return result;
}
/** */ /**
* 为我们常用的Map in collection的形式所作的adapter
* @author shen
*/
private static class ColDataSource implements JRDataSource {
Collection col;
Iterator iter;
Map line;
public ColDataSource(Collection col) {
this .col = col;
iter = col.iterator();
}
public Object getFieldValue(JRField jrField) throws JRException {
return line.get(jrField.getName());
}
public boolean next() throws JRException {
boolean hasNext = iter.hasNext();
if (hasNext)
line = (Map) iter.next();
return hasNext;
}
}
public static ColDataSource convertDataSource(Collection col) {
return new ColDataSource(col);
}
/** */ /**
* handle httpRequest,using parameter(reportType)=pdf|rtf|htm|xml|csv|xls
* @param reportName
* @param col
* @param param
* @param request
* @param response
* @return
* @throws IOException
* @throws JRException
*/
public static boolean exportInHttp(String reportName, Collection col,
Map param, HttpServletRequest request, HttpServletResponse response)
throws IOException, JRException {
String reportType = request.getParameter( " reportType " );
response.reset();
if (reportType == null )
return false ;
if (reportType.equals( " pdf " )) {
response.setContentType( " application/pdf " );
response.setHeader( " Content-Disposition " , " attachment;filename=\ ""
+ reportName + " .PDF\ "" );
} else if (reportType.equals( " rtf " )) {
response.setContentType( " application/x-download " );
response.setHeader( " Content-Disposition " , " attachment;filename=\ ""
+ reportName + " .RTF\ "" );
} else if (reportType.equals( " htm " )) {
response.setContentType( " text/html " );
} else if (reportType.equals( " xls " )) {
response.setContentType( " application/vnd.ms-excel " );
response.setHeader( " Content-Disposition " , " attachment;filename=\ ""
+ reportName + " .XLS\ "" );
} else if (reportType.equals( " xml " )) {
response.setContentType( " application/x-download " );
response.setHeader( " Content-Disposition " , " attachment;filename=\ ""
+ reportName + " .xml\ "" );
} else if (reportType.equals( " csv " )) {
response.setContentType( " application/x-download " );
response.setHeader( " Content-Disposition " , " attachment;filename=\ ""
+ reportName + " .csv\ "" );
} else
return false ;
OutputStream out = new BufferedOutputStream(response.getOutputStream());
JasperUtil.export(reportName, reportType, col, param, out, null );
out.flush();
out.close();
return true ;
}
private static class AdvPdfExporter extends JRPdfExporter {
protected Chunk getChunk(Map attributes, String text) throws JRException, DocumentException, IOException {
JRFont jrFont = new JRBaseFont(attributes);
jrFont.setPdfFontName( " STSong-Light " );
jrFont.setPdfEncoding( " UniGB-UCS2-H " );
jrFont.setPdfEmbedded( true );
Exception initialException = null ;
Color forecolor = (Color) attributes.get(TextAttribute.FOREGROUND);
Color backcolor = (Color) attributes.get(TextAttribute.BACKGROUND);
Font font = null ;
PdfFont pdfFont = null ;
FontKey key = new FontKey(jrFont.getFontName(), jrFont.isBold(), jrFont.isItalic());
Map fontMap = (Map) parameters.get(JRExporterParameter.FONT_MAP);
if (fontMap != null && fontMap.containsKey(key)) {
pdfFont = (PdfFont) fontMap.get(key);
} else {
pdfFont = new PdfFont(jrFont.getPdfFontName(), jrFont.getPdfEncoding(), jrFont.isPdfEmbedded());
}
try {
font = FontFactory.getFont(pdfFont.getPdfFontName(), pdfFont.getPdfEncoding(), pdfFont.isPdfEmbedded(), jrFont.getFontSize(),
(pdfFont.isPdfSimulatedBold() ? Font.BOLD : 0 ) | (pdfFont.isPdfSimulatedItalic() ? Font.ITALIC : 0 ) | (jrFont.isUnderline() ? Font.UNDERLINE : 0 )
| (jrFont.isStrikeThrough() ? Font.STRIKETHRU : 0 ), forecolor);
if (font.getBaseFont() == null && font.family() == Font.UNDEFINED) {
font = null ;
}
} catch (Exception e) {
initialException = e;
}
if (font == null ) {
byte [] bytes = null ;
try {
bytes = JRLoader.loadBytesFromLocation(pdfFont.getPdfFontName(), classLoader, urlHandlerFactory);
} catch (JRException e) {
throw new JRException( " Could not load the following font : " + " \npdfFontName : " + pdfFont.getPdfFontName() + " \npdfEncoding : "
+ pdfFont.getPdfEncoding() + " \nisPdfEmbedded : " + pdfFont.isPdfEmbedded(), initialException);
}
BaseFont baseFont = BaseFont.createFont(pdfFont.getPdfFontName(), pdfFont.getPdfEncoding(), pdfFont.isPdfEmbedded(), true , bytes, null );
font = new Font(baseFont, jrFont.getFontSize(), ((pdfFont.isPdfSimulatedBold()) ? Font.BOLD : 0 ) | ((pdfFont.isPdfSimulatedItalic()) ? Font.ITALIC : 0 )
| (jrFont.isUnderline() ? Font.UNDERLINE : 0 ) | (jrFont.isStrikeThrough() ? Font.STRIKETHRU : 0 ), forecolor);
}
Chunk chunk = new Chunk(text, font);
if (backcolor != null ) {
chunk.setBackground(backcolor);
}
return chunk;
}
}
/** */ /**
* advanced XlsExporter to support image
* @author shen
*
*/
private static class AdvXlsExporter extends JRXlsExporter {
private HSSFPatriarch patriarch = null ;
protected ExporterElements getExporterElements() {
return JRGridLayout.UNIVERSAL_EXPORTER;
}
protected void exportImage(JRPrintImage printImage, JRExporterGridCell gridCell, int colIndex, int rowIndex) {
try {
int x1 = 0 ;
int x2 = 0 ;
int y1 = 0 ;
int y2 = 0 ;
int col1 = colIndex;
int col2 = col1 + gridCell.colSpan;
int row1 = rowIndex;
int row2 = row1 + gridCell.rowSpan;
if (patriarch == null ) patriarch = sheet.createDrawingPatriarch();
HSSFClientAnchor Anchor = new HSSFClientAnchor(x1, y1, x2, y2, ( short ) col1, row1, ( short ) col2, row2);
Anchor.setAnchorType( 0 );
int imageIndex = workbook.addPicture(printImage.getRenderer().getImageData(), HSSFWorkbook.PICTURE_TYPE_JPEG);
// System.out.println("image set "+imageIndex);
patriarch.createPicture(Anchor, imageIndex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** */ /**
* advanced XlsExporter to support image
* @author shen
*
*/
private static class AdvRtfExporter extends JRRtfExporter {
private int zorder = 1 ;
protected void exportImage(JRPrintImage printImage, int offsetx, int offsety) throws JRException, IOException {
int x = twip(printImage.getX() + globalOffsetX);
int y = twip(printImage.getY() + globalOffsetY);
int width = twip(printImage.getWidth());
int height = twip(printImage.getHeight());
if (printImage.getMode() == JRElement.MODE_OPAQUE) {
startGraphic( " dprect " , x, y, width, height);
finishGraphic(JRGraphicElement.PEN_NONE, printImage.getForecolor(), printImage.getBackcolor(), 1 );
}
int leftPadding = printImage.getLeftPadding();
int topPadding = printImage.getTopPadding();
int rightPadding = printImage.getRightPadding();
int bottomPadding = printImage.getBottomPadding();
int availableImageWidth = printImage.getWidth() - leftPadding - rightPadding;
availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth;
int availableImageHeight = printImage.getHeight() - topPadding - bottomPadding;
availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight;
JRRenderable renderer = printImage.getRenderer();
if (availableImageWidth > 0 && availableImageHeight > 0 && renderer != null ) {
writer.write( " {\\*\\do\\dobxpage\\dobypage " );
writer.write( " \\dodhgt " + (zorder ++ ));
writer.write( " \\dptxbx " );
writer.write( " \\dpx " + twip(printImage.getX() + leftPadding + globalOffsetX + offsetx));
writer.write( " \\dpxsize " + twip(availableImageWidth));
writer.write( " \\dpy " + twip(printImage.getY() + topPadding + globalOffsetY + offsety));
writer.write( " \\dpysize " + twip(availableImageHeight));
writer.write( " \\dpfillpat0 " );
writer.write( " \\dplinehollow " );
writer.write( " {\\dptxbxtext " );
writer.write( " {\\pict\\jpegblip " );
writer.write( " \\picwgoal " );
writer.write(twip(availableImageWidth) + "" );
writer.write( " \\pichgoal " );
writer.write(twip(availableImageHeight) + "" );
writer.write( " \n " );
// ByteArrayInputStream bais = new
// ByteArrayInputStream(JRImageLoader.loadImageDataFromAWTImage(bi));
ByteArrayInputStream bais = new ByteArrayInputStream(printImage.getRenderer().getImageData());
int count = 0 ;
int current = 0 ;
while ((current = bais.read()) != - 1 ) {
String helperStr = Integer.toHexString(current);
if (helperStr.length() < 2 ) {
helperStr = " 0 " + helperStr;
}
writer.write(helperStr);
count ++ ;
if (count == 64 ) {
writer.write( " \n " );
count = 0 ;
}
}
writer.write( " \n}}}\n " );
}
if (printImage.getTopBorder() == JRGraphicElement.PEN_NONE && printImage.getLeftBorder() == JRGraphicElement.PEN_NONE
&& printImage.getBottomBorder() == JRGraphicElement.PEN_NONE && printImage.getRightBorder() == JRGraphicElement.PEN_NONE) {
if (printImage.getPen() != JRGraphicElement.PEN_NONE) {
startGraphic( " dprect " , x, y, width, height);
finishGraphic(printImage);
}
} else {
exportBox(printImage, x, y, width, height, printImage.getForecolor(), printImage.getBackcolor());
}
}
private int twip( int points) {
return points * 20 ;
}
private void startGraphic(String type, int x, int y, int w, int h) throws IOException {
writer.write( " {\\*\\do\\dobxpage\\dobypage " );
writer.write( " \\dodhgt " + (zorder ++ ));
writer.write( " \\ " + type);
writer.write( " \\dpx " + x);
writer.write( " \\dpy " + y);
writer.write( " \\dpxsize " + w);
writer.write( " \\dpysize " + h);
}
private void finishGraphic(JRPrintGraphicElement element) throws IOException {
int mode = 0 ;
if (element.getMode() == JRElement.MODE_OPAQUE) {
mode = 1 ;
}
finishGraphic(element.getPen(), element.getForecolor(), element.getBackcolor(), mode);
}
private void finishGraphic( byte pen, Color fg, Color bg, int fillPattern) throws IOException {
switch (pen) {
case JRGraphicElement.PEN_THIN:
writer.write( " \\dplinew10 " );
break ;
case JRGraphicElement.PEN_1_POINT:
writer.write( " \\dplinew20 " );
break ;
case JRGraphicElement.PEN_2_POINT:
writer.write( " \\dplinew40 " );
break ;
case JRGraphicElement.PEN_4_POINT:
writer.write( " \\dplinew80 " );
break ;
case JRGraphicElement.PEN_DOTTED:
writer.write( " \\dplinedash " );
break ;
case JRGraphicElement.PEN_NONE:
writer.write( " \\dplinehollow " );
break ;
default :
writer.write( " \\dplinew20 " );
break ;
}
writer.write( " \\dplinecor " + fg.getRed());
writer.write( " \\dplinecob " + fg.getBlue());
writer.write( " \\dplinecog " + fg.getGreen());
writer.write( " \\dpfillfgcr " + fg.getRed());
writer.write( " \\dplinefgcb " + fg.getBlue());
writer.write( " \\dpfillfgcg " + fg.getGreen());
writer.write( " \\dpfillbgcr " + bg.getRed());
writer.write( " \\dpfillbgcg " + bg.getGreen());
writer.write( " \\dpfillbgcb " + bg.getBlue());
writer.write( " \\dpfillpat " + fillPattern);
writer.write( " }\n " );
}
private void exportBox(JRBox box, int x, int y, int width, int height, Color fg, Color bg) throws IOException {
if (box.getTopBorder() != JRGraphicElement.PEN_NONE) {
Color bc = box.getTopBorderColor();
byte pen = box.getTopBorder();
int a = getAdjustment(box.getTopBorder());
if (bc == null ) {
bc = fg;
}
startGraphic( " dpline " , x, y + a, width, 0 );
finishGraphic(pen, bc, bg, 1 );
}
if (box.getLeftBorder() != JRGraphicElement.PEN_NONE) {
Color bc = box.getLeftBorderColor();
byte pen = box.getLeftBorder();
int a = getAdjustment(pen);
if (bc == null )
bc = fg;
startGraphic( " dpline " , x + a, y, 0 , height);
finishGraphic(pen, bc, bg, 1 );
}
if (box.getBottomBorder() != JRGraphicElement.PEN_NONE) {
Color bc = box.getBottomBorderColor();
byte pen = box.getBottomBorder();
int a = getAdjustment(pen);
if (bc == null )
bc = fg;
startGraphic( " dpline " , x, y + height - a, width, 0 );
finishGraphic(pen, bc, bg, 1 );
}
if (box.getRightBorder() != JRGraphicElement.PEN_NONE) {
Color bc = box.getRightBorderColor();
byte pen = box.getRightBorder();
int a = getAdjustment(pen);
if (bc == null )
bc = fg;
startGraphic( " dpline " , x + width - a, y, 0 , height);
finishGraphic(pen, bc, bg, 1 );
}
}
}
public static void main(String[] args) throws Exception {
System.out.println( " go " );
Map param = new HashMap();
JasperUtil.setParam(param, " t " , new String[] { " 第一 " , " aa " , " 害虫 " } );
Collection col = new ArrayList();
{
Map map = new HashMap();
map.put( " f1 " , " 123 " );
map.put( " f2 " , " 345 " );
map.put( " f3 " , " 最后 " );
col.add(map);
}
{
Map map = new HashMap();
map.put( " f1 " , " 111 " );
map.put( " f2 " , " 222 " );
map.put( " f3 " , " 333 " );
col.add(map);
}
{
Map map = new HashMap();
map.put( " f1 " , " 123123 " );
map.put( " f2 " , " 123213 " );
map.put( " f3 " , " 最后 " );
col.add(map);
}
String reportFile = " report1 " ;
export(reportFile, " pdf " , col, param, null , " d:/1.pdf " );
export(reportFile, " htm " , col, param, null , " d:/2.htm " );
export(reportFile, " rtf " , col, param, null , " d:/3.rtf " );
export(reportFile, " csv " , col, param, null , " d:/4.csv " );
export(reportFile, " xls " , col, param, null , " d:/5.xls " );
System.out.println( " ok " );
}
}
这个星期研究了一下jasper,为了一些具体问题,比如编译,比如中文问题和图像输出,忙活了一阵子
在j2ee下,需要
jasperreports-1.2.3.jar
commons-javaflow.jar
itext-1.3.1.jar
iTextAsian.jar
jdt-compiler-3.1.1.jar
poi-3.0-alpha1-20050704.jar
jdt那个包,如果用jrxml就需要否则会乱报错,如果直接用jasper可能是不要的
解决问题后,成果代码见上,相信对同志们很有用。
之中getReport这个方法,务必重写。
主要特性:
pdf中文,不用特意指定字体,统一在代码中指定
excel支持图形输出
rtf(word)原图形输出非常模糊,改进