jqPrint – plugin di stampa per jQuery

livedemo

jqPrint - Logo
jqPrint è un plug-in per jQuery che consente di stampare una pagina o una porzione di html partendo da un elemento o un selettore jQuery.

Si basa principalmente sul famoso jPrintArea, di cui abbiamo corretto alcune imperfezioni e a cui abbiamo aggiunto alcune comode funzioni.

Come funziona:

Tutto ciò che bisogna fare è selezionare un elemento jQuery o un selettore e invocare il metodo jqprint():

$("div.toPrint").jqprint();
// . . .
$divToPrint.jqprint();

Otterremo la finestra di dialogo del sistema per la stampa.

Di default il plug-in ricerca tra i CSS della pagina i file con l’attributo media='print' e li importa nel documento da stampare, ciò permette di separare nettamente la presentazione per la normale navigazione col browser e per la stampa.

Update 19/06/2009

Attualmente sono previsti i seguenti parametri:

  • debug (bool, default false): permette di visualizzare in fondo al body il contenuto dell’iframe utilizzato per la stampa.
  • importCSS (bool, default true): indica al plugin se importare il CSS (con media=’print’, se presente) o se eseguire una stampa grezza del documento.
  • printContainer (bool, default true): indica al plugin se stampare anche l’html
    dell’elemento usato come selettore, se settato a false può causare dei problemi nell’applicazione delle regole css.
  • operaSupport (bool, default true): attiva un support per la stampa in Opera, effettuando la stampa da un tab temporaneo.

Compatibilità

jqPrint è stato testato con successo con Firefox 3.0.x, IE6, IE7, Safari 3&4, Google Chrome e, dalla versione 0.3, anche in Opera.
Attualmente la stampa dei documenti fra i vari browser presenta alcune diversità. E’ anche completamente dipendente dal CSS. Potrebbe essere interessante capire se siano applicabili delle funzioni di normalizzazione del layout… vedremo con le future release.

Per il momento buona stampa!

