Как распечатать на javascript

How can I pop-up a print dialog box using Javascript?

I have a page with a «Print» link that takes the user to a printer-friendly page. The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page. How can I do this with javascript?

10 Answers 10

unless you mean a custom looking popup.

A bit old, but I like to add . window.print();setTimeout(«window.close()», 100); . This waits enough time for the rest of the page to load, but then hangs until the print button on the print dialogue is pressed, or cancelled, and then neatly shuts the tab down again.

I like this, so that you can add whatever fields you want and print it that way.

function printPage() < var w = window.open(); var headers = $("#headers").html(); var field= $("#field1").html(); var field2= $("#field2").html(); var html = ""; html += ''; html += ' '; html += ""; //check to see if they are null so "undefined" doesnt print on the page. 
s optional, just to give space if(headers != null) html += headers + "

"; if(field != null) html += field + "

"; if(field2 != null) html += field2 + "

"; html += ""; w.document.write(html); w.window.print(); w.document.close(); >;

This worked like a charm for me. Needed to allow popups in browser. I’m not sure the «close» ever gets executed, since the tab never goes away.

If you just have a link without a click event handler:

I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.

You can tie it to button or on load of the page.

I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor).

You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)

@inject IJSRuntime JSRuntime 

Once you have that injected, create a button with a click event that calls a C# method:

Читайте также:  Как изменить css scrolls

(or something more simple if you don’t use MatBlazor)

Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it’s calls such as InvokeVoidAsync

PS: If you wanted to message box in asp net core for instance:

await JSRuntime.InvokeAsync("alert", "Hello user, this is the message box"); 

To have a confirm message box:

bool question = await JSRuntime.InvokeAsync("confirm", "Are you sure you want to do this?"); if(question == true) < //user clicked yes >else < //user clicked no >

Источник

How to print in JavaScript — with code examples

Posted on Apr 25, 2022

Depending on what you want to print and where you run JavaScript code, there are several ways to print in JavaScript.

When you want to print the current webpage of your browser, you can use the window.print() method.

The window.print() method will print the content of the currently active tab in your browser.

You can run the method from the browser console to print the webpage with your printer.

  • Print to the console using console.log()
  • Print to the browser interface using document.write()
  • Print to the alert box using window.alert() method
  • Print to the HTML tag by changing innerHTML property value

Let’s see how to do each one of these methods next.

The console.log() method allows you to print JavaScript data and values to the console.

This is useful when you want to check the value of variables you have in your JavaScript code as shown below:

The console.log() method instructs the JavaScript console to log the value passed as its parameter.

The console is available both on the browser and the Node.js server.

The document.write() method is used to write data to the tag of your HTML document.

This method will erase all data stored inside the tag of your webpage.

Читайте также:  Весь коды цветов css

For example, suppose you have the following HTML document rendered in your browser:

When you run a document.write() command from the browser’s console, the HTML document above will be overwritten.

Running the following command:

Will produce the following output:
 As you can see, all attributes and elements previously written in the document have been erased.

The document object model is not available in the Node.js server, so you can only use this method from the browser.

The window.alert() method is used to create an alert box that’s available in the browser where you run the code.

For example, running the code below:

Will produce the following output:

How to print JavaScript with window.alert()

Using window.alert() method, you can check on your JavaScript variables and values with the browser’s alert box.

You can print to a specific HTML element available on your webpage by changing the innerHTML property of that element.

For example, suppose you have the following HTML document:


The HTML document will have the following changes:

Once you get the element, change the innerHTML property value, and that change will be reflected on your browser page.

Now you’ve learned how to print data and values in JavaScript. Good job! 👍

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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

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

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

  

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

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

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

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

Материалы:

Источник

Версия страницы для печати или печать отдельного блока на сайте

Версия страницы для печати или печать отдельного блока на сайте

В этой статье рассмотрим как можно вызвать печать страницы с помощью JavaScript, распечатать отдельные блоки сайта и оформить распечатываемую страницу стилями.

Вызвать печать на странице

Печать документа на странице можно вызвать JavaScript функцией print() .

Оформление страницы печати

Оформить вид страницы сайта при печати очень просто. Делается это с помощью медиа-запросов. Для этого в стили сайта добавляем @media print и внутри него пишем стили, которые будут вызваны при печати страницы Типография Печатник. В примере ниже на распечатываемой странице сайта отключаем блок с рекламой:

Печать отдельного блока со страницы

Код HTML

Заголовок

Текст
Печать

Код JavaScript

  

При нажатии кнопки «Печать» происходит вызов функции callPrint() . Если будете модернизировать код, то тут функции можно передавать к примеру ID блока, который нужно распечатать. В примере мы ничего не передаем и не используем библиотеку jQuery, хотя при более сложной вариации с ней будет проще.

Далее вызывается всплывающее окно, в которое добавляются наши блоки, после чего окно закрывается и открывается окно браузера для печати. Все это делается практически незаметно. И для пользователя это будет выглядеть так, как будто окно печати открылось сразу.

Подборка бесплатных IT-курсов и вебинаров от Skillbox.

Бесплатные IT-курсы, нужно только пройти онлайн-тест здесь

Если вам понравилась статья, вы можете отблагодарить автора любой суммой, какую сочтете для себя приемлемой:

Источник

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