Customize Jasper view format in Spring application
In my last article I discussed how to integrate or use jasper report as the view in spring application. Spring supports only PDF, XLS, CSV and HTML format for the jasper report view. If you want display your data in the jasper in different format is not available for spring jasper view class or your own view format; you have to override the JasperReportsMultiFormatView class in your spring application.
1) If you want to print the data in text format then override the class AbstractJasperReportsSingleFormatView.java and provide the method as given bellow:-
JasperReportsTextView.java
package spring.report.custom.view;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.export.JRTextExporter;
import org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsSingleFormatView;
public class JasperReportsTextView extends AbstractJasperReportsSingleFormatView {
public JasperReportsTextView() {
setContentType("text/plain");
}
@Override
protected JRExporter createExporter() {
JRTextExporter exporter = new JRTextExporter();
return exporter;
}
@Override
protected boolean useWriter() {
return true;
}
}
2) implement JasperReportsMultiFormatView.java class and place either in the spring.jar or place in your project.
JasperReportsMultiFormatView.java
package org.springframework.web.servlet.view.jasperreports;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperPrint;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContextException;
import org.springframework.util.ClassUtils;
import com.easyretail.reports.dm.JasperReportsTextView;
public class JasperReportsMultiFormatView extends AbstractJasperReportsView {
public static final String DEFAULT_FORMAT_KEY = "format";
private String formatKey = DEFAULT_FORMAT_KEY;
private Map formatMappings;
private Properties contentDispositionMappings;
public JasperReportsMultiFormatView() {
this.formatMappings = new HashMap(4);
this.formatMappings.put("csv", JasperReportsCsvView.class);
this.formatMappings.put("html", JasperReportsHtmlView.class);
this.formatMappings.put("pdf", JasperReportsPdfView.class);
this.formatMappings.put("xls", JasperReportsXlsView.class);
this.formatMappings.put("txt", JasperReportsTextView.class);
}
public void setFormatKey(String formatKey) {
this.formatKey = formatKey;
}
public void setFormatMappings(Properties mappingsWithClassNames) {
if (mappingsWithClassNames == null || mappingsWithClassNames.isEmpty()) {
throw new IllegalArgumentException("formatMappings must not be empty");
}
this.formatMappings = new HashMap(mappingsWithClassNames.size());
for (Enumeration discriminators = mappingsWithClassNames.propertyNames();
discriminators.hasMoreElements();) {
String discriminator = (String) discriminators.nextElement();
String className = mappingsWithClassNames.getProperty(discriminator);
try {
this.formatMappings.put(discriminator,
ClassUtils.forName(className));
}catch (ClassNotFoundException ex) {
throw new ApplicationContextException("Class [" + className
+ "] mapped to format [" + discriminator
+ "] cannot be found", ex);
}
}
}
public void setContentDispositionMappings(Properties mappings) {
this.contentDispositionMappings = mappings;
}
public Properties getContentDispositionMappings() {
if (this.contentDispositionMappings == null) {
this.contentDispositionMappings = new Properties();
}
return this.contentDispositionMappings;
}
protected void renderReport(JasperPrint populatedReport, Map model,
HttpServletResponse response) throws Exception {
String format = (String) model.get(this.formatKey);
if (format == null) {
throw new IllegalArgumentException("No format format found in model");
}
Class viewClass = (Class) this.formatMappings.get(format);
if (viewClass == null) {
throw new IllegalArgumentException("Format discriminator ["
+ format + "]is not a configured mapping");
}
if (logger.isDebugEnabled()) {
logger.debug("Rendering report using view class ["
+ viewClass.getName() + "]");
}
AbstractJasperReportsView view = (AbstractJasperReportsView)
BeanUtils.instantiateClass(viewClass);
// Copy appropriate properties across.
view.setExporterParameters(getExporterParameters());
// Can skip most initialization since all relevant URL processing
// has been done - just need to convert parameters on the sub view.
view.convertExporterParameters();
// Prepare response and render report.
populateContentDispositionIfNecessary(response, format);
view.renderReport(populatedReport, model, response);
}
private void populateContentDispositionIfNecessary(
HttpServletResponse response, String format) {
if (this.contentDispositionMappings != null) {
String header = this.contentDispositionMappings.getProperty(format);
if (header != null) {
response.setHeader(HEADER_CONTENT_DISPOSITION, header);
}
}
}
}
3) JRTextExporter.java extends JRAbstractExporter.java class and place in the place in your application.
package spring.report.custom.view;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRAlignment;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRPrintFrame;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JRPrintText;
import net.sf.jasperreports.engine.JRStyledTextAttributeSelector;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.util.JRStyledText;
import com.easyretail.reports.dm.PrintJobHelper;
public class JRTextExporter extends JRAbstractExporter{
private static final String TXT_ORIGIN_EXPORTER_FILTER_PREFIX =
JRProperties.PROPERTY_PREFIX + "export.txt.exclude.origin.";
protected int pageWidth;
protected int pageHeight;
protected int characterHeight;
protected int characterWidth;
protected JRExportProgressMonitor progressMonitor;
protected Writer writer;
char[][] pageData;
protected String betweenPagesText;
protected String lineSeparator;
StringBuffer pb;
protected static final String systemLineSeparator = System.getProperty("line.separator");
public void exportReport() throws JRException{
pb = new StringBuffer();
progressMonitor = (JRExportProgressMonitor)parameters
.get(JRExporterParameter.PROGRESS_MONITOR);
setOffset();
setInput();
if (!parameters.containsKey(JRExporterParameter.FILTER)){
filter = JROriginExporterFilter.getFilter (jasperPrint.getPropertiesMap(),
TXT_ORIGIN_EXPORTER_FILTER_PREFIX);
}
if (!isModeBatch) {
setPageRange();
}
String encoding = getStringParameterOrDefault(JRExporterParameter.CHARACTER_ENCODING,
JRExporterParameter.PROPERTY_CHARACTER_ENCODING);
Integer characterWidthParam = (Integer) parameters
.get(JRTextExporterParameter.CHARACTER_WIDTH);
if (characterWidthParam != null) {
characterWidth = characterWidthParam.intValue();
if (characterWidth <>0)
throw new JRException("Character width must be greater than 0");
}else {
Integer pageWidthParam = (Integer) parameters
.get(JRTextExporterParameter.PAGE_WIDTH);
if (pageWidthParam != null) {
pageWidth = pageWidthParam.intValue();
if (pageWidth <= 0)
throw new JRException("Page width must be greater than 0");
} else {
throw new JRException("Character or page width must be specified");
}
}
Integer characterHeightParam = (Integer) parameters
.get(JRTextExporterParameter.CHARACTER_HEIGHT);
if (characterHeightParam != null) {
characterHeight = characterHeightParam.intValue();
if (characterHeight <>0)
throw new JRException("Character height must be greater than 0");
} else {
Integer pageHeightParam = (Integer) parameters
.get(JRTextExporterParameter.PAGE_HEIGHT);
if (pageHeightParam != null) {
pageHeight = pageHeightParam.intValue();
if (pageHeight <= 0)
throw new JRException("Page height must be greater than 0");
} else {
throw new JRException("Character or page height must be specified");
}
}
betweenPagesText = (String) parameters.get(JRTextExporterParameter.BETWEEN_PAGES_TEXT);
if (betweenPagesText == null) {
betweenPagesText = systemLineSeparator + systemLineSeparator;
}
lineSeparator = (String) parameters.get(JRTextExporterParameter.LINE_SEPARATOR);
if (lineSeparator == null) {
lineSeparator = systemLineSeparator;
}
StringBuffer sb = (StringBuffer)parameters
.get(JRExporterParameter.OUTPUT_STRING_BUFFER);
if (sb != null){
try {
writer = new StringWriter();
exportReportToWriter();
sb.append(writer.toString());
} catch (IOException e) {
throw new JRException("Error writing to StringBuffer writer : "
+ jasperPrint.getName(), e);
} finally {
if (writer != null){
try {
writer.close();
}catch(IOException e){
}
}
}
}else {
writer = (Writer)parameters.get(JRExporterParameter.OUTPUT_WRITER);
if (writer != null){
try{
exportReportToWriter();
}catch (IOException e){
throw new JRException("Error writing to writer : " +
jasperPrint.getName(), e);
}
}else{
OutputStream os = (OutputStream)parameters
.get(JRExporterParameter.OUTPUT_STREAM);
if (os != null){
try{
writer = new OutputStreamWriter(os, encoding);
exportReportToWriter();
}catch (IOException e) {
throw new JRException("Error writing to OutputStream writer :
" + jasperPrint.getName(), e);
}
}else {
File destFile = (File)parameters
.get(JRExporterParameter.OUTPUT_FILE);
if (destFile == null){
String fileName = (String)parameters
.get(JRExporterParameter.OUTPUT_FILE_NAME);
if (fileName != null){
destFile = new File(fileName);
}else {
throw new JRException("No output specified for the
exporter.");
}
}
try{
os = new FileOutputStream(destFile);
writer = new OutputStreamWriter(os, encoding);
exportReportToWriter();
}catch (IOException e){
throw new JRException("Error writing to file writer : " +
jasperPrint.getName(), e);
}finally{
if (writer != null){
try{
writer.close();
}catch(IOException e){}
}
}
}
}
}
pb = null;
}
protected void exportReportToWriter() throws JRException, IOException{
for(int reportIndex = 0; reportIndex < jasperPrintList.size(); reportIndex++) {
jasperPrint = (JasperPrint)jasperPrintList.get(reportIndex);
List pages = jasperPrint.getPages();
if (pages != null && pages.size() > 0) {
if (isModeBatch) {
startPageIndex = 0;
endPageIndex = pages.size() - 1;
}
if (characterWidth > 0)
pageWidth = jasperPrint.getPageWidth() / characterWidth;
if (characterHeight > 0)
pageHeight = jasperPrint.getPageHeight() / characterHeight;
for(int i = startPageIndex; i <= endPageIndex; i++){
if (Thread.currentThread().isInterrupted()){
throw new JRException("Current thread interrupted.");
}
JRPrintPage page = (JRPrintPage)pages.get(i);
exportPage(page);
}
}
}
writer.flush();
PrintJobHelper printJobHelper = new PrintJobHelper();
ByteArrayInputStream byteArrayInputStream = new
ByteArrayInputStream(pb.toString().getBytes());
printJobHelper.printToDM(byteArrayInputStream);
}
protected void exportPage(JRPrintPage page) throws IOException{
List elements = page.getElements();
pageData = new char[pageHeight][];
for (int i = 0; i < pageHeight; i++) {
pageData[i] = new char[pageWidth];
Arrays.fill(pageData[i], ' ');
}
exportElements(elements);
for (int i = 0; i < pageHeight; i++) {
writer.write(pageData[i]);
pb.append(pageData[i]);
writer.write(lineSeparator);
pb.append(lineSeparator);
}
writer.write(betweenPagesText);
pb.append(betweenPagesText);
if (progressMonitor != null)
{
progressMonitor.afterPageExport();
}
}
protected void exportElements(List elements) {
for (int i = 0; i < style=""> {
Object element = elements.get(i);
if (element instanceof JRPrintText) {
exportText((JRPrintText) element);
} else if (element instanceof JRPrintFrame) {
JRPrintFrame frame = (JRPrintFrame) element;
setFrameElementsOffset(frame, false);
try{
exportElements(frame.getElements());
}finally{
restoreElementOffsets();
}
}
}
}
protected void exportText(JRPrintText element){
int rowCount = calculateYCoord(element.getHeight());
int columnCount = calculateXCoord(element.getWidth());
int x = calculateXCoord(element.getX() + getOffsetX());
int y = calculateYCoord(element.getY() + getOffsetY());
if (x + columnCount > pageWidth) {
//if the text exceeds the page width, truncate the column count
columnCount = pageWidth - x;
}
String allText;
JRStyledText styledText = getStyledText(element);
if (styledText == null) {
allText = "";
}else {
allText = styledText.getText();
}
// if the space is too small, the element will not be rendered
if (rowCount <= 0 || columnCount <= 0)
return;
if (allText != null && allText.length() == 0)
return;
// uses an array of string buffers, since the maximum number of rows
// is already calculated
StringBuffer[] rows = new StringBuffer[rowCount];
rows[0] = new StringBuffer();
int rowIndex = 0;
int rowPosition = 0;
int newLine = 0;
boolean isFirstLine = true;
// first search for \n, because it causes immediate line break
StringTokenizer lfTokenizer = new StringTokenizer(allText, "\n", true);
label:while (lfTokenizer.hasMoreTokens()) {
String line = lfTokenizer.nextToken();
// if text starts with a new line:
if(isFirstLine && line.equals("\n")){
rows[rowIndex].append("");
isFirstLine = false;
rowIndex++;
if(rowIndex == rowCount || !lfTokenizer.hasMoreTokens())
break label;
rowPosition = 0;
rows[rowIndex] = new StringBuffer();
line = lfTokenizer.nextToken();
}
// if there is a series of new lines:
int emptyLinesCount = 0;
while(line.equals("\n") && lfTokenizer.hasMoreTokens()) {
emptyLinesCount ++;
line = lfTokenizer.nextToken();
}
if(emptyLinesCount > 1){
for(int i = 0; i <>
rows[rowIndex].append("");
rowIndex++;
if(rowIndex == rowCount)
break label;
rowPosition = 0;
rows[rowIndex] = new StringBuffer();
//if this is the last empty line:
if(!lfTokenizer.hasMoreTokens() && line.equals("\n"))
{
rows[rowIndex].append("");
break label;
}
}
}
if(!line.equals("\n")){
StringTokenizer spaceTokenizer = new StringTokenizer(line, " ", true);
// divide each text line in words
while (spaceTokenizer.hasMoreTokens()) {
String word = spaceTokenizer.nextToken();
// situation: word is larger than the entire column
// in this case breaking occurs in the middle of the word
while (word.length() > columnCount) {
rows[rowIndex].append(word.substring(0,
columnCount - rowPosition));
word = word.substring(columnCount - rowPosition,
word.length());
rowIndex++;
if(rowIndex == rowCount)
break label;
rowPosition = 0;
rows[rowIndex] = new StringBuffer();
}
// situation: word is larger than remaining space on
// the current line
// in this case, go to the next line
if (rowPosition + word.length() > columnCount) {
rowIndex++;
if (rowIndex == rowCount)
break label;
rowPosition = 0;
rows[rowIndex] = new StringBuffer();
}
// situation: the word is actually a space and it situated
// at the beginning of a new line
// in this case, it is removed
if (rowIndex > 9 && rowPosition == 0 && word.equals(" "))
break;
// situation: the word is small enough to fit in the current line
// in this case just add the word and increment the cursor position
rows[rowIndex].append(word);
rowPosition += word.length();
}
rowIndex++;
if(rowIndex == rowCount)
break;
rowPosition = 0;
rows[rowIndex] = new StringBuffer();
}
}
int xOffset = 0;
int yOffset = 0;
if (element.getVerticalAlignment() == JRAlignment.VERTICAL_ALIGN_BOTTOM)
yOffset = rowCount - rowIndex;
if (element.getVerticalAlignment() == JRAlignment.VERTICAL_ALIGN_MIDDLE)
yOffset = (rowCount - rowIndex) / 2;
for (int i = 0; i <>
String line = rows[i].toString();
int pos = line.length() - 1;
while (pos >= 0 && line.charAt(pos) == ' ')
pos--;
line = line.substring(0, pos + 1);
if (element.getHorizontalAlignment() == JRAlignment.HORIZONTAL_ALIGN_RIGHT)
xOffset = columnCount - line.length();
if (element.getHorizontalAlignment() == JRAlignment.HORIZONTAL_ALIGN_CENTER)
xOffset = (columnCount - line.length()) / 2;
// if text is justified, there is no offset, but the line text is modified
// the last line in the paragraph is not justified.
if (element.getHorizontalAlignment() ==
JRAlignment.HORIZONTAL_ALIGN_JUSTIFIED)
if (i <>
line = justifyText(line, columnCount);
char[] chars = line.toCharArray();
System.arraycopy(chars, 0, pageData[y + yOffset + i],
x + xOffset, chars.length);
}
}
private String justifyText(String s, int width){
StringBuffer justified = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " ");
int tokenCount = t.countTokens();
if (tokenCount <= 1)
return s;
String[] words = new String[tokenCount];
int i = 0;
while (t.hasMoreTokens())
words[i++] = t.nextToken();
int emptySpace = width - s.length() + (words.length - 1);
int spaceCount = emptySpace / (words.length - 1);
int remainingSpace = emptySpace % (words.length - 1);
char[] spaces = new char[spaceCount];
Arrays.fill(spaces, ' ');
for (i = 0; i <>length - 1; i++)
{
justified.append(words[i]);
justified.append(spaces);
if (i <>
justified.append(' ');
}
justified.append(words[words.length-1]);
return justified.toString();
}
protected int calculateYCoord(int y) {
return pageHeight * y / jasperPrint.getPageHeight();
}
protected int calculateXCoord(int x) {
return pageWidth * x / jasperPrint.getPageWidth();
}
protected JRStyledText getStyledText(JRPrintText textElement) {
return textElement.getStyledText(JRStyledTextAttributeSelector.NONE);
}
}
4) Re-implement JasperReportsUtils in your application.
package spring.report.custom.view;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRTextExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
public abstract class JasperReportsUtils {
public static JRDataSource convertReportData(Object value)
throws IllegalArgumentException {
if (value instanceof JRDataSource) {
return (JRDataSource) value;
}else if (value instanceof Collection) {
return new JRBeanCollectionDataSource((Collection) value);
}else if (value instanceof Object[]) {
return new JRBeanArrayDataSource((Object[]) value);
}else {
throw new IllegalArgumentException("Value [" + value + "]
cannot be converted to a JRDataSource");
}
}
public static void render(JRExporter exporter, JasperPrint print, Writer writer)
throws JRException {
exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH,
new Integer(7));
exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT,
new Integer(14));
// exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH,new Integer(524));
// exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT,new Integer(14));
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, writer);
exporter.exportReport();
}
public static void render(JRExporter exporter, JasperPrint print,
OutputStream outputStream) throws JRException {
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
exporter.exportReport();
}
public static void renderAsCsv(JasperReport report, Map parameters,
Object reportData, Writer writer) throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
render(new JRCsvExporter(), print, writer);
}
public static void renderAsCsv(JasperReport report, Map parameters,
Object reportData, Writer writer, Map exporterParameters)
throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
JRCsvExporter exporter = new JRCsvExporter();
exporter.setParameters(exporterParameters);
render(exporter, print, writer);
}
public static void renderAsHtml(JasperReport report, Map parameters,
Object reportData, Writer writer) throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
render(new JRHtmlExporter(), print, writer);
}
public static void renderAsHtml(JasperReport report, Map parameters,
Object reportData, Writer writer, Map exporterParameters)
throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameters(exporterParameters);
render(exporter, print, writer);
}
public static void renderAsPdf(JasperReport report, Map parameters,
Object reportData, OutputStream stream) throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
render(new JRPdfExporter(), print, stream);
}
public static void renderAsPdf(JasperReport report, Map parameters,
Object reportData, OutputStream stream, Map exporterParameters)
throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameters(exporterParameters);
render(exporter, print, stream);
}
public static void renderAsXls(JasperReport report, Map parameters,
Object reportData, OutputStream stream) throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
render(new JRXlsExporter(), print, stream);
}
public static void renderAsXls(JasperReport report, Map parameters,
Object reportData, OutputStream stream, Map exporterParameters)
throws JRException {
JasperPrint print = JasperFillManager.fillReport(report,
parameters, convertReportData(reportData));
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameters(exporterParameters);
render(exporter, print, stream);
}
}
5) Re-implement PrintJobHelper in your application.
package com.easyretail.reports.dm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobEvent;
import javax.print.event.PrintJobListener;
public class PrintJobHelper implements PrintJobListener {
private String printJobStatus = null;
public PrintJobHelper() {}
public static String readCommandLineInput(String inputMessage) {
System.out.println(inputMessage);
Scanner scanner = new Scanner(System.in);
String inputLine = scanner.nextLine();
return inputLine;
}
public static void startPrinter(String fileLocation) {
// Request and read user input
// String sInstruction = "Enter path of the File to print: \n";
// String filePath = readCommandLineInput(sInstruction);
// Create a new File instance by converting the given pathname string
// into an abstract pathname.
File oFile = new File(fileLocation);
// Check if the file exists
boolean bFileExists = oFile.exists();
if (!bFileExists) {
// Inform the user that the file does not exist
System.out.println("File does not exist \n");
} else {
PrintJobHelper printJobHelperObj = new PrintJobHelper();
String status = printJobHelperObj.printAndWait(fileLocation);
System.out.println(status);
}
}
public String printAndWait(String filePath) {
// Input the file
FileInputStream textStream = null;
try {
textStream = new FileInputStream(filePath);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
return ("Could not find the file -" + exception.getMessage());
}
// Set the document type
DocFlavor myFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
// Create a Doc
Doc myDoc = new SimpleDoc(textStream, myFormat, null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
// discover the printers that can print the format according to the
// instructions in the attribute set
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// Create a print job from one of the print services
if (service != null) {
DocPrintJob job = service.createPrintJob();
job.addPrintJobListener(this);
try {
job.print(myDoc, aset);
// Wait till we know the status of our print job
while (printJobStatus == null) {
// Wait for 1 second before checking to see if the job is
// complete.
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
ignore.printStackTrace();
}
}
} catch (PrintException exception) {
exception.printStackTrace();
return ("Problems printing the file. -" + exception
.getMessage());
}
}
return printJobStatus;
}
public String printToDM(Object sb) {
// Input the file
// Set the document type
DocFlavor myFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
// Create a Doc
Doc myDoc = new SimpleDoc(sb, myFormat, null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
// discover the printers that can print the format according to the
// instructions in the attribute set
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// Create a print job from one of the print services
if (service != null) {
DocPrintJob job = service.createPrintJob();
job.addPrintJobListener(this);
try {
job.print(myDoc, aset);
// Wait till we know the status of our print job
while (printJobStatus == null) {
// Wait for 1 second before checking to see if the job is
// complete.
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
ignore.printStackTrace();
}
}
} catch (PrintException exception) {
exception.printStackTrace();
return ("Problems printing the file. -" + exception
.getMessage());
}
}
return printJobStatus;
}
@Override
public void printJobCompleted(PrintJobEvent pje) {
printJobStatus = "Printing successful";
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
printJobStatus = "Printing may be successful but no errors reported.";
}
@Override
public void printDataTransferCompleted(PrintJobEvent pje) {
}
@Override
public void printJobCanceled(PrintJobEvent pje) {
printJobStatus = "PrintJobHelper job cancelled.";
}
@Override
public void printJobFailed(PrintJobEvent pje) {
printJobStatus = "PrintJobHelper job failed.";
}
@Override
public void printJobRequiresAttention(PrintJobEvent pje) {
printJobStatus = "PrintJobHelper job requires attention.";
}
}
Note:
This classed directly print the view in the dot matrix format. If it is not required for your application skip the last class PrintJobHelper.java. remove this class reference from JasperREportUtil.java.
No comments:
Post a Comment