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

Methods to Exclude api_key from URL in AngularJS

To make a GET request to a REST API, I require an apikey. The request will be formed like this - $http.get() The response from the API will be in JSON format. However, for security reasons, I don't want the api key to be visible in the URL. Is ther ...

Resolving Cross-Origin Resource Sharing issues with AWS SDK (Lightsail API) and Vue.js

I'm currently working on a small vue.js application that utilizes aws-sdk to retrieve information about Lightsail instances. However, I keep encountering this issue. :8081/#/:1 Access to XMLHttpRequest at 'https://lightsail.us-west-2.amazonaws.c ...

Node.js encounters a conflict between route names and directory names

Can you use the same name for both a route and a directory in a Node.js project? For example: require("./test")(router); And inside the test.js file: app.get("/test", function(req, res) {}); Also, test is a directory in the same project. When attempti ...

The content within Contentful is presented in a JSON object format, but accessing specific values is proving to be

I have successfully added two records in the contentful database and now I am attempting to fetch the content from Contentful into my React-hooks website. However, I am facing difficulties retrieving the values for title, description, image, and shortDescr ...

When the action "X" was executed, reducer "Y" resulted in an undefined value

I'm encountering an issue with Redux in React. Despite searching through related questions, I haven't found a solution that fits my specific case. Here are the files involved: Index.JS import snackbarContentReducer from '../src/shared/red ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

Asynchronous update of array elements - lack of firing watch events

I have recently developed a component that showcases previews of blog articles. This particular component includes pagination functionality, where selecting a new page triggers the refreshment of the article previews array. The list of articles is obtained ...

Having issues with closing a div tag using $.after() function

This issue can be better understood with an example: http://jsbin.com/lavonexuse The challenge here is to insert a full-width row after a specific column (identified by the class .insertion-point) when "Insert Row" is clicked. The problem I'm facing ...

The Web API's GET request results in an HTTP/1.1 500 Internal Server Error being returned

When creating controllers using Entity, I have encountered an issue with one particular model in my project. While the "Get method" works fine for all other models in the context, it seems to be causing a problem for this specific one. The code in questio ...

How can one append a string of text to the right of each bar? Let's find out!

.chart div { font: 10px sans-serif; background-color: steelblue; text-align: right; padding: 3px; margin: 1px; color: white; } </style> <div class="chart"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5 ...

Display results in a Web application using Google Apps Script

function doGet() { return HtmlService.createHtmlOutputFromFile("vi"); // var output = HtmlService.createHtmlOutput('<b>Hello, world!</b>'); } function doPost() { return HtmlService.createHtmlOutputFromFile("vi"); // var out ...

Retrieving values of checked boxes in a table using JavaScript

While using the select method, I had this line of code: Person_name = $('#selectedPerson').val() When selecting 2 values, person_name.length displays as 2. Recently, I switched to checkboxes displayed in a table. However, when I use person_name ...

Creating a rotating wheel using JavaScript that is activated by a key press event

I need some help with implementing a keystroke event in this code so that the spinning wheel can start based on a key press, like the spacebar. Any suggestions on how to achieve this? I have found an event code for keystrokes in JavaScript: document.body. ...

What is the correct way to align labels to the right in a column layout?

I just started learning React JS and I'm using Material-UI. One issue I encountered is that when I use the column layout with an 'xs' value, the component inside the column appears aligned to the left. To align it to the right, I tried incr ...

Using selenium for testing JavaScript elements through RSpec results in failures in other segments of the RSpec test

Trying to implement Stripe into my web application has brought me to a frustrating roadblock. Every attempt to test the "Pay with Card" button seems to be thwarted by an ElementNotFound error thrown by rspec. Research revealed that the root cause of this ...

Having difficulties integrating a login solution due to an error saying "eslint Promise executor functions should not be async no-async-promise-executor"

I'm currently working on integrating a login solution into my Vue app using the JWT Authentication plugin. While I have a test solution that is functional, I'm facing an issue in my main branch where the eslint version seems to be causing an err ...

How can I link to a different field in a mongoDB Schema without using ObjectID?

I have created two schemas for books and authors: const bookSchema = new mongoose.Schema({ title: String, pages: Number, description: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' } }); const Book = mongoose.model ...

Is it possible to encase <v-img> within an anchor element?

I am currently using Vuetify 1.5 and have included a couple of <v-avatars></v-avatars> elements in which there is a nested <v-img></v-img>. I attempted to enclose the img tags within an a tag but encountered an issue wherein the ima ...

Unusual div image alignment when dimensions are dynamically adjusted with Javascript animations

I have created a basic webpage using JavaScript that aims to scale an element from the center of the page over time when clicked. It is functioning properly for the SVG element I tested it with. However, when I use an image, it initially appears outside o ...

Web page experiencing "increased magnification during loading"

I've been experiencing an issue with my mobile site where the page loads as if it's zoomed in every time. I can easily scale it on a touch phone to make it look right, but I'm looking for ideas on how to prevent this from happening altogethe ...