Mohammad Saberi
Mohammad Saberi

Reputation: 13166

Copy a part of page into clipboard using jQuery

I have a web application written in PHP with many reports in HTML format. Sometimes, I have different reports in one page and each of them have a print button.

One solution I have is to generate that report again using PHP variables in a new page.

But I think there is another way to do it. I can copy all of the report table HTML codes into clipboard, open a new window, paste clipboard data on it and finally print the page contents. I saw something in http://archive.plugins.jquery.com/project/clipboard, but it seems that this plugin does not work anymore.

Do you have any idea to solve my problem (cross-browser)?

Upvotes: 0

Views: 974

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

I can copy all of the report table HTML codes into clipboard, open a new window, paste clipboard data on it and finally print the page contents.

You don't need the clipboard for this, and even if you could get it to work you shouldn't use the clipboard for this: the clipboard is there for the user's convenience, not yours, and overwriting whatever was in it before is not appropriate.

Fortunately you can open a new window and set its contents without going anywhere near the clipboard:

function printReport(elementId)
{
  var elementToPrint = $("#" + elementId),
      printWin = window.open("", "Print", 'left=20,top=20,width=400,height=400');

  printWin.document.write(elementToPrint.html());
  printWin.document.close();
  printWin.focus();
  printWin.print();
  printWin.close(); // optionally close the new window immediately
}

Working demo (tested only in Chrome): http://jsfiddle.net/Vc5yy/

Note that obviously this is just a bare-bones solution, but it should give you all the pieces you need to complete your own solution. You'll probably want to apply an appropriate CSS stylesheet, etc. But the main thing is once you've opened a second window you can write whatever you want to it and then call the window.print() function.

Note that you should run the above function from an event handler (like from a button click as shown in my demo) or the browser's popup blocker probably won't let it open.

Upvotes: 3

Related Questions