Multiple documents send to default printer queue order - c#

I am developing an application which is work as print agent without getting user interaction. In there, I have to consider about below conditions.
Download file shouldn't be access for user.
file sould be deleted after print it.
The download document could be either Image/PDF or word.docx
First downloaded file should be print first.
So far I able to complete as follow.
- watcher method created to catch up new download file.
public void catchDocuments()
{
if (!string.IsNullOrEmpty(Program.docDirectory))
{
file_watcher = new FileSystemWatcher();
file_watcher.Path = Program.docDirectory;
file_watcher.EnableRaisingEvents = true;
file_watcher.Created += new FileSystemEventHandler(OnChanged);
}
}
when new file came, it will fire Onchange event and print document.
string extension = Path.GetExtension(args.FullPath);
if (extension.Equals(#".png") || extension.Equals(#".jpeg") || extension.Equals(#".jpg"))
{
docCtrl.imageToByteArray(nFile);
docCtrl.printImage();
}
else if (extension.Equals(#".pdf"))
{
docCtrl.PrintPDF(nFile);
}
But My problem is, When another files download before complete print process of downloaded file, Application will not work properly.
I used print option as follow.
//For Image printing
public void printImage()
{
System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
pdi.PrinterSettings.PrinterName;
pd.Print();
}
//For PDF Printing
public void PrintPDF(string path)
{
PrintDialog pdf = new PrintDialog();
Process p = new Process();
pdf.AllowSelection = true;
pdf.AllowSomePages = true;
p.EnableRaisingEvents = true; //Important line of code
p.StartInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
Verb = "print",
FileName = path,
};
p.Start();
p.WaitForExit();
p.Close();
}
how could I overcome this issue. I'll be really appreciate your good thoughts.

Related

How can I make print process faster c#

Hello my app has a button to print listed documents. The list can be quite long, like 1000 documents.
PrintDialog printDialog = new PrintDialog();
DialogResult dialogResult = printDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
foreach (Datei datei in dateienList)
{
if (datei.dateiAuswählen == true)
{
PrinterSettings currentPrinterSettings = new PrinterSettings();
printDialog.PrinterSettings = currentPrinterSettings;
currentPrinterSettings.Copies = (short)datei.anzahlKopien;
ProcessStartInfo processInfo = new ProcessStartInfo()
{
Verb = "print",
CreateNoWindow = true,
FileName = datei.pfad,
WindowStyle = ProcessWindowStyle.Hidden
};
Process process = new Process();
process.StartInfo = processInfo;
process.Start();
process.WaitForInputIdle();
process.WaitForExit();
System.Threading.Thread.Sleep(5000);
}
}
}
At first I set Thread.Sleep timeout to 3000, but listed documents got printed out in a mixed order. So, I set it to 60000, assuming it has too little time to process the documents, but it takes way too long since every single document has to be opened, processed, and then closed even though it's set to be invisible.
Is there any solution to this problem? Or should I try another method to print out documents?

Duplicate process start doesn't react as expected

i'm trying to open a process with c# and react to it, when it's been closed. This work's for me:
private void StartProc()
{
var process = new System.Diagnostics.Process { StartInfo = { FileName = "PathTo.exe" } };
process.Start();
process.EnableRaisingEvents = true;
process.Exited += this.Editor_Exited;
}
private void Editor_Exited(object sender, EventArgs e)
{
MessageBox.Show("Process canceled");
}
Lets say I'm opening a text editor with this code. If there is already an instance of this text editor the code won't open a second instance and also jumps instant in the Editor_Exited Code.
I want the code to open a new instance and don't jump in the Editor_Exited code.
string processName = "PathTo.exe";
var process = new System.Diagnostics.Process { StartInfo = { FileName = processName } };
if (process.Start())
{
process.EnableRaisingEvents = true;
process.Exited += this.Editor_Exited;
}
else
{
var p = Process.GetProcessesByName(processName);
p.WaitForExit();
}
I get this is not 100% what you are asking for, but its a work around

printer fails to print when millions of data points sent in a PrintDocument

Presently, I am attempting to print a data plot created using C#/.NET and GDI+ that has millions of data points. When the document goes to the printer, the printer says it successfully printed the document and that it printed 0 pages. The document never does get printed. Here is some of my code:
private void btnPrint_Click(object sender, EventArgs e)
{
if (_config == null)
{
lblStatus.Text = "Error, config is null";
return;
}
_pd = new PrintDocument();
//PaperSize paperSize = new PaperSize("CustomTest", 1000, 100);
//_pd.DefaultPageSettings.PaperSize = paperSize;
_pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
// Add event handler
_pd.PrintPage += new PrintPageEventHandler(PrintPage);
_pd.BeginPrint += new PrintEventHandler(BeginPrinting);
// Construct print dialog
PrintDialog pDialog = new PrintDialog();
pDialog.AllowSomePages = true;
pDialog.ShowHelp = true;
pDialog.Document = _pd;
// Ask the user for input
DialogResult result = pDialog.ShowDialog();
// Print if user desires
if (result == DialogResult.OK)
{
_pd.Print();
}
}
Does anyone have any suggestions? TIA.
It turned out the corporate print spooler was getting in the way. The solution was to bypass the corporate print system and print directly to the printer, by adding the printer by IP address. It was the PCL6 driver that didn't work.

Changing printer settings

So I have the code below and when the dialog opens, it shows the printer settings have change to print double sided but when i click ok and prints, it does not prints double sided but but when i manually select double sided it does print correctly. any ideas what might be the case? Thanks in advance for your help. ASP.NET WEB Application
using (PrintDialog pd = new PrintDialog())
{
PrinterSettings ps = new PrinterSettings();
ps.Duplex = Duplex.Horizontal;
pd.PrinterSettings = ps;
// pd.UseEXDialog = true;
if (pd.ShowDialog() == DialogResult.OK)
{
ProcessStartInfo info = new ProcessStartInfo(filePath);
info.Verb = "Print";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(info);
}
}
you can do this checking PrinterSettings.CanDuplex Property. Just set
PrinterSettings settings = new PrinterSettings();
and check if your printer supports it.
This property gets a value indicating whether the printer supports double-sided printing.
It returns true if the printer supports double-sided printing; otherwise, false.
You could simply do it like this:
PrintDialog pd = new PrintDialog();
PrintDocument MyPrintDocument = new PrintDocument();
MyPrintDocument.PrintPage += new PrintPageEventHandler(PrintPageEvent);
pd.PrinterSettings.PrintRange = PrintRange.AllPages;
MyPrintDocument.PrinterSettings.PrintRange = PrintRange.AllPages;
MyPrintDocument.Print();
where PrintPageEvent is the event triggered on Print();

Pull Up Print Dialog In Notepad

What I'm trying to do is create a Windows Journal (.jrn) file from a .txt. This conversion can be done by printing to a virtual "Journal Note Writer" printer. I've been struggling with a few different methods of getting this to work for a while now, so I've decided to try to simplify things (I hope).
What I Currently Have
Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
FileName = fileToOpen, // My .txt file I'd like to convert to a .jrn
CreateNoWindow = true,
Arguments = "-print-dialog -exit-on-print"
};
p.Start();
This opens the file in Notepad, but does not open the print dialog. I'd like for the print dialog to open and ideally to be able to specify some default options in the print dialog.
Another thing I've tried is this (found in another SO question):
Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
CreateNoWindow = true,
Verb = "print",
FileName = fileToOpen
};
p.Start( );
The problem with this is that it just automatically prints the file to the default printer (a physical one) without giving me the option to change it.
What I'm Looking For
At this point I'm just looking for any way to print a .txt to "Windows Note Writer." I've tried doing the printing without going through an external application, and had some trouble with that as well. I haven't been able to find any other references to converting to a .jrn file, so I'm open to ANY ideas.
To get Journal Note Writer as printer you would have to add it into the printer preferences -> Add Printer (I wonder whether it could be done programmatically).
Anyways you can always get a print of a plain .txt file as described here at MSDN.
After struggling with this issue for a while, I decided to go back to trying the handle the printing directly through the application without going through Notepad. The issue I was having before when I tried this was that changing the paper size would break the resulting .jrn file (the printout would be blank). It turns out that changing some paper size settings was necessary to print on a non-native paper size.
Below is the final code in case anybody else struggles with this issue. Thanks for everybody's help.
private void btnOpenAsJRN_Click(object sender, EventArgs e) {
string fileToOpen = this.localDownloadPath + "\\" + this.filenameToDownload;
//Create a StreamReader object
reader = new StreamReader(fileToOpen);
//Create a Verdana font with size 10
lucida10Font = new Font("Lucida Console", 10);
//Create a PrintDocument object
PrintDocument pd = new PrintDocument();
PaperSize paperSize = new PaperSize("Custom", 400, 1097);
paperSize.RawKind = (int)PaperKind.Custom;
pd.DefaultPageSettings.PaperSize = paperSize;
pd.DefaultPageSettings.Margins = new Margins(20, 20, 30, 30);
pd.PrinterSettings.PrinterName = ConfigurationManager.AppSettings["journalNotePrinter"];
pd.DocumentName = this.filenameToDownload;
//Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
//Call Print Method
try {
pd.Print();
}
finally {
//Close the reader
if (reader != null) {
reader.Close();
}
this.savedJnt = fileToOpen.Replace("txt", "jnt");
System.Threading.Thread.Sleep(1000);
if (File.Exists(this.savedJnt)) {
lblJntSaved.Visible = true;
lblJntSaved.ForeColor = Color.Green;
lblJntSaved.Text = "File successfully located.";
// If the file can be found, show all of the buttons for completing
// the final steps.
lblFinalStep.Visible = true;
btnMoveToSmoketown.Visible = true;
btnEmail.Visible = true;
txbEmailAddress.Visible = true;
}
else {
lblJntSaved.Visible = true;
lblJntSaved.ForeColor = Color.Red;
lblJntSaved.Text = "File could not be located. Please check your .jnt location.";
}
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs) {
//Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
//Read margins from PrintPageEventArgs
float leftMargin = ppeArgs.MarginBounds.Left;
float topMargin = ppeArgs.MarginBounds.Top;
string line = null;
//Calculate the lines per page on the basis of the height of the page and the height of the font
linesPerPage = ppeArgs.MarginBounds.Height /
lucida10Font.GetHeight(g);
//Now read lines one by one, using StreamReader
while (count < linesPerPage &&
((line = reader.ReadLine()) != null)) {
//Calculate the starting position
yPos = topMargin + (count *
lucida10Font.GetHeight(g));
//Draw text
g.DrawString(line, lucida10Font, Brushes.Black,
leftMargin, yPos, new StringFormat());
//Move to next line
count++;
}
//If PrintPageEventArgs has more pages to print
if (line != null) {
ppeArgs.HasMorePages = true;
}
else {
ppeArgs.HasMorePages = false;
}
}

Categories

Resources