Direto pra impressora no Jasper Reports

19 respostas
R

Pessoal,
Como faço para mandar um relatório do Jasper Reports direto pra impressão, sem aparecer o relatório na tela ou a janela de impressão do Windows?

[]'s

19 Respostas

G

JasperPrintManager.printPage(jasperPrint, 0, true);

R

Testei dessa forma e mesmo assim apareceu a tela de impressão do Windows. :cry:

R

Já resolvi, era só trocar true por false :thumbup:

Grato!

L

valeu pela dica
:lol:

M

Desta forma pelo que entendi vai mandar para a impressora default, como faço para setar o “path” da impressora ?

M

Para constar,
Resolvi assim :

private void printDirectlyToPrinter(String printerName,JasperPrint jasperPrint)
	{	
		try {
			//Lista todas impressoras até encontrar a enviada por parametro
			PrintService serviceFound = null;
			PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
			for(PrintService service:services){
				if(service.getName().trim().equals(printerName.trim()))
					serviceFound = service;
			}
			
			if (serviceFound == null)
				throw new NegocioException("Impressora não encontrada !");
			
			JRExporter exporter = new JRPrintServiceExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, serviceFound.getAttributes());
			exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
			exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
			exporter.exportReport();
			
			//JasperPrintManager.printPage(jasperPrint, 0, false);
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
L
JasperReport:

a) - Visualizar a pagina

JasperViewer.viewReport(jasperPrint, false);

b) - Direto para impressora

JasperPrintManager.printPage(jasperPrint, 0, false);
  • A impressora que vai receber o relatorio, será a que estiver padrão !

Falou

V

é possível em um projeto Web ? Esse comando era imprimir no servidor, correto ?

L

ola

esse script serve para desktop, em web (a linha que envia os dados direto para impressora, acredito que seria com um applet)

V

humm!
vou verificar!

valeu

L

da uma olhada nesta applet

import javax.swing.JApplet;

import javax.swing.SwingUtilities;

import javax.swing.JLabel;

import java.io.;
import javax.swing.
;

public class impressodir extends JApplet {

public void init() {

	String impna = "PRN";
	try {


		String dadosw = getParameter("dadosApplet");  	//--- recupera dados 
					
            		PrintWriter pw = new PrintWriter(new FileOutputStream(impna));
            		pw.println(dadosw);
            		pw.close();


        } catch (Exception p) {
      			p.printStackTrace();
        }

}

}

----------------------------- assinando a applet.jar ------------------
del impressodir.jar

jar cvf impressodir.jar *.class

keytool -genkey -dname “cn=impressodir, ou=SeuNome, o=EmpresaTall, c=BR” -alias Impralias -storepass 123456 -validity 3655

jarsigner -storepass 123456 impressodir.jar Impralias

----------------------------- abrir minha applet ------------------------ com minha jsp -----------

<APPLET codebase="." archive="impressodir.jar" code="impressodir" width=300 height=2 alt="Impressao Invalida !"> <PARAM name="dadosApplet" VALUE="<%out.print(dadosw);%>"> </APPLET>

----------------------------- colocar tudo na mesma pasta … jar, jsp eu coloquei ate a class … e estou utilizando …

espero que ajude
t+ :lol:

V

e se for um pdf ?

L

Cara vc sabe se é possivel a applet apos execução de determinada ação fechar o navegador? Por exemplo, eu fiz uma applet de impressão direta, e gostaria q apos a impressao ela fosse fechada !!! tem como ?

V

TEnte fechar com javascript

javascript:parent.close();

L

Mas eu so posso fechar apos a impressao, eu ouvi falar que existe um modo da applet executar o java script da página, so nao sei como !!!

V

veja o link tem um exemplo rodando

http://www.raditha.com/java/mayscript.php

como fez a impressão? pode postar o código, ou pelo menos uma parte ?

