Methods for concealing the title and date when printing web content using JavaScript

When utilizing the window.print method to print out a specific screen, I encountered an issue. I need to hide the date in the top left corner of the image as well as the title (not the big heading) which has been intentionally blurred.

I've come across suggestions online that recommend using @pages { margin: 0 }. However, I'm unsure of how to implement this within the context of window.print();

My attempts at using setAttribute() have not been successful, leading me to believe that I may have made an error somewhere.

https://i.stack.imgur.com/3J063.png

      const element = document.getElementById("qr-code").innerHTML;
      var printWindow = window.open('', '', 'height=800,width=800');
      printWindow.document.write(element);
      printWindow.document.close();
      const title = printWindow.document.title = "some title here";
      const heading = printWindow.document.createElement('h1');
      const text = printWindow.document.createTextNode(title);
      heading.appendChild(text);
      heading.setAttribute('style', 'order: -1; margin-bottom: 50px;');
      printWindow.document.body.appendChild(heading);
      printWindow.document.body.setAttribute('style', 'display: grid; width: 100%; justify-items: center; margin: 0;');
      printWindow.print();

Answer №1

By referencing the information found at , you have the ability to incorporate this css code:

@page { size: auto;  margin: 0mm;}

onto the window, effectively concealing the date and title (as they are located in the margin). To implement this css, you can generate a style element and add it to the window, similar to how you include the heading.

const element = document.getElementById("qr-code").innerHTML;
var printWindow = window.open('', '', 'height=800,width:800');
printWindow.document.write(element);
printWindow.document.close();
const title = printWindow.document.title = "some title here";
const heading = printWindow.document.createElement('h1');
const text = printWindow.document.createTextNode(title);
heading.appendChild(text);

// Below is the style that can be incorporated to hide the date and title during printing.
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '@page { size:auto; margin:0mm;}';

heading.setAttribute('style', 'order:-1;margin-bottom:50px;');
printWindow.document.body.appendChild(heading);

// Attach the style to the body of the window
printWindow.document.body.appendChild(style);

printWindow.document.body.setAttribute('style','display:grid;width:100%;justify-items:center;margin:0;');
printWindow.print();

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

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

Hiding elements in dark mode using `hidden` or `block` in Tailwind will not override its own hidden selector

To switch between dark and light mode for these two images, the dark:block selector does not override the hidden class. <div className="ml-5 content-center"> <img className="hidden dark:block h-6 w-auto my-1" src="/stati ...

Error loading content for webpack://SwaggerUIBundle/src/core/system.js in Swagger UI

When trying to utilize Swagger UI for documenting a Laravel project using the URL http://localhost:8014/api/documentation, I came across an error displayed in the browser console: Error: Unable to destructure property 'type' of 'u' as i ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...

When attempting to render HTML containing multiple CSS classes within a JSON request parameter, the styles are not being applied as expected

In my API, I'm dealing with a JSON request parameter that includes an HTML string. This HTML string references CSS styles from a separate .css file. However, when an HTML element has two CSS classes assigned to it, neither of the classes' styles ...

Error: The fetch request was unsuccessful [NextJS API]

I keep encountering an error - TypeError: fetch failed after waiting for 300 seconds while requesting an optimization server that requires a response time longer than 300 seconds. The request is being sent from the provided API in NextJS. Is there a way ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

Maintain the state of various panels on page load with the Bootstrap Accordion feature

I have implemented a Bootstrap accordion on my form page which allows users to open multiple panels simultaneously. Upon submitting the form, I want to preserve the state of any open Bootstrap accordion panels. To achieve this, I utilized code from stack ...

Change the attribute to read-only upon modification of the dropdown value

I have a dropdown menu with four options. My goal is to make the "number" input field readonly if the user selects either "option3" or "option4" from the dropdown. <select id="dropdown"> <option value="option1">option1</option> ...

Displaying content conditionally in Vue.js

I need assistance with displaying product lists for different companies in cards based on the selected section. Currently, the products are being displayed for all listed companies because the markup is the same across the page. Below is a snippet of my co ...

Issue: Child Pages not found in Nuxt RoutingDescription: When navigating

Currently working on a Nuxt application that utilizes the WordPress REST API to fetch content. While my other routes are functioning correctly, I am facing challenges with nested pages. The structure I have implemented in my Nuxt app is as follows: pages ...

Guide on passing a variable from AJAX response to a JavaScript function when a user clicks

I need to send the value of a variable as a parameter to a javascript function when clicking on a link. The value is obtained from an AJAX response. However, I am encountering an error in the console stating that 'test' is not defined. var test ...

Angular directive has issues with $compile functionality

This Angular directive automatically appends a new HTML item to the page every time my model changes: app.directive('helloWorld', function($compile) { return { restrict: 'AE', replace: true, scope:{ ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

By utilizing a combination of JavaScript and jQuery, we can dynamically fill interconnected select boxes with data from an

After finding solutions to this particular query, I successfully managed to populate a select box based on the selection made in another select box. (You can see my answer here) This was achieved by retrieving data from an array structure that was generate ...

A solid gauge undergoes a refreshing process once it obtains new data in the form of a point

I've been running into some issues with the solid gauge component while using the highcharts-vue wrapper. Whenever it receives new data, it restarts the animation from 0. You can see an example of this behavior in the sandbox link provided here: https ...

Using AngularJS for AJAX operations with dynamic PHP variables

I have an AngularJS code that is looping through an AJAX JSON response like this: <div ng-repeat="post in posts"> {{post.title}} {{post.url}} </div> It's working fine. How can I pass a PHP variable based on the JSON? Let's assume t ...

The error occurred in async JavaScript parallel code because the task is not recognized as a function

I am attempting to upload an image and update the image URL in the database collection using the code provided below. Controller.prototype.handle = function (req, res, next) { var id = req.params.id, controller = req.params.controller, optio ...

Dealing with error handling in NUXT using asyncData and Vue actions

The URL I am trying to access is http://mywebsite.com/[category that doesn't exist]. Despite the code snippet provided below, I am unable to reach the catch block in asyncData. async asyncData({ params, store }) { try { await store.dispatch(&ap ...