process always prints document by default printer - c#

I have a problem with selecting printer to print my document.
My code is :
var filename = #"C:\Users\I\Desktop\test.doc";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings =new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
Process objP = new Process();
objP.StartInfo.FileName = filename;
objP.StartInfo.WindowStyle =
ProcessWindowStyle.Hidden; //Hide the window.
objP.StartInfo.Verb ="print";
objP.StartInfo.Arguments ="/p /h \"" + filename + "\" \"" + pd.PrinterSettings.PrinterName + "\"";
objP.StartInfo.CreateNoWindow = false;
//true;//!! Don't create a Window.
objP.Start();
//!! Start the process !!//
objP.CloseMainWindow();
}
and whatever I choose, process always will use default printer, no matter what value of pd.PrinterSettings.PrinterName is.
What's wrong with my code?

You probably want to use "PrintTo" instead of "print" for the verb. You already set objP.FileName to the filename so there's no need to get complicated in the arguments. Pass the printer name alone there.
var filename = #"C:\Users\I\Desktop\test.doc";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings =new PrinterSettings();
if (DialogResult.OK == pd.ShowDialog(this))
{
Process objP = new Process();
objP.StartInfo.FileName = filename;
objP.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //Hide the window.
objP.StartInfo.Verb ="PrintTo";
objP.StartInfo.Arguments = pd.PrinterSettings.PrinterName;
objP.StartInfo.CreateNoWindow = false;
//true;//!! Don't create a Window.
objP.Start();
//!! Start the process !!//
objP.CloseMainWindow();
}

Try changing pd.PrinterSettings =new PrinterSettings(); to read something like this:
pd.PrinterSettings =new System.Drawing.Printing.PrinterSettings;
By default when you create an instance of printer settings it returns the default printer name just an fyi... you can then try something like this
//sudu code
foreach(string strPrinter in PrinterSettings.InstalledPrinters)
{
// or unless you know the name of the printer then skip this and assign it to the code above
}

Related

How to print .docx silently with c#

I want to print a .docx file silently and being able to choose the tray of the printer.
At first I tried to print the .docx with the Microsoft.Office.Interop.Word but word is opening...
After I converted the .docx file to an image and printed it with ProcessStartInfo but it shows a printing window to the user.
ProcessStartInfo info = new ProcessStartInfo(imageFilePath);
info.Verb = "Print";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(info);
I tried another method it print the image silently BUT the image is blured and not scaled correctly.
PrinterSettings settings = new PrinterSettings();
string defaultPrinter = settings.PrinterName;
FileInfo fileInfo = new FileInfo(imageFilePath);
PrintDocument pd = new PrintDocument();
pd.DocumentName = fileInfo.Name;
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(imageFilePath);
PrintPageEventArgs arguments = args;
System.Drawing.Rectangle m = new System.Drawing.Rectangle()
{
Y = 0,
X = 0,
Location = new System.Drawing.Point(0, 0),
Height = args.MarginBounds.Height,
Size = args.MarginBounds.Size,
Width = args.MarginBounds.Width
};
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height)
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
args.Graphics.DrawImage(i, m);
};
pd.Print();
So is it possible to print a .docx silently and being able to choose the tray of the printer ?
Did anyone face the same issue. Any help in this regard. Thanks in advance.
I did something very similar to this myself but I never looked up the documentation if you could choose the tray. I believe these are set on the print server itself (if you are using one) and would be able to reference those if your application has the access rights.
string PrinterName = #"\\Server\nameOfThePrinter";
ProcessStartInfo printProcessInfo = new ProcessStartInfo()
{
Verb = "PrintTo",
CreateNoWindow = true,
FileName = pdfFileName,
Arguments = "\"" + PrinterName + "\"",
WindowStyle = ProcessWindowStyle.Hidden
};
Process printProcess = new Process();
printProcess.StartInfo = printProcessInfo;
printProcess.Start();
printProcess.WaitForInputIdle();
printProcess.WaitForExit(10000);
if (printProcess.HasExited)
{
}else
{
printProcess.Kill();
}
return true;
Also, you may want to investigate this article here https://www.codeproject.com/Tips/598424/How-to-Silently-Print-PDFs-using-Adobe-Reader-and
Cheers!
I found a solution I couldn't print a .docx silently so I converted it as a .png image before.
Link to convert .docx to .png
Here is the code to print the image :
PrinterSettings settings = new PrinterSettings();
string PrinterName = settings.PrinterName;
//set paper size
PaperSize oPS = new PaperSize
{
RawKind = (int)PaperKind.A4
};
//choose the tray here
PaperSource oPSource = new PaperSource
{
RawKind = (int)PaperSourceKind.Upper
};
PrintDocument printDoc = new PrintDocument
{
PrinterSettings = settings,
};
//set printer name here it's the default printer
printDoc.PrinterSettings.PrinterName = PrinterName;
printDoc.DefaultPageSettings.PaperSize = oPS;
printDoc.DefaultPageSettings.PaperSource = oPSource;
printDoc.PrintPage += new PrintPageEventHandler((sender, args) =>
{
System.Drawing.Image img = System.Drawing.Image.FromFile(imageFilePath);
int printHeight = (int)printDoc.DefaultPageSettings.PrintableArea.Height;
int printWidth = (int)printDoc.DefaultPageSettings.PrintableArea.Width;
int leftMargin = 0;
int rightMargin = 0;
args.Graphics.DrawImage(img, new System.Drawing.Rectangle(leftMargin, rightMargin, printWidth, printHeight));
});
printDoc.Print();
printDoc.Dispose();

