Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Wednesday, March 17, 2021

How to check whether the current user has edit permission for a particular list using JSOM in SharePoint 2013

 we first need to get the login name of user and pass it to the get_effectiveBasePermissions method.


To ensure that user has edit permission, we will check the SP.PermissionKind.editListItems enum.


SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

    getCurrentUserPermission();

});



function getCurrentUserPermission()

{    

    var web,clientContext,currentUser,oList,perMask;


    clientContext = new SP.ClientContext.get_current();

    web = clientContext.get_web();

    currentUser = web.get_currentUser();   

    oList = web.get_lists().getByTitle('Test List');

    clientContext.load(oList,'EffectiveBasePermissions');

    clientContext.load(currentUser); 

    clientContext.load(web);           


    clientContext.executeQueryAsync(function(){

        if (oList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems)){

            console.log("user has edit permission");

        }else{

             console.log("user doesn't have edit permission");

        }   

    }, function(sender, args){

        console.log('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());

    });

}

Friday, July 24, 2020

JavaScript : How to Convert UTC Date Time to local/EST Hours using JavaScript?

In this below script, Convert UTC Date Time to local/EST Hours

Convert UTC Date Time to local/EST Hours In SharePoint
In this article , we will use default java-script action

Type 1:

var localTime = new Date();
var localKolkata = moment.tz(localTime, "Asia/Kolkata").format("hh:mm:ss");

Javascript script provide date and time format.

Type 2:

function getLocalTime(i) {
    if (typeof i !== 'number') return;
    var d = new Date();
    var len = d.getTime();
    var offset = d.getTimezoneOffset() * 60000;
    var utcTime = len + offset;
    return new Date(utcTime + 3600000 * i);
}

#sharepoint #javascript #datetime #jquery #convertdatetime

Monday, June 20, 2016

How to get Auto populate dropdown in SharePoint List using SPServices?

In this below script, Auto populate dropdown in SharePoint List using SPServices

Auto populate dropdown in SharePoint List using SPServices

<input type="text" id="txtsearch" onkeyup="binddetails()">
Code:
function binddetails()
{
availableTags = [];

  $().SPServices({
            operation: "GetListItems",
            async: false,
            listName: "Keywords",
              CAMLQuery: "<Query><Where><Contains><FieldRef Name='Title' /><Value Type='Text'>"+$("#txtsearch").val()+"</Value></Contains></Where></Query>",
                       CAMLViewFields: "<ViewFields Properties='True' />",
            completefunc: function(xData, Status) {
                var ktop = "";
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    var titl = "N/A";
                    if ($(this).attr("ows_Title") != null) {
                       // titl = ;
                        availableTags.push($(this).attr("ows_Title"));
                    }
                    });
                    }
                    });
                       $("#txtsearch").autocomplete({
      source: availableTags
    });
}

Thursday, May 12, 2016

How to get all the td values of a Table in a JavaScript function?

In this below script, get all the td values of a Table in a JavaScript

get all the td values of a Table using JavaScript In SharePoint
Script:

$("#tblemp tbody tr").each(function() {

     
      alert($(this).find("td:last-child").html());
    });

HTML:

<table id="tblemp" class="display" cellspacing="0" width="100%">
        <thead>
           <tr>
              <th></th>
             <th>Name</th>
            <th>Position</th>
            <th>Office</th>
           <th>Age</th>
           <th>Start date</th>
          <th>Salary</th>

    </tr>
</thead>
<tbody>
    <tr>
       <td class="details-control" ></td>      
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$320,800</td>


    </td>
    </tr>
 
 
  </tbody>
  </table>

Tuesday, April 26, 2016

Item Adding / Item Added Event Receiver for Document Library

In this below script, Item Adding / Item Added Event Receiver

Item Adding / Item Added Event Receiver In SharePoint
Ways to retrieve data are:

Properties.ListItem[«FieldName »]

Properties.AfterProperties[«FieldName »]

Properties.BeforeProperties[«FieldName »]


we must add the synchronization parameter


 to our xml definition.


<Receiver>
<Name>EventReceiver1ItemAdded</Name>
<Type>ItemAdded</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>TutoTaxonomy.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
<Synchronization>Synchronous</Synchronization>
</Receiver>
In our code we add an update of the column “test”


public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
properties.ListItem["test"] = "test synchro";
properties.ListItem.Update();
}

Saturday, April 9, 2016

Print css using Window.print() using pdf print

In this below script, Print css using Window.print

Print css using Window.print In SharePoint
<style type="text/css" media="print">
@page {
    size: auto;   /* auto is the initial value */
    margin: 0;  /* this affects the margin in the printer settings */
}
</style>


@page :left {
  margin-left: 4cm;
  margin-right: 3cm;
}

@page :right {
  margin-left: 3cm;
  margin-right: 4cm;
}

Freeze header in SharePoint List 2013

In this below script, Freeze header in SharePoint List 2013

Freeze header in SharePoint List
The stickyHeaders widget as part of the Sharepoint List .

_spBodyOnLoadFunctionNames.push("stickyHeaders");

function stickyHeaders() {//-----------------------------------------------------------------------------------------------------------------------------------------------
//Class
function List () {
this.list               = "";
this.webpart            = "";
this.sticky             = "";
this.header             = "";
this.dphm               = "";
this.s4                 = "";
this.contentBox = "";
this.top_old            = 0;
this.top_new            = 0;
this.bottom_old         = 0;
this.bottom_new         = 0;
this.wpBottomBorder_old = 0;
this.wpBottomBorder_new = 0;
this.wpTopBorder_old    = 0;
this.wpTopBorder_new    = 0;
this.wpScrollPos_old    = 0;
this.wpScrollPos_new    = 0;
this.prevHeight         = 0;
this.permsWithAnon      = 0;
this.fixedHeight        = 0;
this.fixedWidth         = 0;
this.widthChange        = true;
this.setWidth = function() {
if(this.widthChange){
if(this.fixedWidth) {
//TODO
//$(this.sticky).css("overflow-x","hidden")
//$(this.sticky).width($(this.sticky).closest("[id^=WebPartWPQ][style*=width]").width() - 18).children().each(function (j) {
// $(this.header).css("min-width",$(this.header).children('*:nth-child(' + (j+1) + ')').width())
//});
} else {
this.sticky.width(this.header.width());
for(var k=0, childrenLength = this.sticky.children().length; k<childrenLength; k++){
this.sticky.children().eq(k).width( this.header.children().eq(k).width() ).css("max-width","");
}
}
this.widthChange = false;
}
};
this.setLeftOffset = function() {
var parent = this.webpart.length != 0 ? this.webpart : this.dphm;
this.sticky.css("left",(parent.offset().left + parseInt(parent.css("padding-left")) - 2) + "px");
};
this.setTopPosition = function() {
if( !this.fixedHeight ){
this.sticky.css("top", (this.s4.offset().top + 2));
} else {
this.sticky.css("top",this.webpart.offset().top + "px")
if(this.sticky.attr('data-hidden', false) && this.sticky.offset().top < (this.s4.offset().top + 2)){
this.sticky.css("top", (this.s4.offset().top + 2));
}
}
};
this.update = function(eventType) {
if(this.sticky.attr('data-hidden', false)){
this.setLeftOffset();
this.setTopPosition();
}
if(eventType == "scrollList"){
this.wpScrollPos_old = this.wpScrollPos_new
this.wpScrollPos_new = this.webpart.scrollTop()

if(this.wpScrollPos_old <= this.prevHeight && this.wpScrollPos_new >= this.prevHeight ){
this.contentBox = this.list.find(".ms-core-menu-box")
this.contentBox.appendTo(this.sticky.find("th").eq(this.contentBox.closest("th").index()))
this.setWidth()
this.sticky.fadeIn().addClass("typeA");

} else if(this.wpScrollPos_old >= this.prevHeight && this.wpScrollPos_new <= this.prevHeight ) {
if(!this.sticky.hasClass("typeB")){
this.sticky.fadeOut().removeClass("typeA");
} else {
this.contentBox = this.sticky.find(".ms-core-menu-box")
this.contentBox.appendTo(this.header.find("th").eq(this.contentBox.closest("th").index())).css({"top":"auto","left":"auto"})
this.sticky.removeClass("typeA")
}
}
} else {
this.top_old = this.top_new;
this.top_new = this.header.offset().top - this.s4.offset().top;

this.bottom_old = this.bottom_new;
this.bottom_new = this.top_new - 30 + this.list.height();

if(this.fixedHeight) {
this.wpTopBorder_old = this.wpTopBorder_new;
this.wpTopBorder_new = this.webpart.parent().offset().top - this.s4.offset().top;
this.wpBottomBorder_old = this.wpBottomBorder_new
this.wpBottomBorder_new = this.webpart.parent().offset().top + parseInt(this.webpart.css("height")) - this.s4.offset().top


//fix for the permission this.when anonymous access is activated
this.bottom_new = this.permsWithAnon ? this.top_new - 30 + this.dphm.height() : this.bottom_new

this.bottom_old         = !this.bottom_old         ? this.bottom_new         : this.bottom_old;
this.top_old            = !this.top_old            ? this.top_new            : this.top_old;
this.wpBottomBorder_old = !this.wpBottomBorder_old ? this.wpBottomBorder_new : this.wpBottomBorder_old;
this.wpTopBorder_old    = !this.wpTopBorder_old    ? this.wpTopBorder_new    : this.wpTopBorder_old;

if (this.top_old >= 0 && this.top_new <= 0 || this.bottom_old <= 0 && this.bottom_new >= 0 || this.fixedHeight && ( this.wpBottomBorder_old <= 0 && this.wpBottomBorder_new >= 0 || this.wpTopBorder_old >= 0 && this.wpTopBorder_new <= 0 ) || ( this.top_old == this.top_new && this.bottom_old == this.bottom_new && this.top_old < 0 && this.bottom_old > 0 )) {
this.contentBox = this.list.find(".ms-core-menu-box")
if(this.contentBox){
this.contentBox.appendTo(this.sticky.find("th").eq(this.contentBox.closest("th").index()))
}
this.setWidth()
this.sticky.fadeIn().addClass("typeB")

} else if (this.top_old <= 0 && this.top_new >= 0 || this.bottom_old >= 0 && this.bottom_new <= 0 || this.fixedHeight && ( this.wpBottomBorder_old >= 0 && this.wpBottomBorder_new <= 0 || this.wpTopBorder_old <= 0 && this.wpTopBorder_new >= 0 )){
this.contentBox = this.sticky.find(".ms-core-menu-box")
this.contentBox.appendTo(this.header.find("th").eq(this.contentBox.closest("th").index())).css({"top":"auto","left":"auto"})
if(!this.sticky.hasClass("typeA")){
this.sticky.fadeOut().removeClass("typeB");

if(this.sticky.hasClass("typeA")){
if(this.wpBottomBorder_new <= 0){
this.sticky.removeClass("typeB").fadeOut();
} else {
this.sticky.removeClass("typeB")
}
}
}
}
}
}

(function (){
var wpq = $("#DeltaPlaceHolderMain [id^=MSOZoneCell_WebPartWPQ]:visible");
if (wpq.length === 1) {
function ShowContextRibbonSections() {
SP.Ribbon.WebPartComponent.registerWithPageManager({editable: true, isEditMode: false, allowWebPartAdder: false});
var wpcomp = SP.Ribbon.WebPartComponent.get_instance();
if (wpcomp) {
wpcomp.selectWebPart(document.getElementById(wpq.attr('id')), true);
}
}

ExecuteOrDelayUntilScriptLoaded(ShowContextRibbonSections, "sp.ribbon.js");
var DeselectAllWPItems_old = DeselectAllWPItems;
DeselectAllWPItems = function () {
DeselectAllWPItems_old();
setTimeout(function () { ShowContextRibbonSections(); }, 25);
};
}

var RibbonContainer = $("#RibbonContainer")
var ribbonHeight = RibbonContainer.height();
g_workspaceResizedHandlers.push(function () {
setTimeout(function () {
var newRibbonHeight = RibbonContainer.height();
if (ribbonHeight !== newRibbonHeight) {
findListsOnPage(false);
ribbonHeight = newRibbonHeight;
}
}, 500);
});

if (jQuery.inArray("spgantt.js", g_spPreFetchKeys) > -1) {
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
setTimeout(function () { findListsOnPage(false); }, 500);
}, "spgantt.js");
} else {
findListsOnPage(false);
}

$(window).bind('hashchange.stickyHeaders', function () {
findListsOnPage(true);
});
})()

function findListsOnPage(hashchange) {
window['listContainer'] = {"lists":[]}

var quickEdit = false;

$("tr:has(>th[class^='ms-vh']):not(.sticky):visible, .ms-listviewgrid").closest("table").each(function(){
if($(this).find("tbody > tr").length > 1){
listContainer.lists.push(new List());
listContainer.lists[listContainer.lists.length - 1].list = $(this);
if($(this).hasClass('.ms-listviewgrid')){
quickEdit = true;
}
}
})

if (quickEdit) {
SP.GanttControl.WaitForGanttCreation(function () {
setTimeout(function () {
initializeStickyHeaders(listContainer,hashchange);
}, 1000);
return;
});
} else {
setTimeout(function(){initializeStickyHeaders(listContainer,hashchange);},0)

}
}

function initializeStickyHeaders(container,hashchange) {
$(window).unbind('resize.stickyHeaders');
$(window).bind ('resize.stickyHeaders', function () { $(container.lists).each(function(){this.update("resize")}) });

$('#s4-workspace').unbind('scroll.stickyHeaders');
$('#s4-workspace').bind('scroll.stickyHeaders', function () { $(container.lists).each(function(){this.update("scroll")}) });

$(container.lists).each(function(){
this.webpart        = this.list.closest("[id^=WebPartWPQ]")
this.header         = this.list.find("tr:has(>th):not(.sticky):visible")
this.dphm           = this.list.closest("#DeltaPlaceHolderMain");
this.s4             = $("#s4-workspace")
this.permsWithAnon  = this.list.closest("div[id$='rptrAnony__div']").length;
this.fixedHeight    = this.list.closest("[id^=WebPartWPQ][style*=height]").length;
this.fixedWidth     = this.list.closest("[id^=WebPartWPQ][style*=width]").length;

var prevElem = this.header.closest("table").prevAll()
for(var i=0, prevElemLength = prevElem.length;i<prevElemLength;i++){
this.prevHeight = this.prevHeight + $(prevElem[i]).outerHeight()
}

if(this.fixedHeight || this.fixedWidth){
this.webpart.bind("scroll",{elem:this}, function(event){
event.data.elem.update("scrollList")
})
}

if (!this.webpart.find(".sticky").length) {
this.list.before('<div class="sticky-anchor"><span></span></div>');
this.sticky = this.header.clone(true, true).addClass("sticky").attr('style', "position: fixed; border: 1px solid grey; background-color: white; box-shadow: 0 0 6px -2px black; display: none;").insertAfter(this.list);
this.sticky.find("#users_imn_header").attr("src", "/_layouts/15/images/imnhdr.gif")
this.sticky.find(".ms-selectall-span img").on("click",{header:this.header},function (event) {
var span = event.data.header.find(".ms-selectall-span")
span[0].checked = span[0].checked ? false : true;
ToggleAllItems2(span[0], span.attr("id").substr(17), span[0].checked)
});
} else {
if(hashchange){
this.sticky = this.list.closest("div").find(".sticky");
/*
var childrenLength = $(this.header).children().length
for(k=0; k<childrenLength; k++){
if(!this.header.children().eq(k).find(".ms-filter-iconouter").attr('data-hidden')){
this.header.children().eq(k).find(".ms-filter-iconouter").css("display","inline-block")
} else {
this.header.children().eq(k).find(".ms-filter-iconouter").css("display","none")
}
if(!this.header.children().eq(k).find(".ms-sortarrowdown-iconouter").attr('data-hidden')){
this.header.children().eq(k).find(".ms-sortarrowdown-iconouter").css("display","inline-block")
} else {
this.header.children().eq(k).find(".ms-sortarrowdown-iconouter").css("display","none")
}
}
*/
} else {
this.sticky = this.list.closest("div").find(".sticky");
}
}

//update stickies when grouped views are expanded or collapsed
this.list.children("tbody[id^='titl']").find(".ms-gb a").bind('click.stickyHeaders',{elem:this},function (event) {
var elem = event.data.elem
elem.widthChange = true
interval = setInterval(function(){
if($("#tbod" + $(event.target).closest("tbody").attr("id").substr(4) + "_").attr("isloaded") == "true"){
elem.update("expandCollapse");
clearInterval(interval);
}  
},1)
});
});
$(container.lists).each(function(){this.update("standard")})
}

(function () {
$("<div/>", {html: '&shy;<style>.sticky .ms-core-menu-box {top: auto !important; left: auto !important;}</style>'}).appendTo("body");
})();
}