L
Então Vinicius a primeira parte fiz o seguinte, enviei o xml do relatorio (oque é gerado pelo Ireport), por parametro e tambem o resultset por parametro. Mas o result set fiz uma classe que faz a conversão dele para XML. Assim:
public String cachedRowSetToXml(CachedRowSetImpl crs) throws Exception{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element results = doc.createElement(&quot;Results&quot;);
        doc.appendChild(results);

        ResultSetMetaData rsmd = crs.getMetaData();
        int colCount = rsmd.getColumnCount();
        if(colCount &gt; 0){
            Element metadata = doc.createElement(&quot;Metadata&quot;);
            results.appendChild(metadata);

            for(int j=1; j&lt;=colCount; j++){
                Element node = doc.createElement(rsmd.getColumnName(j));
                node.setAttribute(&quot;type&quot;, String.valueOf(rsmd.getColumnType(j)));
                metadata.appendChild(node);
            }

            while (crs.next()) {
                Element row = doc.createElement(&quot;Row&quot;);
                results.appendChild(row);
                for (int i = 1; i &lt;= colCount; i++) {
                    Object value = crs.getObject(i);
                    Element node = doc.createElement(rsmd.getColumnName(i));
                    node.appendChild(doc.createTextNode((value == null ? &quot;&quot; : value.toString())));
                    row.appendChild(node);
                }
            }
        }

        DOMSource domSource = new DOMSource(doc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, &quot;no&quot;);
        transformer.setOutputProperty(OutputKeys.METHOD, &quot;xml&quot;);
        transformer.setOutputProperty(OutputKeys.ENCODING, &quot;ISO-8859-1&quot;);
        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        transformer.transform(domSource, sr);

        return sw.toString();
    }
Na applet eu faço o caminho inverso com esse XML gerado através de CachedRowSet. Assim :
private CachedRowSetImpl xmlToCachedRowSet(String xml) throws Exception{

        CachedRowSetImpl crs = new CachedRowSetImpl();
        RowSetMetaData rsmd  = new RowSetMetaDataImpl();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(xml.getBytes(&quot;ISO-8859-1&quot;)));

        Element elem = doc.getDocumentElement();

        //verifica se xml é de erro ou vazio
        if(elem.getTagName().equalsIgnoreCase(&quot;Error&quot;)){
            throw new Exception(&quot;IntegrateService: &quot;+elem.getTextContent());
        }
        else if(elem.getTagName().equalsIgnoreCase(&quot;Empty&quot;)){
            return crs;
        }

        NodeList nl = elem.getElementsByTagName(&quot;Row&quot;);
        NodeList metaList = elem.getElementsByTagName(&quot;Metadata&quot;);

        //monta o metada do CachedRowSet
        if(metaList.getLength() &gt; 0){
            NodeList metaNodeList = metaList.item(0).getChildNodes();
            rsmd.setColumnCount(metaNodeList.getLength());
            for(int x=0; x&lt;metaNodeList.getLength(); x++){
                Element dt = (Element) metaNodeList.item(x);
                rsmd.setColumnLabel(x+1, dt.getTagName());
                rsmd.setColumnName(x+1, dt.getTagName());
                rsmd.setColumnType(x+1, Integer.parseInt(dt.getAttribute("type")));
            }
            crs.setMetaData(rsmd);
        }

        //Monta os dados do CachedRowSet
        for(int i=0; i&gt;&lt;nl.getLength(); i++) {
            NodeList cList = nl.item(i).getChildNodes();
            crs.moveToInsertRow();
            for(int y=0; y&gt;&lt;cList.getLength(); y++){
                Element data = (Element)cList.item(y);
                int type = rsmd.getColumnType(y+1);
                String value = "";
                if(data.hasChildNodes()) value = data.getFirstChild().getNodeValue();

                //insere o valor pelo tipo de dado
                if(value.isEmpty())
                    crs.updateNull(data.getTagName());
                else if(type == java.sql.Types.INTEGER || type == java.sql.Types.NUMERIC || type == java.sql.Types.SMALLINT)
                    crs.updateInt(data.getTagName(), Integer.parseInt(value));
                else if(type == java.sql.Types.FLOAT || type == java.sql.Types.DOUBLE || type == java.sql.Types.DECIMAL)
                    crs.updateDouble(data.getTagName(), Double.parseDouble(value));
                else if (type == java.sql.Types.TIMESTAMP || type == java.sql.Types.DATE){
                    java.util.Date dataUtil = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(value);
                    java.sql.Date dataSql = new java.sql.Date(dataUtil.getTime());
                    crs.updateDate(data.getTagName(), dataSql);
                } else
                    crs.updateString(data.getTagName(), value);

            }
            crs.insertRow();
            crs.moveToCurrentRow();
            crs.afterLast();

        }
        crs.beforeFirst();

        return crs;

    }
