Ways to display a specific section on an HTML page using AngularJS

Main page content

<div class="row">
    <div class="col-md-3">
        link 1
        link 2
        link 3
        .
        .
        .
    </div>
</div>

<div class="col-md-9">
    <div ng-view></div>
</div>

Clicking a link on the main page will load the child page in ng-view.

<table class='table table-bordered'>
    <tr>
        <td>
            This is the screen view.
            When a user clicks a link on the parent page, specific content is loaded here.
        </td>
    </tr>
</table>    


<button type="button" class="btn btn-success btn-md" ng-click="myprint()" >
    <span class="glyphicon glyphicon-print"></span> Print
</button>


<div id ="printsection">
    <table style="width:80mm;">
        <tr style="text-align: center;">
            <td>This is the print view contents. 
                These contents will be sent to the printer when printing.
            </td>
        </tr>
    </table>
</div>

The child page consists of two sections - screen view and print section.

Upon clicking the print button, the content from the print section will be sent to the printer.

CSS rules defined for media print:

print.css

body {
    background-color: white;
    color: black;
    font-family: Times,"Times New Roman",Garamond, serif;
}
body * {
    visibility: hidden;
}
#printsection * {
    visibility: visible;
}
#printsection {
    position: absolute;
    left: 0;
    top: 0;
}

The issue is that upon clicking the print button, all contents, including the print section, are being hidden.

Please note that an 80mm width POS printer is being used, hence the width set to 80mm in the print section.

Answer №1

One way to easily replace the content of a page and initiate printing is by using a simple function.

<button onclick="printElement('my-section')">Print</button>

function printElement(id) {
    var printHtml = document.getElementById(id).outerHTML;
    var currentPage = document.body.innerHTML;
    var elementPage = '<html><head><title></title></head><body>' + printHtml + '</body>';
    
    // Temporarily change the body content
    document.body.innerHTML = elementPage;
    
    // Print the modified content
    window.print();
    
    // Revert back to the original content
    document.body.innerHTML = currentPage;
}

When clicking the print button, ensure that you are also changing the visibility property of "printsection" to visible.

Below are some CSS rules for managing visibility:

display:none, display:block.

Answer №2

The visibility of the printSection and its parent elements was not set to visible. To rectify this, ensure that you apply the following CSS:

#printSection{
    visibility: visible;
}

Remember to also check and make all parent elements visible if they were hidden using body *{ ... }

Answer №3

If you want to customize the printing style of your webpage, consider using CSS media rules specifically for printing purposes: CSS media rules - @media print. Here is an example:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>

        @media all {
            /* Define styles applicable to all devices */
        }

        @media screen {
            /* Styles specific to screen display */
        }

        @media only print {
            /* Styles intended for printed material or print preview mode */
            main {
                display: none;
            }
        }
    </style>
</head>
<body>
    <main>
        <button onclick="window.print()">Print</button>
        <h1>hello</h1>
        <p>Some paragraph</p>
    </main>

    <div id="print-section">
        <h2>subtitle</h2>
        <table border="1" width="50%">
            <tbody>
            <tr>
                <td>A</td>
                <td>B</td>
            </tr>
            <tr>
                <td>C</td>
                <td>D</td>
            </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

When a user initiates printing using CTRL + P or the print button with window.print(), only the content outside of the main tag will be included in the printout, following this best practice approach.

According to the documentation:
Syntax:

@media <media-query> {
  /* Define media-specific styles */
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The NodeJs and Express API, integrated with Ejs files, encounters a crash when attempting to retrieve data from the database on the second attempt

I've been assigned the task of developing an API that retrieves data from a database and presents it on the frontend. This is my first time working with APIs, and I've encountered some challenges along the way. The database I'm using is call ...

Preventing Canvas Image Disappearance with JavaScript's onload Event

My current issue involves adding an Image to my webpage. However, every time I hit the refresh button, the image disappears. After researching on Stack Overflow, it was suggested to include window.onload=yourDrawFunction() in the code. Despite following th ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

Swap out the hyperlink text for a dropdown menu when clicked and then revert back

Is there a way to dynamically switch between a label/text and a Kendo Combobox in a div using JavaScript when clicking on the text? The desired functionality includes: Clicking on the text displays the combobox, clicking away from it hides the combobox a ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

What are some tips for getting media queries to function properly?

I need help with my homepage banner image as I am trying to make it responsive by adding media queries. The goal is for the image to adapt to 3 different sizes based on the screen being used, but currently only the medium-sized version appears. Could someo ...

Adjusting image size to accommodate responsive column cell using CSS

I've been working on optimizing my mobile website using a responsive column layout. The challenge I'm facing is getting the images within each column to stretch to 100% width while automatically adjusting their height. I experimented with settin ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

Background Image Division (Twitter Bootstrap)

I am facing a challenge while creating a module with a span8 width and varying height. The div contains an image that dictates its height, with text overlaid on the image. My issue lies in preventing part of the image from getting cropped when Bootstrap re ...

Is my Discord.js bot malfunctioning due to incorrect indentation, despite the absence of errors?

After spending a considerable amount of time developing this bot, I encountered an issue following an update that introduced 'limitedquests'. Previously, the bot worked flawlessly but now, certain functions are not functioning as intended without ...

Stop HTML audio playback upon clicking on a specific element

I'm looking to add background music to my website with a twist - a music video that pops up when the play button is clicked. But, I need help figuring out how to pause the background music once the user hits play. Play Button HTML - The play button t ...

Tips for safeguarding your passwords across diverse authentication methods

Exploring a new project idea, I am interested in supporting the SASL Mechanisms for authentication, particularly PLAIN and DIGEST-MD5. I am curious about how to securely store users' passwords when implementing these two authentication methods. When ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

Troubleshooting Highcharts container selection problem on Nexus 7 running version 4.2.1

Having a problem with Highcharts on my Nexus 7. When I touch the chart, the entire thing gets selected with a blue overlay, but this doesn't happen on other devices like the Nexus 4. Even when I try accessing demos from Highcharts website, the issue ...

Uploading and cropping multiple images in AngularJS

Currently in search for quality Angularjs code that offers support for multiple image uploads along with cropping capabilities. After extensive searching, I have come across either solutions that excel at multiple image uploading or ones that specialize i ...

Traverse through an object in ReactJS

Having trouble iterating over an object in my ReactJS project and facing some content display issues. Check out this fiddle for reference - http://jsfiddle.net/8e039Ltw/ Here's the ReactJS code snippet:- class TodoApp extends React.Component { ...

Whoops! The input buffer seems to be containing an image format that is not supported while attempting to utilize Next JS next-opt

I initially used the default Image Optimization component in my Next JS app, only to realize that the site could only be hosted on Vercel and not on other web hosting platforms. This limitation prompted me to explore the next-optimized-images package, whic ...

CSS Alignment in React with Material UI

Is there a way to align one button to the left while centering the other two? To see an example in Codesandbox, please visit HERE <DialogActions sx={{ justifyContent: "center" }}> <Button>Left</Button> <Button on ...

Enhancing Vue.js functionality with extra information stored in local storage

I've created a To Do List app where you can add tasks using a button. Each new task is added to the list with a checkbox and delete button in front of it. I'm trying to save all the values from the inputs and the checked checkboxes on the page on ...

Repeating X and Y Axis Labels on Highcharts

Highchart is new to me. I recently created a basic chart showing the count of males and females over the past five years. I have included a screenshot for reference. I am wondering if it's possible to remove duplicate labels from both axes? Below is ...