Thursday, March 31, 2016

How to Turn on Line Numbers In Visual Studio

In this below script, Turn on Line Numbers In Visual Studio

Turn on Line Numbers In Visual Studio

Line numbers are not on by default. 

 

Tools -> Options -> Text Editor -> All Languages -> General -> Display and check Line numbers:

Wednesday, March 30, 2016

Configuring Auditing in SharePoint 2010

In this below script, Configuring Auditing in SharePoint 2010

Configuring Auditing in SharePoint 2010

  • Go to site Settings
  • select Site collection Administration
  • Choose Audit log Reports
  • Delete Deletion
  • Please the save location 
  • I'll save this report to the Shared Documents Library, however in production this is where I create a document library with unique permissions so only Site Collection Administrators can see the contents. I click on Browse.
  • View Report 
  • You ll get excel report format

Tuesday, March 29, 2016

How to get current master page and change it on the Site using javascript

 GET request

/_api/Web?$select=CustomMasterUrl,MasterUrl

function MastePageChange() {
    var clientcontext;
    var cweb;
    var customMasterURL = '/_catalogs/masterpage/NewMasterPage.master';
    clientcontext = new SP.ClientContext.get_current();
    cweb = clientcontext.get_web();
    cweb.set_customMasterUrl(masterPageUrl);
    cweb.set_masterUrl(masterPageUrl);
    cweb.update();
    clientcontext.executeQueryAsync(function() {
        alert("Master Page has been changed successfully \n" + customMasterURL);
    }, function(sender, args) {
        alert("Error: " + args.get_message());
    });
}

MastePageChange();

How to set SharePoint list view 'Item Limit' with the option programmatically

Limit the total number of items returned to the specified amount



ClientContext clientContext = new ClientContext("http://hercules");
          clientContext.Credentials = new NetworkCredential("Peakfinder", "password@1");
          string listName = "Employess", viewName = "All Items";          
          bool paged = true;      
          List list = clientContext.Web.Lists.GetByTitle(listName);
          View view = list.Views.GetByTitle(viewName);
          view.Paged = paged;
          view.Update();
          clientContext.ExecuteQuery();

How to change SharePoint list field color using jquery code base on value?

In this below script, hange SharePoint list field color using jquery code

change SharePoint list field color
 $("table.ms-listviewtable > tbody > tr > td:nth-child(columnNumber) > div").filter(function() {
        ( parseInt( $(this).text() ) > 59 ) ? $(this).css("background-color", "#00FF66") : null  
    });

Calculating date value based on a column value Using SharePoint Workflow

In this below script, oCalculating date value based on a column value SP

Calculating date value based on a column value
=IF(A<1/3/2016,A+100,A+50)
Set the column to return date.


How to open a calendar item in a modal dialog?

In this below script, open a calendar item in a modal dialog

open a calendar item in a modal dialog In SharePoint
function openDialog(pageUrl) {
  var options = {
      title : "calender",
      width : 500,
      height : 400,
      url : pageUrl
  };

  SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
}

$('.ms-acal-month').ready(function () {
   setTimeout(function() {
       $('a[href*="DispForm.aspx"]').each(function() {
           $(this).attr('onclick', 'openDialog("' +  $(this).attr('href') + '")');
           $(this).attr('href','javascript:void(0)');
       });
   }, 1000);
});

Friday, March 25, 2016

Print Angular JS

http://jsfiddle.net/BlinkSun/tcVhN/235/

a factory that you can call and a directive, two way: by htmls from variable scope or by extern template, if the template have a css linked in, it must print de style too !

Thursday, March 24, 2016

Error in "Pause for" Action - Nintex Workflows

In this below script, "Pause for" Action - Nintex Workflow

Pause for Action - Nintex Workflow In SharePoint

·        Email triggered says Workflow Terminated unexpectedly for item.

·        Error message logged was “Error POC 1” failed to run.

·        I got below information when I discussed this issue with nintex support

 

SharePoint dictates which Workflow Timer Service will run the workflow - so this could occur on any server on which the "Microsoft SharePoint Foundation Workflow Timer Service" is enabled.

 

When Nintex is deployed it install’s some DLL’s required for workflows on the WFE’s where

 Microsoft SharePoint Foundation Web Application service is enabled.

So when Workflow Timer Service attempts to run a workflow where Microsoft SharePoint Foundation Web Application is disabled it throws error.

 