Agora tendo o Xml do relatorio e o cached das informações foi só compilar o relatório e boa ... A unica coisa q ainda esta me faltando é a applet enviar um comando javascript para fechar assim que terminar a impressão. Olha a Applet:
@Override
    public void init() {
        try {
            imprimir();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,"ERRO:"+ ex.toString());
            Logger.getLogger(impressao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void imprimir() throws Exception {
        JasperReport layout = null;
        /* Pega Parametros */
        getParameters();
        if(!xmlRel.isEmpty() && !xmlCached.isEmpty()){
            /* Carrega o Design do Relatorio */
            JasperDesign jasperDesign = JRXmlLoader.load(new java.io.ByteArrayInputStream((xmlRel).getBytes("UTF-8")));
            /* Compila o Relatorio */
            layout = JasperCompileManager.compileReport(jasperDesign);
            if (isComplete()){
                /* Parametros de Localidade para Data no Relatorio */
                parameters.put("REPORT_LOCALE", new Locale("pt", "BR"));
                JasperPrint jasperPrint = null;
                /* Cached de Informações para o Relatorio */
                CachedRowSetImpl crs = xmlToCachedRowSet(xmlCached);
                /* Relatório Gerado */
                jasperPrint = JasperFillManager.fillReport(layout, parameters, new JRResultSetDataSource((java.sql.ResultSet)crs));
                /* Faz a Impressão de Acordo com o parametro de visualização da configuração de Impressão */
                JasperPrintManager.printPage(jasperPrint, 0, propPrint);
            }
        }

    }
>
J

Alguem conseguiu fazer a impressão do PDF para a impressora?

L

Eu acabei de fazer um teste aqui e até consegui imprimir um arquivo PDF vindo de uma URL direto na impressora, o problema é que o PDF não esta vindo no tamanho normal, não sei pq! Olha o código.

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPrintPage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;

/**
 *
 * @author LGBIZZAN
 */
public class Print3 {

    public Print3(boolean showDialog, String imp) {
        try {
            String url = "http://xxxxxx/xxxx/resultados/AAKALWCCLWYHHYZNADGX.pdf";
            String docName = "C:\\Temp\\teste.pdf";
            /*Busca Arquivo na URL*/
            URL remote = new URL(url);
            URLConnection conn = remote.openConnection();
            conn.setRequestProperty("Accept", "*/*");
            InputStream in = conn.getInputStream();
                                    
            File fl = new File(docName);                    
            
            /*Escrever o File*/
            OutputStream outputStream = new FileOutputStream(fl);
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }            
            
            FileInputStream fis = new FileInputStream(fl);
            FileChannel fc = fis.getChannel();
            ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            
            PDFFile curFile = new PDFFile(bb); // Create PDF Print Page
            PDFPrintPage pages = new PDFPrintPage(curFile);

            PrinterJob pjob = PrinterJob.getPrinterJob();                      
            pjob.setJobName(docName);
            Book book = new Book();
            PageFormat pformat = PrinterJob.getPrinterJob().defaultPage();
            book.append(pages, pformat, curFile.getNumPages());
            pjob.setPageable(book);

            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            //aset.add(MediaSizeName.ISO_A4); // informa o tipo de folha 
            //aset.add(javax.print.attribute.standard.MediaTray.ENVELOPE);
            // print
            if (showDialog) {
                if(pjob.printDialog())
                    pjob.print();
            }else{
                PrintService impressora = null;
                if(!imp.isEmpty())
                    impressora = buscaImpressora(imp);
                else
                    impressora = PrintServiceLookup.lookupDefaultPrintService();
                pjob.setPrintService(impressora);
                
                pjob.print(aset);
            }
            if(fl.exists())
                fl.delete();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Print3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Print3.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PrinterException ex) {
            Logger.getLogger(Print3.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public PrintService buscaImpressora(String i){
        PrintService impressora = null;
        DocFlavor df = DocFlavor.SERVICE_FORMATTED.PRINTABLE;  
        PrintService[] ps = PrintServiceLookup.lookupPrintServices(df, null);  
        for (PrintService p: ps) {
            if(p.getName().equalsIgnoreCase(i)){                
                impressora = p;
                break;
            }
        }
        return impressora;
    }
    
    public static void main(String[] args) {  
        new Print3(true,null);
    }
}

Alguem tem uma ideia ?

Criado 4 de agosto de 2006
Ultima resposta 13 de set. de 2013
Respostas 19
Participantes 7