Pull Up Print Dialog In Notepad - c#

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;
}
}

Related

Printing from a preview (PrintPreviewDialog) without calling PrintPageEventHandler again, and recreating the PrintDocument

I'm certain I'm missing something here...
I create a PrintDocument (which is very time consuming 600-1200 pages), and then allow the user to preview it with PrintPreviewDialog.
However, when the user chooses to print the document (from the preview dialog) the print document gets created again. I just want the document that has been created, previewed, accepted by the user, to be printed. How do I print the created document directly?
The code is simply this...
PageSettings pageSettings = new PageSettings();
pageSettings.Margins.Top = 40;
pageSettings.Margins.Bottom = 40;
pageSettings.Margins.Left = 40;
pageSettings.Margins.Right = 40;
LoadChartsBook chartsBook = new LoadChartsBook(chartsData);
PrintDocument docToPrint = chartsBook.CreatePrintDocument();
docToPrint.DefaultPageSettings = pageSettings;
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = docToPrint;
previewDialog.ShowDialog();
Then the called code for CreatePrintDocument()
public PrintDocument CreatePrintDocument()
{
index.resetCounter();
coverPagePrinted = false;
currentChartIndex = 0;
pageNumber = 0;
PrintDocument printDocument = new PrintDocument();
printDocument.DocumentName = (index.totalEntries()+1).ToString() + ", of Load Charts Book: " + chartBookID;
printDocument.PrintPage += new PrintPageEventHandler(PrintLoadChartsBookEventHandler);
return printDocument;
}
Each chart is very processor intensive and hence time consuming to create, I need to avoid this apparent second call to CreatePrintDocument() but can't see why it's being called in again anyway.
Am I missing a setting in the preview dialog?
Any help appreciated.

Print Ribbon using PrintDialog

that drives me nuts. I try to silent print a ribbon (1000 mm height, 150 mm width). The content is a Canvas containing a formatted Text.
If I use "Microsoft Print To PDF" it works and looks OK. When i go on and use the OKI Printer from the pdf it is fine!
If I directly try to print using the OKI, I will get a blank ribbon or (if i change some parameters) I get a very small text in the middle of nowhere.
Any ideas? Unfortunatly it is nearly impossible to Debug.
This is the print function:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
PrintDialog prnt = new PrintDialog();
//PrintQueue queue = new LocalPrintServer().GetPrintQueue("Microsoft Print To PDF");
PrintQueue queue = new LocalPrintServer().GetPrintQueue("OKI C3450");
prnt.PrintQueue = queue;
//var f = queue.GetPrintCapabilities();
prnt.PrintTicket = new PrintTicket();
prnt.PrintTicket.PageMediaSize = new PageMediaSize(3779.53, 566.93);
prnt.PrintTicket.PageOrientation = PageOrientation.Landscape;
//if (prnt.ShowDialog() == true)
//{
Size pageSize = new Size(3779.53, 566.93);
var canvasToPrint = this.backgroundCanvasSchleife1;
this.backgroundCanvasSchleife1.Measure(pageSize);
this.backgroundCanvasSchleife1.Background = new SolidColorBrush(Colors.Transparent);
this.backgroundCanvasSchleife1.Children.RemoveRange(0, this.backgroundCanvasSchleife1.Children.Count-1);
this.backgroundCanvasSchleife1.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));
//if (prnt.ShowDialog() == true)
//{
// try
//{
prnt.PrintVisual(this.backgroundCanvasSchleife1, "Printing Canvas");
//}catch (Exception ex)
//{
// var t = ex;
//}
//}
//}
//this.Close();
}

Multiple documents send to default printer queue order

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.

Printing to a thermal printer with ASP.NET C# WebForms (4.5)

I have a requirement for a project at work to print to a thermal printer (specifically a Citizen CT-S651) that is attached to the computer via USB from ASP.NET C# Webforms. So far, I have tried a few things and did a lot of research. The main three things I have tried was using QZ Tray (formerly known as JZebra, found here https://qz.io/), however the non-free version costs too much right now, and the free version is too annoying in its popups to be of much use right now. I also tried to generate a PDF using MigraDoc (http://www.pdfsharp.net/), but when I try to print to the printer, it uses far too much paper before it even prints "Hello World" code for that shown below:
private void print()
{
Document document = CreateDocument();
document.UseCmykColor = true;
const bool unicode = false;
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
//pdfRenderer.Save("C:/Users/jamesl/Documents/Visual Studio 2013/Projects/TestCheckScanner/TestCheckScanner/TestDocument.pdf");
MemoryStream stream = new MemoryStream();
pdfRenderer.PdfDocument.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();
}
private Document CreateDocument()
{
Document document = new Document();
MigraDoc.DocumentObjectModel.Unit width, height;
width = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(80);
height = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(50);
Section section = document.AddSection();
section.PageSetup.PageHeight = height;
section.PageSetup.PageWidth = width;
section.PageSetup.PageHeight = height;
section.PageSetup.PageWidth = width;
section.PageSetup.LeftMargin = 0;
section.PageSetup.RightMargin = 0;
section.PageSetup.TopMargin = 0;
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black; //Same as System.Drawing.Color
paragraph.AddFormattedText("Hello, World!");
return document;
}
Since that hasn't worked very well, I have gotten it to print a little bit using PrintDocument, however, the main problems I have with this way are twofold: 1. Formatting it print a proper receipt is going to be very tedious although if it is ends up being the best way with my current constraints I am all for it. 2. This method only works if I print from Visual Studio, when I try it on the test web app I have set up on a server, I get an error of "Settings to access printer 'CITIZEN CT-S651' are not valid." Here is my code for that:
private void print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.PrinterSettings.PrinterName = "CITIZEN CT-S651";
pd.Print();
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.End();
}
}
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Test Print", new System.Drawing.Font("Arial", 12), new SolidBrush(Color.Black), 60, 0);
e.Graphics.DrawString("Test Again", new System.Drawing.Font("Arial", 12), new SolidBrush(Color.Black), 60, 20);
}
Any help you can give on this matter would be awesome!

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.

Categories

Resources