- Print only the content of a webpage using CSS and JavaScript
- Print an entire page
- Print part of a web page
- Assigning a print area with JavaScript
- Summary
- Related links
- Javascript печать блока с HTML страницы
- Если браузер не видит CSS стили
- Материалы:
- Print a div tag content with Javascript.
- What does the script?
- Print the content of a div element using JavaScript
- Print the content of a div element using JavaScript
- Conclusion
- About the author
- Sharqa Hameed
- Print the Content of a div Element using HTML & JavaScript
- HTML Code:
- HTML Output:
- JavaScript Code:
- Video Output Of Print the Content of a div Element:
- Final Output Of Print the Content of a div Element:
Print only the content of a webpage using CSS and JavaScript
For security reasons, modern browsers do not allow JavaScript access to a user’s printer directly.
But what JavaScript can do is make a request to print the current page, which prompts the user with a print preview.
Table of contents
Print an entire page
Printing couldn’t be much more straightforward: call window.print() or, because it is a method on the global object, just print() :
/* Request to print the current page */ window.print(); // OR: print();
This will request to print the entire page.
Print part of a web page
Printing part of a page is more difficult because window.print() doesn’t accept any arguments that could specify a part of the page to print (e.g. a only).
Luckily, it is possible to specify the appearance of elements when printing using a CSS media query for the print view.
So inside @media print <> , first specify that all elements inside the body should not be displayed in print view using the ‘all’ wildcard ( * ).
Afterwards, set the appearance of the element you want to print and its content to display: block , making it visible.
Now, when window.print() is called, only the visible element will appear in the preview:
Print me.
Assigning a print area with JavaScript
In the above example, the element for printing has the print-area class name assigned to it.
In practice, this may not already be the case in your HTML markup.
But you can assign this name to any element using JavaScript.
To do so, access the classList of an element and call the add() method, passing in the class name to add:
For example, the code below assigns the class name print-area to an element with the ID of the-content :
Print me.
Now, when window.print() is called, the .print-area CSS applies to the with ID the-content , and it (and not the ) is visible in the print view.
Summary
JavaScript can be used to send a job to the printer for user approval. An entire web page can be sent for printing by simply calling the window.print() method.
To print part of a page, use a CSS media query for the print view, specifying that only HTML content you want to print should be displayed in this view.
Related links
Javascript печать блока с HTML страницы
При создании очередного сайта столкнулся с задачей печати HTML-страницы. На странице была информация о проекте (коттеджи) и ее нужно было по клику распечатать. Для решения идеально подходит Javascript. Итак, создаем такую структуру:
Обязательно задаем идентификатор. Содержимое может быть любым. Далее напишем небольшую функцию для печати веб-страницы:
И немного поясню. Эта функция откроет новое popup-окно, вызовет функцию печати. После печати автоматически закроет окно. В новое окно передается содержимое блока print-content. Также вызываем стили CSS, чтобы отформатировать содержимое. И, конечно, надо вызывать функцию. Делаем через Javascript функцию onClick:
Ну вот и все. Просто и с душой.
Если браузер не видит CSS стили
Если браузер по той или иной причине не хочет видить CSS, то можно упростить код, удалив пару строк:
Материалы:
Print a div tag content with Javascript.
This template adds a beautiful html certificate, maybe in a real layout it has a header, or footer, etc, what if I need to print just the certificate?, Well we are going to a add a button to print the certificate:
onclick="printCertificate()" class="fixed z-10 bg-blue-900 text-white bottom-0 right-0 m-10 py-2 px-4 rounded-full shadow-xl hover:text-yellow-600 focus:outline-none">Print
function printCertificate() const printContents = document.getElementById('certificate').innerHTML; const originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; >
What does the script?
It gets the html element with the id «certificate», then it get the original html layout content, then it creates a new one and add the div content to this «new» html, then it prints the new html layout and finally the html becomes the original html layout.
Print the content of a div element using JavaScript
Have you ever encountered a situation where you need to print the content of some specific HTML and save it for future use? For instance, it is required to store the cooking recipes or designing ideas from the respective websites and use this information while working offline. In such scenarios, it is important for you to know how to print the content of any element of HTML.
In this blog, we will learn the procedure for printing the div element’s content with the help of Javascript.
Print the content of a div element using JavaScript
With the help of the below-given example; we will demonstrate the procedure for printing the content of a “div” element. So, the following section comprises the HTML code and its description.
- Firstly, we will use a div element and set its “id” as “divCon” which will help to get its content in JavaScript.
- In the next step, we will set “lightyellow” as the “background-color” of the added “div” element.
- Inside the “div” element, we will now add a heading and a paragraph with “ ” and “ ” respective HTML tags.
< div id = "divCon" style = "background-color: lightyellow;" >
< h2 >Print the content of a div element using JavaScript
< p >
Now we will print the content of a div element using JavaScript in a new window. Press the below button and see the result.