Condividi:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • TwitThis

  1. epescol scrive:

    Grazie per questo script che è molto utile ..

    E’possibile eliminare con la funzione l’eventuale formattazione dell’elemento ?

  2. eros scrive:

    Potresti farlo anche con la funzione, in linea di massima.
    Avevo in effetti una vaga idea di includere un sistema per normalizzare gli elementi da stampare…
    Ma il sistema più corretto è senz’altro quello di creare un CSS ad hoc per la stampa (media=’print’), che verrà automaticamente recuperato dal plugin.

    Nell’esempio allegato (ad esempio) il CSS per la stampa modifica il carattere e setta il background-color dei th a White.
    Ma niente ti vieta di fare modifiche alla formattazione degli elementi molto più “sostanziose”.

    Ti rimando al riguardo ad un articolo di ALA, molto interessante:
    http://www.alistapart.com/articles/goingtoprint/

  3. Sasha scrive:

    Grazie per un plugin molto attuale! Visto che e una versione ancora alfa, e possibile aggiungere funzionalita di stampare il contenuto di un iframe? intendo stampare un intera pagina web (per es., esterna) caricata nell’iframe da un link sulla nostra pagina.

  4. eros scrive:

    E’ una richiesta molto interessante, a cui non avevo pensato.
    Non credo ci siano problemi ad includere questa modifica nelle future release!
    Grazie dell’interessamento!

    edit: in effetti credo di aver parlato troppo presto. Operare su di un iframe ESTERNO al proprio sito (quindi di un altro dominio) solleva dei problemi di sicurezza del browser non aggirabili….

  5. Sasha scrive:

    Sono riuscito a farlo recentamente:
    var iframeDoc = $(‘.frameOuterDiv iframe’).contents();
    $(iframeDoc).find(“body”).attr(‘id’,'jqprintTarget’);
    $(iframeDoc).find(“style”).prepend(‘body’);
    $(iframeDoc).find(‘#jqprintTarget’).jqprint();
    Ma ci saranno sicuramente dei problemi con gli stili css esterni che sono collegati alla pagina esterna con tag – credo che sia impossibile spostarli nel body, i browser non potrebbero subire questo trattamento…

  6. Vernon G scrive:

    I am sorry but I only know and type english so I hope you can help me because I am trying to figure out how to do something with your plugin.

    I was able to get it working with no problem but I need to be able to have it NOT print the header of the print i.e. the link of the page that was printed. I don’t care if the footer is left in but I would really like to leave out the header because I am using it to print a receipt from an admin panel and while I have it password protected, I would rather people did not know the address to it.

    Also, I know I can set the browser to not print the header manually but I have found references that say its possible but I can not figure out how to do it with your plugin. thank you!

  7. eros scrive:

    I’m sorry but it is a browser setting, as you know. This plugin can only help you to set what in the page must be printed, but can’t manipulate browser’s printing settings…

  8. Klaus Albert scrive:

    sometimes it’s fine to use a otherwise unknown css file, so I added the option

    snip
    if (opt.useCSS)
    {
    doc.write(“”);
    }
    snap

    call
    $(“.info”).jqprint({useCSS:”/intranet/css/project.info.css”})

  9. eros scrive:

    Yes, it may be a nice feature for the next release.
    Thank you for the idea!

  10. Davide scrive:

    Mi succede una cosa strana: quando vado a stampare un div contenente dei checkbox, che in precedenza avevo selezionato, i checkbox in questione vengono deselezionati e poi parte la stampa.

    In i checkbox che avevo selezionato tramite un serialize, non vengono deselezionati MA nella stampa risultano deselezionati.

  11. eros scrive:

    Hai provato ad attivare il debug del plugin?
    Vediamo se nell’iframe i checkbox risultano deselezionati.

  12. dilishtv scrive:

    Hi..
    Nice plugin and working fine with IE6,7,8, ff
    but not working in Chrome and Safari.. it’s printing everything on the page. even the demo page

    Seems its not getting focus to the iframe. can you please help?

    Thanks alot

  13. eros scrive:

    You’re right, with chrome there’s that problem… but with safari 4.0.3 (win) it seems to work well.
    Can you tell me what is the version of your browsers?
    Thank you for the feedback!

  14. Davide scrive:

    Ciao,

    ho provato ad attivare il debug ed effettivamente i checkbox non risultano selezionati. Ti dirò di più: questo non mi succede in IE8 ma in FF si. Poi non solo i cb ma anche gli altri input (text e select) non risultano selezionati.
    Comunque ho capito che all’interno del div da stampare ci sono anche degli script da girare al document.load e questi vengono riprocessati con FF (come se mi resettasse la form quindi). Ho dovuto mettere un controllo in più: se è la prima volta che carico la pag esegui gli script inclusi nel div altrimenti non eseguirli.

    Alla fine mi succede che con IE8 tutto funziona (non so come dato che di solito è lui che rompe…) e con FF nella stampa vengono riportati i valori iniziali dei campi e non i valori dopo l’inputazione:solo se stampo la pagina dopo il suo caricamento e senza inputare i campi la stampa risulta corretta.

  15. dilishtv scrive:

    Sorry about my comment on Safari – I was trying with Chrome and it was not working and thought it would do the same with Safari.. as both are based on webkit.
    Its working fine with IE6, IE7, IE8, FF 2x and Safari. I have used media css to hide the contents in chrome. Any updates on this ??

    Thanks once again friend..!

  16. dilishtv scrive:

    Hi,

    I added a check for chrome browser and applied same “new window” logic as Opera does. So for Chrome and Opera it opens a new window instead of iframe and print perfectly as other browsers does.

    Thanks for a great plugin once again.

  17. Corrado scrive:

    @dilishtv: I’ve the same problem with Chrome 3.0.195.33. Can you post corrections you have made? Many thanks!

  18. dilishtv scrive:

    // ———————————————————————–
    // eros@recoding.it
    // jqprint 0.3
    //
    // – 19/06/2009 – some new implementations, added Opera support
    // – 11/05/2009 – first sketch
    //
    // Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
    // requires jQuery 1.3.x
    //————————————————————————

    (function($) {
    var opt;

    $.fn.jqprint = function(options) {
    opt = $.extend({}, $.fn.jqprint.defaults, options);

    var $element = (this instanceof jQuery) ? this : $(this);
    var chrome = $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
    if (opt.operaSupport && $.browser.opera || chrome) {
    var tab = window.open(“”, “Wynn Reservations”);
    tab.document.open();

    var doc = tab.document;
    }
    else {
    var $iframe = $(“”);

    if (!opt.debug) { $iframe.css({ position: “absolute”, width: “0px”, height: “0px”, left: “-600px”, top: “-600px” }); }

    $iframe.appendTo(“body”);
    var doc = $iframe[0].contentWindow.document;
    }

    if (opt.importCSS) {
    if ($(“link[media=print]“).length > 0) {
    $(“link[media=print]“).each(function() {
    doc.write(“”);
    });
    }
    else {
    $(“link”).each(function() {
    doc.write(“”);
    });
    }
    }

    if (opt.printContainer) { doc.write($element.outer()); }
    else { $element.each(function() { doc.write($(this).html()); }); }
    doc.close();
    ((opt.operaSupport && $.browser.opera) || chrome ? tab : $iframe[0].contentWindow).focus();
    setTimeout(function() { ((opt.operaSupport && $.browser.opera) || chrome ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);

    }

    $.fn.jqprint.defaults = {
    debug: false,
    importCSS: true,
    printContainer: true,
    operaSupport: true
    };

    // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
    jQuery.fn.outer = function() {
    return $($(”).html(this.clone())).html();
    }
    })(jQuery);

  19. KEVIN scrive:


    MedicamentSpot.com. Canadian Health&Care.No prescription online pharmacy.Best quality drugs.Special Internet Prices. High quality drugs. Order pills online

    Buy:Prozac.Advair.Zocor.Zetia.Acomplia.Cozaar.Lipitor.Amoxicillin.SleepWell.Aricept.Female Cialis.Ventolin.Buspar.Benicar.Seroquel.Wellbutrin SR.Nymphomax.Lasix.Lipothin.Female Pink Viagra….

Lascia un commento