2011-05-09 21 views

Respuesta

1

La impresión en ExtJS no es particularmente fácil. El mejor recurso que he encontrado para hacer que los componentes se puedan imprimir se puede encontrar en un Sencha architect's blog. La publicación describe cómo configurar representadores de impresión personalizados para los componentes y otros detalles sobre la impresión. Sin embargo, esta información es para ExtJS 3.x; es posible que ExtJS 4 haya hecho la impresión más fácil.

+0

Ese enlace de Sencha architect está roto. – Blaise

+0

He actualizado el enlace para usar la copia de la publicación de blog de Wayback Machine. – NT3RP

7
    var targetElement = Ext.getCmp('PrintablePanelId'); 
        var myWindow = window.open('', '', 'width=200,height=100'); 
        myWindow.document.write('<html><head>'); 
        myWindow.document.write('<title>' + 'Title' + '</title>'); 
        myWindow.document.write('<link rel="Stylesheet" type="text/css" href="http://dev.sencha.com/deploy/ext-4.0.1/resources/css/ext-all.css" />'); 
        myWindow.document.write('<script type="text/javascript" src="http://dev.sencha.com/deploy/ext-4.0.1/bootstrap.js"></script>'); 
        myWindow.document.write('</head><body>'); 
        myWindow.document.write(targetElement.body.dom.innerHTML); 
        myWindow.document.write('</body></html>'); 
        myWindow.print(); 

escribe tu componente extjs imprimible en el documento.

+0

+1 Tomé este enfoque y lo amplié (ver respuesta a continuación) – Peter

1

¡Me gusta la respuesta de Gopal Saini! Tomé su enfoque y escribí una función para una de mis aplicaciones. Aquí está el código. Probado en FF y Safari. No lo he probado en IE, pero debería funcionar.

print: function(el){ 

    var win = window.open('', '', 'width='+el.getWidth()+',height='+el.getHeight()); 
    if (win==null){ 
     alert("Pop-up is blocked!"); 
     return; 
    } 


    Ext.Ajax.request({ 

     url: window.location.href, 
     method: "GET", 
     scope: this, 
     success: function(response){ 

      var html = response.responseText; 
      var xmlDoc; 
      if (window.DOMParser){ 
       xmlDoc = new DOMParser().parseFromString(html,"text/xml"); 
      } 
      else{ 
       xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
       xmlDoc.async = false; 
       xmlDoc.loadXML(html); 
      } 


      win.document.write('<html><head>'); 
      win.document.write('<title>' + document.title + '</title>'); 


      var xml2string = function(node) { 
       if (typeof(XMLSerializer) !== 'undefined') { 
        var serializer = new XMLSerializer(); 
        return serializer.serializeToString(node); 
       } else if (node.xml) { 
        return node.xml; 
       } 
      } 


      var links = xmlDoc.getElementsByTagName("link"); 
      for (var i=0; i<links.length; i++){ 
       win.document.write(xml2string(links[i])); 
      } 

      win.document.write('</head><body>'); 
      win.document.write(el.dom.innerHTML); 
      win.document.write('</body></html>'); 
      win.print(); 
     }, 
     failure: function(response){ 
      win.close(); 
     } 
    }); 
} 
0

Otra opción a considerar es procesar el componente en una imagen o pdf. Si bien la ventana emergente/opción de impresión es agradable, algunos navegadores no se imprimen correctamente. Tienden a ignorar las imágenes de fondo, ciertas propiedades de CSS, etc. Para que el componente se imprima exactamente de la manera que aparece en la ventana emergente, terminé escribiendo un código del lado del servidor para transformar el html en una imagen.

Esto es lo que se ve el código de cliente como:

print: function(el){ 

    var waitMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."}); 
    waitMask.show(); 


    //Parse current url to set up the host and path variables. These will be 
    //used to construct absolute urls to any stylesheets. 
    var currURL = window.location.href.toString(); 
    var arr = currURL.split("/"); 
    var len = 0; 
    for (var i=0; i<arr.length; i++){ 
     if (i<3) len+=(arr[i].length+1); 
    } 
    var host = currURL.substring(0, len); 
    if (host.substring(host.length-1)=="/") host = host.substring(0, host.length-1); 

    var path = window.location.pathname; 
    if (path.lastIndexOf("/")!=path.length-1){ 
     var filename = path.substring(path.lastIndexOf("/")+1); 
     if (filename.indexOf(".")!=-1){ 
      path = path.substring(0, path.lastIndexOf("/")+1); 
     } 
     else{ 
      path += "/"; 
     } 
    } 


    //Start constructing an html document that we will send to the server 
    var html = ('<html><head>'); 
    html += ('<title>' + document.title + '</title>'); 


    //Insert stylesheets found in the current page. Update href attributes 
    //to absolute URLs as needed. 
    var links = document.getElementsByTagName("link"); 
    for (var i=0; i<links.length; i++){ 
     var attr = links[i].attributes; 
     if (attr.getNamedItem("rel")!=null){ 

      var rel = attr.getNamedItem("rel").value; 
      var type = attr.getNamedItem("type").value; 
      var href = attr.getNamedItem("href").value; 

      if (href.toLowerCase().indexOf("http")!=0){ 
       if (href.toString().substring(0, 1)=="/"){ 
        href = host + href; 
       } 
       else{ 
        href = host + path + href; 
       } 
      } 

      html += ('<link type="' + type + '" rel="' + rel+ '" href="' + href + '"/>'); 
     } 
    } 

    html += ('</head><body id="print">'); 
    html += (el.dom.innerHTML); 
    html += ('</body></html>'); 


    //Execute AJAX request to convert the html into an image or pdf - 
    //something that will preserve styles, background images, etc. 
    //This, of course, requires some server-side code. In our case, 
    //our server is generating a png that we return to the client. 
    Ext.Ajax.request({ 

     url: "/WebServices/Print?action=submit", 
     method: "POST", 
     rawData: html, 
     scope: this, 
     success: function(response){ 
      var url = "/WebServices/Print?action=pickup&id="+response.responseText; 
      window.location.href = url; 
      waitMask.hide(); 
     }, 
     failure: function(response){ 
      win.close(); 
      waitMask.hide(); 
      var msg = (response.responseText.length>0 ? response.responseText : response.statusText); 
      alert(msg); 
     } 
    }); 
} 

Una vez más, esto requiere un poco de magia del lado del servidor para transformar el html en una imagen. En mi caso, implementé un servicio "Imprimir". Los clientes envían solicitudes de trabajo a través de la acción "enviar" y recuperan productos de salida a través de la acción "recolección".

Para convertir html a imágenes, terminé usando una aplicación de línea de comandos gratuita llamada Web Screen Capture. Solo funciona en Windows y no sé qué tan escalable es, así que utilícelo a su riesgo.

2

También puede añadir un componente a imprimir a la Ext.window.Window con una propiedad modal establecido en true y acaba de abrir un diálogo de impresión estándar que sólo se imprimirá el componente deseado .

var view = this.getView(); 
var extWindow = Ext.create('Ext.window.Window', { modal: true }); 
extWindow.add(component); // move component from the original panel to the popup window 
extWindow.show(); 

window.print(); // prints only the content of a modal window 

// push events to the event queue to be fired on the print dialog close 
setTimeout(function() { 
    view.add(component); // add component back to the original panel 
    extWindow.close(); 
}, 0); 
+0

Esto funcionó para mí; también creé una función para recorrer los componentes. Revisé la altura del panel e inserté un div vacío cuando necesitaba un salto de página –