i am using a report in iReports, but I would want to print this with something changes in configuration for example: Copies, Orientation, Sides and others things; but it is not possible for me.
The fragment code is that:
InitialContext initialContext = new InitialContext();
DataSource dataSource = (DataSource) initialContext.lookup("java:/ds");
Connection connection = dataSource.getConnection();
String report = JasperCompileManager.compileReportToFile("report.jrxml");
JasperPrint jasperPrint = JasperFillManager.fillReport(report, new HashMap<String, Object>(), connection);
String defaultPrinter = PrintServiceLookup.lookupDefaultPrintService().getName().toLowerCase();
PrinterJob printerJob = PrinterJob.getPrinterJob();
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService selectedService = null;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(Sides.DUPLEX);
for (PrintService service : services) {
String existingPrinter = service.getName().toLowerCase();
if (existingPrinter.equals(defaultPrinter)) {
selectedService = service;
break;
}
}
if (selectedService != null) {
printerJob.setPrintService(selectedService);
boolean printSucceed = JasperPrintManager.printReport(jasperPrint, false);
}
I am using java language, help me please.
Related
Hi I am looking into using Java (to be deployed as servlets in Websphere 8.5) to integrate with SSRS. I have looked into some of the sample codes out there and try it out.
private static SoapHeader createExecutionIdSoapHeader(String executionId) {
Document doc = DOMUtils.createDocument();
Element executionHeaderElement = doc.createElement("ExecutionHeader");
executionHeaderElement.setAttribute("xmlns", XML_NAMESPACE);
Element executionIdElement = doc.createElement("ExecutionID");
executionIdElement.setTextContent(executionId);
executionHeaderElement.appendChild(executionIdElement);
SoapHeader soapH = new SoapHeader(new QName(XML_NAMESPACE, "ExecutionHeader"), executionHeaderElement);
return soapH;
}
public static Holder<byte[]> getReportResult(String output_type, String reportFolder, String reportName, ArrayOfParameterValue arrayOfParameterValue) {
Holder<byte[]> result = null;
try {
String historyID = null;
String executionID = null;
ReportExecutionServiceSoap service = getExecutionService();
BindingProvider bp = (BindingProvider) service;
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, authenticator.getUsername());
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, authenticator.getPassword());
ExecutionInfo info = new ExecutionInfo();
info = service.loadReport(REPORT_PATH, historyID);
executionID = info.getExecutionID();
List<Header> headers = new ArrayList<Header>();
SoapHeader header = createExecutionIdSoapHeader(executionID);
headers.add(header);
bp.getRequestContext().put(Header.HEADER_LIST, headers);
if (!arrayOfParameterValue.getParameterValue().isEmpty()) {
service.setExecutionParameters(arrayOfParameterValue, "en-us");
}
// Default to return HTML4.0
String deviceInfo = "";
if (output_type == null || output_type.isEmpty()) {
output_type = "HTML4.0";
}
if ("IMAGE".equalsIgnoreCase(output_type)) {
deviceInfo = RENDER_DEVICE_INFO_IMAGE;
} else {
deviceInfo = RENDER_DEVICE_INFO_HTML;
}
result = new Holder<byte[]>();
Holder<String> extension = new Holder<String>();
Holder<String> mimeType = new Holder<String>();
Holder<String> encoding = new Holder<String>();
Holder<ArrayOfWarning> warnings = new Holder<ArrayOfWarning>();
Holder<ArrayOfString> streamIDs = new Holder<ArrayOfString>();
service.render(output_type, deviceInfo, result, extension, mimeType, encoding, warnings, streamIDs);
} catch (Throwable th) {
th.printStackTrace();
}
return result;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ArrayOfParameterValue arrayOfParameterValue = new ArrayOfParameterValue();
List<ParameterValue> parameters = arrayOfParameterValue.getParameterValue();
ParameterValue parameterValue = new ParameterValue();
parameterValue.setName(PARAMETER_NAME);
parameterValue.setValue(PARAMETER_VALUE);
parameters.add(parameterValue);
Holder<byte[]> result = GenerateReport.getReportResult(REPORT_FORMAT, REPORT_FOLDER, REPORT_NAME,
arrayOfParameterValue);
System.out.println("--------------------------------- Writing to Browser --------------------------------");
ServletOutputStream out = response.getOutputStream();
out.write(result.value);
out.flush();
out.close();
System.out.println("--------------------------------- Writing to File -----------------------------------");
DateFormat df = new SimpleDateFormat("dd_MM_yy_HH_mm_ss_");
Date date = new Date();
String filename = df.format(date) + "SSRS_Report.pdf";
FileOutputStream o = new FileOutputStream("C:\\Users\\keh\\Desktop\\Temp\\" + filename);
o.write(result.value);
o.flush();
o.close();
} catch (Exception e) {
e.printStackTrace();
}
}
When I run the codes, I have this error :
[5/17/17 19:21:02:704 SGT] 000000c4 SystemErr R javax.xml.ws.soap.SOAPFaultException: The session identifier is missing. A session identifier is required for this operation. ---> Microsoft.ReportingServices.Diagnostics.Utilities.MissingSessionIdException: The session identifier is missing. A session identifier is required for this operation.
Any expert out there can point me to a solution pls?
P.S. I have tried to use WSBindingProvider as shown in Surendra Gurjar's Blog and it ran beautifully on an Apache server, but I got a ClassCastException when I deploy it to Websphere.
I'm trying to print from differents printer trays using javax.print with no luck, I have a printer HP Officejet Pro X476dw with 2 paper trays numbered 1 and 2.
My code is this:
public class ImprimeSide{
public static void main (String [] args) {
try {
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, null);
//Acquire Printer
PrintService printer = null;
for(PrintService serv: pservices){
if(serv.getName().contains("HP Officejet")){
printer = serv;
}
}
if(printer != null){
//Open File
FileInputStream fis = new FileInputStream("Documento2.pdf");
//Create Doc out of file, autosense filetype
Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
//Create job for printer
DocPrintJob printJob = printer.createPrintJob();
//Create AttributeSet
PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
//Add MediaTray to AttributeSet
pset.add(MediaTray.SIDE);
//Print using Doc and Attributes
printJob.print(pdfDoc, pset);
//Close File
fis.close();
}
}catch (Throwable t) {
t.printStackTrace();
}
}
}
Changing the line pset.add(MediaTray.SIDE) for every constant in the class MediaTray (TOP, BOTTOM, MANUAL.. etc) doesn't change anything, it will print taking paper from the default tray.
Any sugestion will be appreciated.
you must declare a MediaTray after mapping all media in a hashmap
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
for (PrintService service : services)
{
System.out.println(service);
// we retrieve all the supported attributes of type Media
// we can receive MediaTray, MediaSizeName, ...
Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
if (o != null && o.getClass().isArray())
{
for (Media media : (Media[]) o)
{
// we collect the MediaTray available
if (media instanceof MediaTray)
{
System.out.println(media.getValue() + " : " + media + " - " + media.getClass().getName());
trayMap.put(media.getValue(), media);
}
}
}
}
MediaTray selectedTray = (MediaTray) trayMap.get(Integer.valueOf(mediaId));
and after you add it to the PrintRequestAttributeSet
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(selectedTray);
And when you print you use this PrintRequestAttributeSet
DocPrintJob job = services[0].createPrintJob();
job.print(doc, attributes);
Jorge
I am using JasperReports API to print from my Java application. I am printing a report like this:
public void prints(String billNo, String fileName, String outFileName, String perameterName) {
HashMap hm = new HashMap();
hm.put(perameterName, billNo);
//Here parameterName is the parameter in JasperReport.
// billNo is the value from my java application.
try {
conn = new connection().db();
PrinterJob job = PrinterJob.getPrinterJob();
/* Create an array of PrintServices */
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService default_service = PrintServiceLookup.lookupDefaultPrintService();
int selectedService = 0;
/* Scan found services to see if anyone suits our needs */
for (int i = 0; i < services.length; i++) {
if (services[i].getName().toUpperCase().equals(default_service.getName().toUpperCase())) {
selectedService = i;
}
}
job.setPrintService(services[selectedService]);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.ISO_A4);
printRequestAttributeSet.add(new Copies(1));
JRPrintServiceExporter exporter;
exporter = new JRPrintServiceExporter();
JasperPrint print = JasperFillManager.fillReport(fileName, hm, conn);
JRExporter exporterr = new JRPdfExporter();
exporterr.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFileName);
exporterr.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
exporter.exportReport();
exporterr.exportReport();
} catch (JRException e) {
JOptionPane.showMessageDialog(null, e);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Printer not connected. Check power cable.");
}
}
I use to invoke this method in other classes.
But how can I pass multiple Parameters and multiple values to report?
for example query:
"select * from table1 where date>"+thisDate+" and date<"+thatDate+" "
How can I send thisDate and thatDate from my Java application?
Since you are using a HashMap you can store there many values. You can do it like:
HashMap hm = new HashMap();
hm.put(perameterName, billNo);
hm.put("thisDate", thisDate);
hm.put("theDate", theDate);
hm.put("anotherParam", paramValue);
If you don't want your method to pass so many keys and values as arguments, you can simply pass the "hm" object to your method:
public void prints( String fileName, String outFileName, HashMap hm){
I need to print to an Epson TM-T70 printer (Ethernet version) with Java. I can't found documentation about this. Which is the simplest way? Maybe using JavaPOS? Is there some example?
Thanks.
for our pos, I was able to do:
/* (non-Javadoc)
* #see be.intoit.pos.epsonagent.commands.Command#execute()
*/
public void execute() throws Exception {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
StringBuilder builder = new StringBuilder();
builder.append(toPrint);
builder.append(EscapeCodeUtil.createEscapeCode(10));
PrintRequestAttributeSet aset= new HashPrintRequestAttributeSet();
aset.add(new MediaPrintableArea(100,400,210,160,Size2DSyntax.MM));
InputStream is = new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));
Doc mydoc = new SimpleDoc(is, flavor, null);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//print using default
DocPrintJob
job = defaultService.createPrintJob();
job.print(mydoc, aset);
}
Where The util class was:
public class EscapeCodeUtil {
public static String createEscapeCode(int ... codes)
{
StringBuilder sb = new StringBuilder();
for(int code : codes)
sb.append((char) code);
return sb.toString();
}
}
This cut the paper
Socket sock = new Socket(IP_printer, 9100);
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.print(""+(char)29+(char)86+(char)0);
I try to create dynamic crosstab. When I try, I have an error java.lang.ClassCastException Jasper Report Crosstab than I solved it. But my report is empty. I don't get it why. I check my result set is empty or not. But it does not empty.
Here is my code:
public class DynamicJasperTemplate{
.....//variables define here
public void buildReport() throws Exception{
....//I create query here and get row column and measure field name
JRDataSource ds = getDataSource(query,a,b,c);//I get data from db as jrdatasource
DynamicReport dr = buildReportLayout(a,b,c,ds); // build report layout and add it crosstab in this method.
params.put("sr",ds);//I set report parameter value
JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, new ClassicLayoutManager(), params);
JasperPrint jp = JasperFillManager.fillReport(jr, params, ds);
JasperExportManager.exportReportToPdfFile(jp,"C:/report-out.pdf");
}
private DynamicReport buildReportLayout(String[] a,String[] b,String[] c, JRDataSource ds) {
FastReportBuilder drb = new FastReportBuilder();
drb.setWhenNoDataAllSectionNoDetail();
initStyles();
CrosstabBuilder cb = new CrosstabBuilder();
cb.setHeight(200)
.setWidth(500)
.setHeaderStyle(mainHeaderStyle)
.setDatasource("sr",DJConstants.DATA_SOURCE_ORIGIN_REPORT_DATASOURCE, DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE)
.setUseFullWidth(true)
.setColorScheme(4)
.setAutomaticTitle(true)
.setCellBorder(Border.PEN_1_POINT());
Object obj="NUMBER";
Object obj1="VARCHAR2";
String type = null;
for(int i=0; i<a.length; i++) {
DJCrosstabRow row = new CrosstabRowBuilder().setProperty(a[i],String.class.getName())
.setHeaderWidth(100).setHeight(0)
.setTitle(a[i])
.setShowTotals(true).setTotalStyle(totalStyle)
.setTotalHeaderStyle(totalHeader).setHeaderStyle(colAndRowHeaderStyle)
.build();
cb.addRow(row);
}
DJCrosstabColumn col =new CrosstabColumnBuilder().setProperty(b.toString(),"java.sql.Timestamp")
.setHeaderHeight(60).setWidth(50)
.setTitle(b.toString()).setShowTotals(true)
.setTotalStyle(totalStyle).setTotalHeaderStyle(totalHeader)
.setHeaderStyle(colAndRowHeaderStyle)
.build();
cb.addColumn(col);
cb.addMeasure(c[0],"java.math.BigDecimal", DJCalculation.NOTHING , c[0],measureStyle);
djcross = cb.build();
drb.addHeaderCrosstab(djcross);
drb.setUseFullPageWidth(true);
drb.addParameter("sr", "java.util.Collection");
DynamicReport dr = drb.build();
return dr;
}
private void initStyles() {
....//here ı define styles
}
private JRDataSource getDataSource(String query,String[] a,String[] b,String[] c) throws SQLException, JRException {
Connection con = new getConnection().conn();
List<Map<String, ?>> arr = new ArrayList<Map<String, ?>>();
String columnValue;
Map data = new HashMap();
JRResultSetDataSource result = null;
ResultSet rs = null;
int i;
try{
if(con!=null){
Statement stmt = con.createStatement();
rs = stmt.executeQuery(query);
JRDataSource ds = new JRResultSetDataSource(rs);
return ds;
}
......
I hope you can tell me the what I make wrong.
I solved my problem here solution :
when ı delete drb.addParameter("sr", "java.util.Collection"); and b.toString() i make error as unknown column change it b[0] than my problem solved.