Solution:

·        Disable Workflow Timer Service to all the WFE’s where Microsoft SharePoint Foundation Web Application service is disabled.

·        Or Enable Microsoft SharePoint Foundation Web Application Service on all WFE’s.

 

1)               Related Issues: So due to the above reasons not only “Pause for” action throws error but some below mentioned actions also throws error.

 

2)               Change State: Since while changing state in a State Machine Workflow, a hidden delay is involved. So in that case also, it may throw error in case after delay it got caught by WFE where Microsoft SharePoint Foundation Web Service is disabled but Workflow Timer Service is enabled.

 

3)               Pause Until: This action also throws error while in a paused state until some date is passed.

 

4)               Assign Flexi Task: Due to the delay involved before sending reminders, it may error out.

 

Similarly Task Reminder Action, Request Data, or any other action where delay is involved may throw errors if occupied by wrongly configured WFE’s.

 

Tuesday, March 22, 2016

@media print remove url href values when printing in Chrome

In this below script, remove url href values when printing in Chrome using javascript

remove url href values when printing in Chrome using javascript In SharePoint
your printed webpages you will need to use your CSS styles to override it.

 Customize the print CSS, and finding that it prints links out with the href value as well as the link.


}@media print {
  a[href]:after {
    content: none !important;
  }
}

STSNavigate in SharePoint

In this below script,STSNavigate in SharePoint

STSNavigate in SharePoint
In this article menu item uses createNewDocumentWithRedirect function in core.js file

<asp:content contentplaceholderid="PlaceHolderAdditionalPageHead" runat="server">
       <SharePoint:RssLink runat="server"/>
      
       <Script>
       function STSNavigate(Url){
              window.open(STSPageUrlValidation(Url),"_blank");
       }
       </Script>
</asp:content>

STSNavigate in turn calls STSPageUrlvalidation: 
function STSPageUrlValidation(url)
{ULSxSy:;
    return PageUrlValidation(url);
}
It then calls PageUrlValidation - THIS IS THE KEY PART:
function PageUrlValidation(url)
{ULSxSy:;
    if ((url.substr(0, 4)=="http") ||
        (url.substr(0, 1)=="/")     ||
        (url.indexOf(":")==-1))
    {
        return url;
    }
    else
    {
        var L_InvalidPageUrl_Text="Invalid page URL: ";
        alert(L_InvalidPageUrl_Text);
        return "";
    }
}

How to add custom context menu list in SharePoint 2013?

In this below script,add custom context menu list in javascript

add custom context menu list In SharePoint

In this article ,We have create custom Context menu in SharePoint custom list ,

for single list(i.e. List Library) I have created a custom action for the content type.

 

1.Open SharePoint Designer.

2. Open SharePoint site

3. Go to that specific page and edit that page

4. Click on "Custom Action" in SharePoint  Designer and open "List item Menu"

 



5.Popup will be appear “Create Custom Action”.
6.Click Ok

 

 

7.Finally Created Custom Context menu.

 

 

How to Print css in SharePoint 2013

In this below script,Print css in javascript

Print css

I got is adding media="print" property to the CSS references.

/* This CSS removes the header, navigation and other action elements from the print preview  */

1. 

<style>
     @media print{
     #suiteBar{display:none;}
          #titleAreaBox{display:none;}
          #pageTitle{display:none;}
#btnPrint{display:none;}

     }
     </style>


/* Insert your print stylsheet here */

}

2. 

 /* Reference master page  */ 

<link rel="stylesheet" media="print" href="print.css" type="text/css"/>