Print Test Page

Как распечатать часть отрендеренной HTML-страницы на JavaScript?

Код JavaScript window.print() может печатать текущую HTML-страницу. Если у меня есть div на странице HTML (например, страница, созданная с помощью ASP.NET MVC), тогда я хочу для печати только div. Есть ли какой-либо jQuery ненавязчивый JavaScript или обычный код JavaScript для реализации этого запроса? Сделав это более понятным, предположим, что отображаемая HTML-страница похожа:

6 ответов

   printDivCSS = new String ('') function printDiv(divId) 
This is a test page for printing
Div 1: Print
This is the div1 print output


Div 2: Print
This is the div2 print output


Div 3: Print
This is the div3 print output

printDivCSS просто там, если вам нужно отформатировать то, что вы печатаете, с помощью таблицы стилей. Если вы не хотите, чтобы ваш печатный текст форматировался с помощью таблицы стилей, тогда вам это не нужно.

Это решение прекрасно работает в FF, но не работает для IE 7. В IE7 он напечатает всю страницу с пустым полем для требуемой области печати

Я проверил, какова была ситуация. IE7 будет печатать активный кадр по умолчанию, поэтому я должен сфокусировать () кадр. Это не позволит мне сосредоточиться () «видимость: скрытый» контент, поэтому мне пришлось убрать этот бит стилевого форматирования. Фрейм уже имеет ширину, высоту и рамку 0, поэтому он скрыт даже без форматирования стиля. Таким образом, все работает. О, последнее замечание: если пользователь пытается CTRL + F выполнить поиск на странице, возможно, что его поиск найдет совпадения внутри фрейма, совпадения, которые они не видят. Вам нужно будет очистить кадр после того, как они закончат печать, чтобы исправить это.

Читайте также:  Php проверить равно ли

Источник

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.

Источник

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

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, то можно упростить код, удалив пару строк:

Материалы:

Источник

How to Print the content of DIV with Images using JavaScript

www.encodedna.com

I have previously shared an article here explaining how to print HTML table with images using JavaScript. Now, here in this article I’ll show you how to print the contents of a DIV element with images using plain old JavaScript.

An HTML &ltdiv> element can have different types of content inside different elements, like a &ltp> element, a header element like &lth2>, it can have an &ltimg/> element etc.

Print DIV content with images using JavaScript

To print the contents of various elements inside a &ltdiv>, we’ll have to first extract the contents and store it in a variable. Then we’ll open a window (a pop window) and write the contents (stored in a variable) in the window and print.

In the first example, the &ltdiv> will have two &ltp> elements and an &lth2> (for header) element.

<!DOCTYPE html> <html> <head> <style> div < border: solid 1px #CCC; padding: 10px; ></style> </head> <body> <div id='parent'> <h2>This is header :-)</h2> <p> Child element 1 </p> <p> Child element 2 </p> </div> <p> <input type='button' value='Print Content' onclick='myApp.printDiv()' /> </p> </body> <script> var myApp = new function () < this.printDiv = function () < // Store DIV contents in the variable. var div = document.getElementById('parent'); // Create a window object. var win = window.open('', '', 'height=700,width=700'); // Open the window. Its a popup window. win.document.write(div.outerHTML); // Write contents in the new window. win.document.close(); win.print(); // Finally, print the contents. > > </script> </html>

The parent &ltdiv> element has an id . Using the element’s id, I am first extracting the contents of it and storing it in a variable. See the above script.

The window object is important here. It represents a window in browser. I am using the object to open a new browser window.

The method takes 4 parameters like url, name, features and replace . However, I have just assigned one value that is the height and width of the window. If you remove the first two blank parameters, the method will open a new window in new a tab.

The .write() method (win.document.write(div.outerHTML);) will write the contents in the new popup window, which is later closed using the .close() method.

After closing the window object, I am printing the contents using the .print() method.

Note: If a printer is attached to the computer, it will ask you to choose a printer. Or else, it will print a PDF document.

Now, lets print the contents of a &ltdiv> element along with images.

<!DOCTYPE html> <html> <head> <style> div < border: solid 1px #CCC; padding: 10px; >img < width: 75px; height: 75px; >input < font-size: 20px; ></style> </head> <body> <div > <h2>This is header :-)</h2> <p> Child element 1 </p> <p> Child element 2 </p> <!--Here are the images--> <div> <img src='https://www.encodedna.com/images/theme/javascript.png' alt='JS' /> <img src='https://www.encodedna.com/images/theme/google.png' alt='Google' /> </div> </div> <p> <input type='button' value='Print Content' onclick='myApp.printDiv()' /> </p> </body> <script> var myApp = new function () < this.printDiv = function () < // Store DIV contents in the variable. var div = document.getElementById('parent'); // Create a window object. var win = window.open('', '', 'height=700,width=700'); // Open the window. Its a popup window. win.document.write(div.outerHTML); // Write contents in the new window. win.document.close(); win.print(); // Finally, print the contents. > > </script> </html>

There is not much difference between the first and second example. The script is the same for both the examples, with or without images. There’s not much to explain.

However, I have defined CSS style in the above example (the 2nd example) for the elements inside the &lthead> tag, especially the images ( img < width: 75px; height: 75px; >). The images have specific width and height defined. See the &ltstyle> tag inside the &lthead> tag. But, the styles were not applied when I tried to print it.

We can apply style to the images and other elements before printing it.

Add some Style to the Print

To define style to the print, add a variable and add few styles (CSS styles) according to you requirement. For example,

<script> var myApp = new function () < this.printDiv = function () < var div = document.getElementById('parent'); var win = window.open('', '', 'height=700,width=700'); // Define and style for the elements and store it in a vairable. var style = '<style>'; style = style + 'div, p '; style = style + 'img < width: 75px; height: 75px;>'; style = style + '</style>'; // Now, write the DIV contents with CSS styles and print it. win.document.write(style); win.document.write(div.outerHTML); win.print(); > > </script>

Now, the &ltdiv> element has borders and padding. The image has specific width and height. Similarly, if you want you can define fonts, size, colours etc.

Источник

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