Printing in ASP.Net without displaying a dialog box

Is there a way for my web application to automatically print a popup page without prompting the client to choose a printer?

I am looking for guidance on implementing silent printing in ASP.Net using java-script or ajax, or any other suitable solution for this scenario. Can you provide recommendations or examples?

Answer №1

There are legitimate reasons why users cannot default to a specific printer:

  • Users need the freedom to select their preferred printer for printing.

  • Users should have the option to decide whether or not to print, preventing unwanted material from being constantly printed.

Answer №2

You can find third party controls that are compatible with WPF for this task. It may be worth exploring whether they can also be used in an asp.net environment.

Answer №3

//PrintPage.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Printing;
using System.IO;
using System.Drawing;

namespace PrintManagement
{
    public partial class PrintPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }

        }

         private void printDocument2_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
           {

                Graphics g = e.Graphics;
                SolidBrush Brush = new SolidBrush(Color.Blue);
                string textToPrint = TextBox2.Text;
                g.DrawString(textToPrint, new Font("verdana", 14), Brush, 10, 10);

            }


        protected void PrintButton_Click(object sender, EventArgs e)
        {
            try
            {
                string currentTime = DateTime.Now.ToString("yyyyMMddHHmm");
                System.Drawing.Printing.PrinterSettings printerSettings = new System.Drawing.Printing.PrinterSettings();
                printerSettings.PrintToFile = true;
               // ps.PrintFileName = "D:\\PRINT\\Print_"+Time+".oxps"; /* you can save file here */
                System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument();
                printDoc.PrintPage += new PrintPageEventHandler(printDocument2_PrintPage);
                System.Drawing.Printing.StandardPrintController standardPrintControl = new System.Drawing.Printing.StandardPrintController();
                printDoc.PrintController = standardPrintControl;
                printDoc.DefaultPageSettings.Landscape = true;
                printDoc.PrinterSettings = printerSettings;
                printDoc.Print();
                TextBox2.Text = "";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Printed Successfully.Check: Drive D')", true);


            }
            catch (Exception ex)
            {

            }


        }

        protected void RefreshButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("PrintPage.aspx");
        }
    }
}

//PrintPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PrintPage.aspx.cs" Inherits="PrintManagement.PrintPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>


</head>
<body>
    <form id="form1" runat="server">


    <asp:TextBox ID="TextBox2" runat="server" Width="240px" Height="120px" 
        TextMode="MultiLine"></asp:TextBox>


    <br />
    <br />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
        ControlToValidate="TextBox2" ErrorMessage="Empty message cannot be printed!" 
        ValidationGroup="vgp1"></asp:RequiredFieldValidator>
    <br />
    <br />
    <asp:Button ID="PrintButton" runat="server" Text="Print" onclick="PrintButton_Click" 
        ValidationGroup="vgp1" />


    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="RefreshButton" runat="server" onclick="RefreshButton_Click" Text="Refresh" 
        ValidationGroup="vgp2" />
&nbsp;&nbsp;&nbsp;


    </form>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining the power of Vuforia with the capabilities of Three

I'm having difficulty with the integration of three.js and Vuforia, as I have limited knowledge about OpenGl which makes it challenging to troubleshoot. Our team is working on a small AR app where we aim to utilize Vuforia for tracking and recognitio ...

Validating date and time picker pairs using JavaScript

I am looking to implement start and end date validation using datetimepicker. My current code is not functioning as expected. I need the end date to be greater than or equal to the start date, and vice versa. If anyone has a solution for this issue, plea ...

What could be the reason these two functions yield different outcomes?

I am currently in the process of optimizing a function to enhance performance. Previously, the old function took approximately 32 seconds, while the new one now only takes around 350 milliseconds for the same call. However, there seems to be an issue as th ...

Ember's distinctive feature: Named Block Helpers

Can we create "named blocks" in a different way? For instance, {{#customBlock "repeatableBlock"}} {{!-- block containing numerous properties and data that may become messy if hardcoded multiple times --}} {{/customBlock}} Then, elsewhere in the code, {{ ...

Is there a way to create a timed fadeIn and fadeOut effect for a div using HTML and CSS?

I have a single div that initially displays text, and I want it to fade out after a specific time so that another div will then fade in. However, my attempt at coding this transition is not producing the desired result: $(function() { $(".preloa ...

Tips for accessing the value of the range slider in Bootstrap 5 while it is being slid

Is it possible to capture the value from a Bootstrap 5 slider while sliding? I want to continuously receive the value as I move the handle, rather than only getting the final value when I release the handle. Currently, I am using a Bootstrap 5 range slide ...

Sort function now accepts a limitless amount of arguments for sorting

We are tasked with creating a function that can take an unlimited number of arguments to sort an array by. For example: var data = [['John','London',35], ['Ricky','Kuala Lumpur',38], [' ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

The hyperlink does not function properly when included within an <input type=button> element

I have encountered an issue with the code below. In my project, I have a search bar along with some buttons. Currently, only the hyperlink of the search button is functioning correctly. The other buttons seem to redirect to the same link as the search bu ...

Can you explain the significance behind the error message "RangeError: Invalid status code: 0"?

Currently, I'm trying to understand the workings of express and have come up with this get method: app.get('/myendpoint', function(req, res) { var js = JSON.parse ({code: 'success', message:'Valid'}); res.status( ...

Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display. HTML structure: <div id="canvas"></div> To populate the canvas with div elements, I'v ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

How can I access an InputStream from a local XML file in a PhoneGap application?

Looking for advice on how to fetch an inputstream from a local XML file using JavaScript in my PhoneGap application. I'm new to JavaScript, so any guidance would be appreciated! ...

AngularJS and the JavaScript programming language

Struggling with opening an Excel sheet by clicking on a button? I've written the code, but encountering issues. function openFile(strFilePath) { var objExcel; //Create EXCEL object objExcel = new ActiveXObject("Excel.Applicati ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Attempting to integrate a three.js OBJLoader within an HTML canvas

My issue is quite straightforward: I attempted to connect a three.js script with an HTML canvas, but I was unsuccessful and now I'm unsure how to proceed. Here is the code I have (I've already loaded the necessary scripts in the HTML head): wi ...

Unable to transmit Props to Component - Fluctuating Behavior

I developed a React.js and Next.js application where I needed to pass the User object to all pages. My plan was to then pass this User component to the Head component in order to display different navigation options based on the user's role. Here is w ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

PHP data is not displayed by Ajax

I seem to be encountering a bit of trouble. I am attempting to utilize ajax to retrieve data from a PHP server, which in turn fetches it from a MySQL database, and then display it within a specific HTML tag location. However, for some unknown reason, nothi ...