locked
How to print any file format in c# RRS feed

  • Question

  • using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Diagnostics;
    
    namespace PrintFile
    {
        public partial class PrintFile : Form
        {
            public PrintFile()
            {
                InitializeComponent();
            }
    
            // browse file
            private void BrowseBttn_Click(object sender, EventArgs e)
            {
                try
                {
                    OpenFileDialog openfile = new OpenFileDialog();
                    openfile.Title = "Select the file";
    
                    if (openfile.ShowDialog() == DialogResult.OK)
                    {
                        FilePath.Text = openfile.FileName;
                    }
                }
                catch(Exception x) 
                {
                    MessageBox.Show(x.Message + "\n\n Unable to select the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
    
            private void PrintBttn_Click(object sender, EventArgs e)
            {
                try
                {
                    string Filepath = string.Empty;
    
                    Filepath = FilePath.Text.Trim();
    
                    Process print = new Process();
    
                    print.StartInfo.FileName = Filepath;
    
                    print.StartInfo.Verb = "Print";
    
                    print.StartInfo.UseShellExecute = true;
    
                    print.StartInfo.CreateNoWindow = true;
    
                    print.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    
                    print.Start();
    
                   // print.StartInfo.Arguments =
    
                    print.CloseMainWindow();
    
                    print.Close();
    
                } // end try
                catch (Exception x)
                {
                    MessageBox.Show(x.Message + "\n\n Unable to print the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                } // end catch
    
                 
            }
        }
    }

    Above code for print file  in  printer.

    The above code, In some PC it is working and some PC it is not  working .  I am try to print pdf ,  word  and text file.

    i am facing the problem to print pdf file and text file .

    Please help  me ,

    how to print pdf and text  file  using  C# program    


    Mukesh Kumar


    • Edited by mukeshkumarts Monday, December 30, 2013 5:39 AM
    • Moved by Cindy Meister MVP Monday, December 30, 2013 2:21 PM neither Office nor Word related
    Monday, December 30, 2013 5:36 AM

Answers

  • Print text file, use following source code,

    using(Printfile = new StreamReader("c:\\testDir1\\Password.txt))
        {
            try
            {
                PrintDocument docToPrint = new PrintDocument();
                docToPrint.DocumentName = "Password"; //Name that appears in the printer queue
                docToPrint.PrintPage += (s, ev) =>
                {
                    float linesPerPage = 0;
                    float yPos = 0;
                    int count = 0;
                    float leftMargin = ev.MarginBounds.Left;
                    float topMargin = ev.MarginBounds.Top;
                    string line = null;
    
                    // Calculate the number of lines per page.
                    linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
    
                    // Print each line of the file. 
                    while (count < linesPerPage && ((line = Printfile.ReadLine()) != null))
                    {
                        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                        ev.Graphics.DrawString(line, printFont, Brushes.Black,  leftMargin, yPos, new StringFormat());
                        count++;
                    }
    
                    // If more lines exist, print another page. 
                    if (line != null)
                        ev.HasMorePages = true;
                    else
                        ev.HasMorePages = false;
                };
                docToPrint.Print();
            }
            catch (System.Exception f)
            {
                MessageBox.Show(f.Message);
            }
        }
    Print PDF file,

    http://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html

    -----------------------------------------
     Mark as answer if it helps to you
     Free .NET Barcode Generator & Scanner supporting over 40 symbologies

    • Marked as answer by Eason_H Monday, January 6, 2014 9:24 AM
    Monday, December 30, 2013 8:48 AM
  • Hi mukeshkumarts,

    If you want to print document such as the  doc, docx, pdf, jpeg etc. with C# code. Follow this Post.

    Here I have to use the filedialog control of dot net framework for the file  browsing purpose and add this namespace using System.Diagnostics and  using ProcessStartInfo class i have to call the particular document file and  print this file.

    Using ProcessStartinfo Class we can call the external resources which is  outside of dot net technology. Window based Application:=>Add opendialog control  on Designer Form.

    Add this code in Form.cs in : Add this code on the Browse Button Click  For browsing file.

    private void btnBrowse_Click(object sender, EventArgs e)
    
    {
    
       DialogResult dr = openFileDialog1.ShowDialog();
    
        string[] s = openFileDialog1.FileName.Split('.');
    
        if (dr.ToString() == "OK")
    
       {
    
            if (s.Length > 1)
    
            if (s[1] == "doc" || s[1] == "docx" || s[1] == "jpg")
    
            txtFileName.Text = openFileDialog1.FileName;
    
        else
    
         MessageBox.Show("Please select doc,docx,jpeg file !!");
    
     }
    
    }
    

    Add This code on print Button Click:=>Here i have to use processStartInfo dot  net inbuilt class for accessing external resourcess like do,docx etc file.

    private void btnPrint_Click(object sender, EventArgs e)
    
    {
    
         if (string.IsNullOrEmpty(txtFileName.Text.Trim()))
         { 
    
             txtFileName.BackColor = Color.Yellow;
    
             MessageBox.Show("Please Select file.");
    
              return;
         }
    
        //Using below code we can print any document 
    
        ProcessStartInfo info = new ProcessStartInfo(txtFileName.Text.Trim());
    
        info.Verb = "Print";
    
        info.CreateNoWindow = true;
    
        info.WindowStyle = ProcessWindowStyle.Hidden;
    
        Process.Start(info);
    } 
    

    Article from here :http://www.c-sharpcorner.com/Blogs/13946/print-any-document-file-using-a-C-Sharp-code-without-opening-docu.aspx

    A nice article, you can refer to. Hope it can help you.

    Thanks


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Eason_H Monday, January 6, 2014 9:24 AM
    Tuesday, December 31, 2013 6:03 AM

All replies

  • Print text file, use following source code,

    using(Printfile = new StreamReader("c:\\testDir1\\Password.txt))
        {
            try
            {
                PrintDocument docToPrint = new PrintDocument();
                docToPrint.DocumentName = "Password"; //Name that appears in the printer queue
                docToPrint.PrintPage += (s, ev) =>
                {
                    float linesPerPage = 0;
                    float yPos = 0;
                    int count = 0;
                    float leftMargin = ev.MarginBounds.Left;
                    float topMargin = ev.MarginBounds.Top;
                    string line = null;
    
                    // Calculate the number of lines per page.
                    linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
    
                    // Print each line of the file. 
                    while (count < linesPerPage && ((line = Printfile.ReadLine()) != null))
                    {
                        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                        ev.Graphics.DrawString(line, printFont, Brushes.Black,  leftMargin, yPos, new StringFormat());
                        count++;
                    }
    
                    // If more lines exist, print another page. 
                    if (line != null)
                        ev.HasMorePages = true;
                    else
                        ev.HasMorePages = false;
                };
                docToPrint.Print();
            }
            catch (System.Exception f)
            {
                MessageBox.Show(f.Message);
            }
        }
    Print PDF file,

    http://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html

    -----------------------------------------
     Mark as answer if it helps to you
     Free .NET Barcode Generator & Scanner supporting over 40 symbologies

    • Marked as answer by Eason_H Monday, January 6, 2014 9:24 AM
    Monday, December 30, 2013 8:48 AM
  • Hello Mukesh,

    It looks like your question is not related to Word developers. Am I right? If so, I would recommend asking such questions in the Visual C# or Visual Basic forums. There, I suppose, you will get the most qualified answers. Anyway, I have found a similar forum thread - Print a file Using C# without Print dialogue box .

    If you develop a VSTO add-in, VBA macro or just automate Word, you can use the PrintOut method of the Document class from the Word Object Model. You can read more about this approach in the How to: Programmatically Print Documents article in the MSDN library.

    Monday, December 30, 2013 2:32 PM
  • Hi mukeshkumarts,

    If you want to print document such as the  doc, docx, pdf, jpeg etc. with C# code. Follow this Post.

    Here I have to use the filedialog control of dot net framework for the file  browsing purpose and add this namespace using System.Diagnostics and  using ProcessStartInfo class i have to call the particular document file and  print this file.

    Using ProcessStartinfo Class we can call the external resources which is  outside of dot net technology. Window based Application:=>Add opendialog control  on Designer Form.

    Add this code in Form.cs in : Add this code on the Browse Button Click  For browsing file.

    private void btnBrowse_Click(object sender, EventArgs e)
    
    {
    
       DialogResult dr = openFileDialog1.ShowDialog();
    
        string[] s = openFileDialog1.FileName.Split('.');
    
        if (dr.ToString() == "OK")
    
       {
    
            if (s.Length > 1)
    
            if (s[1] == "doc" || s[1] == "docx" || s[1] == "jpg")
    
            txtFileName.Text = openFileDialog1.FileName;
    
        else
    
         MessageBox.Show("Please select doc,docx,jpeg file !!");
    
     }
    
    }
    

    Add This code on print Button Click:=>Here i have to use processStartInfo dot  net inbuilt class for accessing external resourcess like do,docx etc file.

    private void btnPrint_Click(object sender, EventArgs e)
    
    {
    
         if (string.IsNullOrEmpty(txtFileName.Text.Trim()))
         { 
    
             txtFileName.BackColor = Color.Yellow;
    
             MessageBox.Show("Please Select file.");
    
              return;
         }
    
        //Using below code we can print any document 
    
        ProcessStartInfo info = new ProcessStartInfo(txtFileName.Text.Trim());
    
        info.Verb = "Print";
    
        info.CreateNoWindow = true;
    
        info.WindowStyle = ProcessWindowStyle.Hidden;
    
        Process.Start(info);
    } 
    

    Article from here :http://www.c-sharpcorner.com/Blogs/13946/print-any-document-file-using-a-C-Sharp-code-without-opening-docu.aspx

    A nice article, you can refer to. Hope it can help you.

    Thanks


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Eason_H Monday, January 6, 2014 9:24 AM
    Tuesday, December 31, 2013 6:03 AM