Print Content of Div element by using 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

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.

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 ( * ).

Читайте также:  Python list search by key

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.

Источник

Javascript печать блока с HTML страницы

При создании очередного сайта столкнулся с задачей печати HTML-страницы. На странице была информация о проекте (коттеджи) и ее нужно было по клику распечатать. Для решения идеально подходит Javascript. Итак, создаем такую структуру:

Обязательно задаем идентификатор. Содержимое может быть любым. Далее напишем небольшую функцию для печати веб-страницы:

  

И немного поясню. Эта функция откроет новое popup-окно, вызовет функцию печати. После печати автоматически закроет окно. В новое окно передается содержимое блока print-content. Также вызываем стили CSS, чтобы отформатировать содержимое. И, конечно, надо вызывать функцию. Делаем через Javascript функцию onClick:

Ну вот и все. Просто и с душой.

Если браузер не видит CSS стили

Если браузер по той или иной причине не хочет видить CSS, то можно упростить код, удалив пару строк:

Материалы:

Источник

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.

Источник

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.

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.


Then we will add a button which calls the “printDivContent()” Javascript function on its “Onclick” event:

Javascript code
To print the content of an HTML element such as “div”, you need to store its data in a variable. Now, we will perform the following steps while coding in JavaScript:

  • First, we will create a function named “printDivContent()”.
  • Then, define variables named “contentOfDiv” and “newWin” inside the “printDivContent()” function.
  • By using the “divCon” id, we will get the content of the “div” HTML element and store it in the variable “contentOfDiv”.
  • Variable “newWin” will be used to open the print window as a popup.
  • Then we will use the “newWin” variable to call the JavaScript method “document.write()”. In this method, we will pass the tags of the HTML elements that are added inside “div”, which in return get the content of the specified elements.

Here is the complete code for the above-given example:

function printDivContent ( ) {
var contentOfDiv = document. getElementById ( «divCon» ) . innerHTML ;
var newWin = window. open ( » , » , ‘height=650, width=650’ ) ;
newWin. document . write ( » ) ;
newWin. document . write ( » ) ;
newWin. document . write ( ‘ Content of Div element:
‘ ) ;
newWin. document . write ( contentOfDiv ) ;
newWin. document . write ( » ) ;
newWin. document . close ( ) ;
newWin. print ( ) ;
}

After running above HTML code, the resultant output on browser will be:

Clicking the “Print” button will call the JavaScript “printDivContent()” function and the following window will appear on the screen:

As you can see, we have successfully accessed the content of the added “div” element:

We have provided all the necessary information about printing the content of a “div” element using Javascript.

Conclusion

To print the content of a “div” element, firstly, you need to assign an “id” in HTML, then store its data in a variable by accessing the specified “id” in JavaScript code. While programming in JavaScript, there come situations where it is required to print a particular segment of a web page. In such cases, our provided method can help you out. This blog discussed the procedure of printing the div element’s content with the help of JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Hey Guys, In Today’s Blog We are going to see How to create and Print the Content of a Div Element Using Html and JavaScript. We Use Html and Javascript Code For Print the Content of a Div Element.

Here is a preview of how we Print the Content of a div.

Print the Content of a div Element using HTML & JavaScript

This is a very simple project in which the content will be contained in a div container that will be created using a basic HTML element and using the button command, the content will be printed inside the div area. This project teaches you how to construct a print button that lets users print any webpage they need while also teaching you the fundamentals of printing.

master frontend development ebook cover

Do you want to learn HTML to JavaScript? 🔥

If yes, then here is our Master Frontend: Zero to Hero eBook! 📚 In this eBook, you’ll learn complete HTML, CSS, Bootstrap, and JavaScript from beginner to advance level. 💪 It includes 450 Projects with source code.

Now The Project is going to create and for that, we are first adding an HTML Code.

HTML Code:

First We create a div class with the name “printableArea” and Inside the div class we add a header using an H1 tag with the content Print me, Then We close the Div tag.

Then We create an input class as button type and set the onclick function by giving a name for it and finally a value “print a div ” is added.

So that’s for HTML, Now We directly go for JavaScript to print the div area. Here we skip the CSS, if you want means you can use it. As it is a sample of the project so we directly added the content.

HTML Output:

Print the Content of a div Element using HTML & JavaScript

JavaScript Code:

Here first we create an function and calling out the onclick function which is in HTML to make contents inside to work it. Now We creating two variables namely “printContents” and “originalContents” one for calling out the element using JS get Element property and one for printing the contents inside of div class.

After that we are storing the printContents values to the originalContents value.

Then We use the JS property window.print to make a print of the contents inside of div class.

Lastly the contents which is inside of variable “originalContents” were again stored to the same variable declared three lines above.

So that’s for JS , Now We came to end of our Project as we successfully added the source codes. So we can now move for project preview which is mentioned below of Output Section.

Video Output Of Print the Content of a div Element:

Final Output Of Print the Content of a div Element:

See the Pen
Print Div area by Greg Vissing (@gvissing)
on CodePen.

Now We have Successfully created Print the Content of a div Element Using Html and JavaScript. You can use this project for your personnel needs and the respective lines of code are given with the code pen link mentioned below.

If you find out this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

Источник

Оцените статью