What is the method for styling a PDF page using CSS attributes for printing?

function displayAndPrint() {
   var divContents = document.getElementById("box2text").innerHTML;
   var popup = window.open('', '', 'height=500, width=500');
   popup.document.write('<html>');
   popup.document.write('<body > <h1>Div contents are <br>');
   popup.document.write(divContents);
   popup.document.write('</body></html>');
   popup.document.close();
   popup.print();
}

This code snippet includes a function that retrieves the content of a div and opens it in a new window for printing.

 <div class="box2" id="box2">
    <textarea name="box2text" id="box2text" cols="30" rows="10"></textarea>
 </div>
 <div class="button">
    <button onclick="displayAndPrint()">DISPLAY AND PRINT</button>
 </div>

Please note that this script only displays text, not CSS properties like color.

Answer №1

To create a custom printable page with your CSS styles, you can start by making a new HTML file named "print-page.html". Inside this file, link your CSS stylesheet. Then, you can use the following JavaScript function to open this custom page, insert your content, and print it:

function generatePrintablePage() {
    var content = document.getElementById("content").innerHTML;
    const printWindow = window.open('print-page.html', '_blank', `width=${window.innerWidth},height=${window.innerHeight}`);
    printWindow.onload = function(){
        printWindow.document.body.innerHTML = content;
        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

Working with time durations in Moment.js to manipulate datetime

How can I properly combine the variable secondsToMinutes with the startdate? The value of secondsToMinutes is "3:20" and the startDate is "2:00 PM". The desired endDate should be "2:03:20 PM". Despite my efforts, I keep encountering errors every time I at ...

Should I generate a new object or utilize an already existing one?

When working with JavaScript and needing to replace existing data with new data, what is considered a good or "correct" practice? I currently utilize Dojo's Memory and dGrid to showcase my data. The information is refreshed each time the user clicks ...

Simulating an ES6 module that returns a factory function for moment.js

Disclaimer: I'm a beginner with Jest so please bear with me. I'm currently working on testing a Vue2.js filter named DateFilter using Jest. This filter simply formats a date that is passed to it. DateFilter.js import Vue from 'vue'; ...

set a value to a global array within a function

After writing the following javascript code: <script language="javascript" type="text/javascript"> var name = new Array(); var i = 0; function doSomething() { name[i] = "a"; alert(name[i]); i++; } < ...

Tips for incorporating external AMD modules with Angular2 using WebPack

In my current project using Angular2, TypeScript, and WebPack, I am looking to incorporate the Esri ArcGIS JavaScript API. The API can be accessed from the following URL: By importing Map from 'esri/Map';, I aim to import the corresponding modul ...

Embed a subcomponent within another component triggered by an onClick event in ReactJS

Watch this quick demo to see my project in action. So, here's the deal - I have a menu with different options, and when "Tickers" is selected, I want it to display the Tabs component. However, if any other menu option is chosen, I don't want the ...

The Angular Ngx Charts display refuses to fill up despite attempts to populate

Currently, I am facing an issue with populating my charts using real data from an API. Here is the HTML code snippet in question: <ngx-charts-bar-vertical [results]="popularCountriesData" [legend]="false" [showXAxisLabel] ...

Error: Trying to access the 'name' property of an undefined value is not possible

The issue arises with the undefined value of currentPackage. render() { const { hasAccounts, asideClassesFromConfig, disableScroll, htmlClassService, currentPackage, user, } = this.props; const isActive = checkStatus(user?.status); const packageLogo = curr ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...

Display an image in Vue.js

I'm having some trouble displaying images in my laravel/Vue 2.0 project and could use some assistance. Here's how I upload the image using the Laravel controller: //Save image to disk if($request->hasFile('image')) { ...

Enter a number into a text box and increase the value in several text boxes created with jQuery in PHP

I need to dynamically populate textboxes with student information from a database after inputting a value, for example 100, and clicking on the 'Add' button. The challenge is to incrementally assign values to each textbox based on the initial num ...

Transmit the identifier of the span tag to the URL seamlessly without the need to refresh

<div id="unique50">Greetings</div> Transfer the code 50 to the designated link by clicking on the specific div element without requiring a page reload ...

Issue with arranging blocks in a horizontal line in Opera

I am currently experiencing an issue with a wide page that contains an information block and numerous images positioned to the right. The layout is designed to be used with a horizontal scrollbar. While this setup works perfectly in Firefox, Safari, Chrom ...

How should one go about creating an npm package out of a vuejs component and testing it locally?

Initially, I created a vuejs project as a test container using vue-cli. Next, I developed an npm package named "vue-npm-example" from a Vuejs component in my local environment and then imported it into the aforementioned testing project. Within the packag ...

Having trouble with Bootstrap 5 Carousel not sliding to the next image? Learn how to fix this issue by upgrading from Bootstrap 4 to Bootstrap 5

Having downloaded both the compiled css and js and the source files of the bootstrap 5 library, I've experimented with both. While the css seems to load fine, I'm struggling to get this example to function. It's from a bootstrap 4 related po ...

Navigating through functions and saving outcomes

I need help creating a function that groups JSON elements based on a specific criteria, but I am having trouble with my loop. The goal is to create groups of 12 bottles and return a single JSON list. For example, in this case, the function should extract ...

Error in Angular: IE8 is expecting an identifier

My application runs smoothly on most browsers, but I encounter an issue with IE8 where an Expected Identifier error occurs. $scope.delete = function (index) { $scope.recipelists.splice(index, 1); localStorage.setItem('markedRecipes ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

Exploring ASP.NET Core 3.0: Animated Loading Icons

My latest project involves integrating a loading GIF, and I'm using ASP.NET Core 3.0 with Razor Pages for this task. It's been challenging for me as a newcomer to incorporate some Javascript or Ajax code to achieve the desired functionality. Upon ...

What is the best way to save a JSON stream to a file in Node.js?

I am facing an issue with writing a complete JSON object to a file as it is received. Currently, I am using const file = fs.createWriteStream('./example.file'); var inputStream = JSON.parse(generatedData); fs.write(inputStream+"\n"); The d ...