Thursday 12 June 2014

Printing a Remote Document Using Aspose.Words to a Network Printer.

Sometimes clients need to print documents from Internal non public facing websites. At times there are also user access considerations in that we do not want to give them direct access to the file. For this we allow them the option to print the document to a designated printer on their network. We can do this by creating a simple printing method that takes a URL / Downloads It on the Server / Renders It Through Aspose and Prints it to a Network printer. Step 1. Identify the Network Printer we can display printers running this command
public static void Main(string[] args)
{
     DropDownList list = new DropDownList();
     
     System.Drawing.Printing.PrinterSettings.InstalledPrinters.Cast().ForEach
     (
         y => this.ddlPrinters.Items.Add(y)            
     );
}
Step 2. Run this method
var couldPrint = PrintDocument("http://www.somesite.com/somedocument.doc", this.ddlPrinters.SelectedValue);
Which in turn runs this block of code. Step 3.
public static bool PrintDocument(string uriToDocument, string printerName)
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uriToDocument);
                myReq.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);
                WebResponse myResp = myReq.GetResponse();

                StreamReader reader = new StreamReader(myResp.GetResponseStream());

                MemoryStream ms = new MemoryStream();

                reader.BaseStream.CopyTo(ms);

                if (Path.GetExtension(uriToDocument) == ".doc" || Path.GetExtension(uriToDocument) == ".docx")
                {
 
                    Aspose.Words.Document document = new Aspose.Words.Document(ms);

                    document.Print(printerName);

                }
                return true;
            }
            catch (Exception ex)
            {
                //Log to your database here.
            }

            return false;
        }

No comments:

Post a Comment