How to send multiple files to the printer with one Process call

I need to print multiple PDF-files from the hard-drive. I have found this beautiful solution of how to send a file to the printer. The problem with this solution is that if you want to print multiple files you have to wait for each file for the process to finish.
in the command shell it is possible to use the same command with multiple filenames: print /D:printerName file1.pdf file2.pdf
and one call would print them all.
unfortunately simply just to put all the filenames into the ProcessStartInfo doesn't work
string filenames = #"file1.pdf file2.pdf file3.pdf"
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.FileName = filenames;
neither does it to put the filenames as Arguments of the Process
info.Arguments = filename;
I always get the error: Cannot find the file!
How can I print a multitude of files with one process call?
Here is an example of how I use it now:
public void printWithPrinter(string filename, string printerName)
{
var procInfo = new ProcessStartInfo();
// the file name is a string of multiple filenames separated by space
procInfo.FileName = filename;
procInfo.Verb = "printto";
procInfo.WindowStyle = ProcessWindowStyle.Hidden;
procInfo.CreateNoWindow = true;
// select the printer
procInfo.Arguments = "\"" + printerName + "\"";
// doesn't work
//procInfo.Arguments = "\"" + printerName + "\"" + " " + filename;
Process p = new Process();
p.StartInfo = procInfo;
p.Start();
p.WaitForInputIdle();
//Thread.Sleep(3000;)
if (!p.CloseMainWindow()) p.Kill();
}
Following should work:
public void PrintFiles(string printerName, params string[] fileNames)
{
var files = String.Join(" ", fileNames);
var command = String.Format("/C print /D:{0} {1}", printerName, files);
var process = new Process();
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = command
};
process.StartInfo = startInfo;
process.Start();
}
//CALL
PrintFiles("YourPrinterName", "file1.pdf", "file2.pdf", "file3.pdf");
It's not necessarily a simple solution, but you could merge the pdfs first and then send then to acrobat.
For example, use PdfMerge
Example overload to your initial method:
public void printWithPrinter(string[] fileNames, string printerName)
{
var fileStreams = fileNames
.Select(fileName => (Stream)File.OpenRead(fileName)).ToList();
var bundleFileName = Path.GetTempPath();
try
{
try
{
var bundleBytes = new PdfMerge.PdfMerge().MergeFiles(fileStreams);
using (var bundleStream = File.OpenWrite(bundleFileName))
{
bundleStream.Write(bundleBytes, 0, bundleBytes.Length);
}
}
finally
{
fileStreams.ForEach(s => s.Dispose());
}
printWithPrinter(bundleFileName, printerName);
}
finally
{
if (File.Exists(bundleFileName))
File.Delete(bundleFileName);
}
}

printing pdf without spawning adobe reader?

Presently I'm using the following lines of c# code to automatically print a pdf file to a mobile printer:
string defFile = (Path.Combine(System.Windows.Forms.Application.StartupPath, tkt_no + "_DEF.pdf"));
string rwPrinter = "";
if (GlobalVars.useDefaultPrinter == false)
{
foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
if (strPrinter.StartsWith("ZDesigner"))
{
rwPrinter = strPrinter;
break;
}
}
}
if (jobdo.Equals("print"))
{
Process process = new Process();
process.StartInfo.FileName = defFile;
if (rwPrinter.Length > 0)
{
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + rwPrinter + "\"";
}
else
{
process.StartInfo.Verb = "print";
}
process.Start();
process.WaitForInputIdle();
Thread.Sleep(10000);
process.Kill();
These above lines are good if the application is on a workstation desktop, but the problem I am having is when it actually prints the pdf file from a Citrix App shortcut, it spawns Adobe Reader (the default for pdf) and doesn't close when print job is done.
So my question is, is there any way to print a pdf document without opening Adobe or similar? Perhaps in the iTextSharp library which I'm using in the same application to populate fields?

Print File without print dialog box

I need your help to print my locally saved file without using print dialog box , i tried out many cases but failed to do so. one case is like;
var pr = new PrintDocument();
pr.PrintController = new System.Drawing.Printing.StandardPrintController();
pr.PrinterSettings = new PrinterSettings();
pr.PrinterSettings.PrintFileName = "E:\\File.docx";
pr.PrinterSettings.PrinterName = fileName.ToString();
pr.Print();
pr.Dispose();
This will start Microsoft Word and print the test.rtf while suppressing the Print dialog box. However, the path must be fully specified.
var settings = new PrinterSettings();
var startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Program Files\Microsoft Office\Office\WINWORD.EXE";
startInfo.Arguments = #"test.rtf /q /n /mFilePrintDefault /mFileExit";
var p = Process.Start(startInfo);

How to print Cyrillic PDF in C#? Text missing

I use iTextSharp to create document in my programs. All text in documents is Russian, I use Tahoma fonts:
private static void PrepareFonts()
{
_baseTahoma = BaseFont.CreateFont("c:/windows/fonts/tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
_tahomaBold = new Font(_baseTahoma, 10, Font.BOLD);
_tahoma = new Font(_baseTahoma, 10, Font.NORMAL);
_tahoma16Bold = new Font(_baseTahoma, 18, Font.BOLD);
_tahomaSmall = new Font(_baseTahoma, 8, Font.NORMAL);
}
When document is created, I print it on button click that way:
RegistryKey adobe = Registry.LocalMachine.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe");
if (adobe != null)
{
string path = adobe.GetValue("").ToString();
GenerateDocuments();
Process proc = new Process();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.Verb = "print";
string pdfFileName = _invoice.FullName;
proc.StartInfo.FileName = path;
proc.StartInfo.Arguments = #"/p /h " + pdfFileName;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (proc.HasExited == false)
{
if (!proc.WaitForExit(5000))
proc.Kill();
}
proc.EnableRaisingEvents = true;
proc.Close();
}
But on the paper there are only lines from tables without any characters. There's no text or numbers.
In requirements specification is written that user must print documents on button click and I have to do it that way. Manual opening document and "Print as image" are not possible.
Can anyone give suggestion, how can I print Cyrillic document?
#Drac When I open the file, I see Cyrillic characters; when I print the file (normal printing), I see Cyrillic characters. If some printer isn't able to print the document correctly, you need to look at your printer driver (maybe you're using the wrong one) or your printer.

Categories

Resources