Printing web page programmatically in Java

ria picture ria · Oct 14, 2008 · Viewed 8.9k times · Source

I have a J2EE based web application.

In one of the pages there is a button labeled "Print".

My problem is something like this:

User enters tool names for e.g: ToolName1 ToolName2 ToolName3

Then clicks on "Print".

The intended action is that tool details of the 3 tools are retrieved from db and then printed one tool per page. (i.e On clicking this button some processing should take place in the background db retrieval before sending the details to the printer...)

Please suggest how best this task of printing the web page could be done.

Hope the problem is clear.

Thanks in advance...:)

Answer

Nick Pierpoint picture Nick Pierpoint · Oct 14, 2008

You could make the button call a bit of Javascript:

<script>
    function printPage() {
        window.print();  
    }
</script>

You'd call this using something like:

<form>
<input TYPE="button" onClick="printPage()">
</form>

or directly as:

<input TYPE="button" onClick="window.print()">

If you need to format the output onto multiple pages you would use the page-break-before CSS property. For example:

<style>
    div.tool {
        page-break-before: always
    }
</style>

<div class="tool" id="tool1">
...
</div>
<div class="tool" id="tool2">
...
</div>

You could put this in a "print" specific stylesheet as suggested by Guido García.