April 26, 2020

How to print a Lightning Component & Hide print button when printing -PART 1

Hello Trailblazers !

In this blog post, we are going to see how to print Lightning Component and how we can hide some elements while printing using standard slds class.

.slds-no-print selector is used to hide a component when printing a page.

Example:
<div class="slds-no-print">hide this div when printing</div>


Step 1 : Create Lightning Component that you want to print

<!-- DocTypeComponent.cmp-->
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<lightning:button class="slds-no-print slds-align_absolute-center slds-m-around_xx-small"><a style="text-decoration: none;" href="{!'/c/PrintComponent.app'}" target="_blank" >Print Preview</a></lightning:button>
    <p class="slds-box slds-text-heading_small">Doctype icons represent a type of file when a preview or image is unavailable. <br /><br />
        <lightning:icon iconName="doctype:audio" alternativeText="Audio file" title="Audio" />
        <lightning:icon iconName="doctype:image" alternativeText="Image file" title="Image" />
        <lightning:icon iconName="doctype:mp4" alternativeText="MP4 file" title="MP4" />
        <lightning:icon iconName="doctype:xml" alternativeText="XML file" title="XML" />
    </p>
</aura:component>

Step 2 : Create Lightning App to call lightning component in it.

<!-- PrintComponent.app-->
<aura:application extends="force:slds" access="global">
    <ltng:require scripts=""  afterScriptsLoaded="{!c.scriptsLoaded}" />
    <aura:attribute name="isLoaded" type="Boolean" default="false"/>
    <aura:if isTrue="{!v.isLoaded}">
        <div class="printDoc">
            <c:DocTypeComponent/>
        </div>
    </aura:if>
</aura:application>

Step 3: Use window.print() inside js function

/* PrintComponentController.js */
({
 scriptsLoaded : function(component, event, helper) {
        component.set("v.isLoaded", true);
        setTimeout(function(){
            window.print();
        }, 2000);
 }
})

Step 4 : Use @media print in css

<!-- PrintComponent.css-->
@media print {
.THIS.printDoc {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}


Resources



2 comments: