Skip to content
the poor coder

how to print in javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

JavaScript

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.

CSS

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

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

HTML

<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.

JavaScript

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();

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC