Introduction
It's easy to set watermark on webpages, we have to set body background-image property with y axis-repeat but the problem is backgrounds do not print by default. The user would have to change their browser's print settings. So you should find a different way to show your watermark using text or an <img>
element. Here I am going to set watermark image dynamically at the time of page printing with the help of iframe and table.
Background
I have multiple pages of data in the gridview and I have to set watermark image at the time of printing. Most people firstly try to set Background-image property of a body or any control on a page to set watermark. It shows the watermark in the background. But when you print it, it disappears as default print setting removes background images or colors.
Solution
One of the solution to this problem is to repeat table header on page at the time of print and place a watermark image in the header along with the style "display:table-header-group;
" so the watermark will show on each page.
Using the code
First of the key thing is to repeat header of a gridview on page print. so we have to set following properties to gridview.
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
Then another important thing is set a style to gridview
thread.
<style type = "text/css">
thead
{
display:table-header-group;
}
</style>
Now add image into the header of gridview.
<asp:TemplateField HeaderText="id">
<HeaderTemplate>
<img alt="" src="watermark.jpg" style="z-index:-1;position:absolute"/>ID
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
I use iframe and div to print the content with watermark.
<div id="divcontents">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
......
</div>
<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>
<script type="text/javascript">
function ClickHereToPrint(){
try{
var oIframe = document.getElementById('ifmcontentstoprint');
var oContent = document.getElementById('divcontents').innerHTML;
var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
if (oDoc.document) oDoc = oDoc.document;
oDoc.write("<html><head><style type = 'text/css'>" +
"thead {display:table-header-group;}</style>");
oDoc.write("</head><body onload='this.focus(); this.print();'>");
oDoc.write(oContent + "</body></html>");
oDoc.close();
}
catch(e){
self.print();
}
}
</script>
Just Call the print script to see the magic.
Points of Interest
Here the property of table's header group is used to repeat watermark image on each and every printed page.