how to print in javascript

How to Print in JavaScript

If you want to print something in JavaScript, there are a few ways to do it.

Using window.print()

The easiest way to print a webpage is to use the built-in function window.print(). You simply call this function when the user clicks a button or link, and it will print the current page.


function printPage() {
  window.print();
}

Creating a Print-Friendly CSS

If you want more control over the printing process, you can create a print-friendly CSS file that will be applied only when the user prints the page. This allows you to remove unnecessary elements, adjust the layout, and change the font size and color for better readability on paper.


@media print {
  /* your print-friendly styles here */
}

To apply the print-friendly CSS, you need to include it in your HTML file:


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

Generating a PDF

If you want to generate a PDF file instead of printing directly from the browser, you can use a JavaScript library like jsPDF or pdfMake. These libraries allow you to create a PDF document from scratch or from an HTML template, and customize its content and layout.


var doc = new jsPDF();
doc.text('Hello World!', 10, 10);
doc.save('hello.pdf');

This code creates a new PDF document, adds some text to it, and saves it as a file named "hello.pdf".

These are just a few ways to print in JavaScript. Depending on your use case, you may need to use a different approach or combine multiple techniques. Always test your code on different browsers and devices to ensure it works as intended.

hljs.highlightAll();

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe