Print .rtf or .txt file from PRINT button? - c#

I am making a simple work note pad test program. I want to be able to click on a menu item in the menutool bar (Print) and have the document print to my printer. The following code is what I use but I am not sure if this is all that I need for a simple print. I am new to C# and thus not complete familiar with the printDocument class.
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
StreamReader streamToPrint = new StreamReader
("C:\\My Documents\\MyFile.txt");
try
{
Font printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(myFileName);
pd.Print();
}
finally
{
streamToPrint.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

Problem : You are not handling the PrintPagEvent properly.
Solution : to print the document you need to handle the PrintPageEvent properly by writing the PrintPageEvent Handler.
String content="";
Font printFont = new Font("Arial", 10);
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
content= File.ReadAllText("C:\\My Documents\\MyFile.txt");
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
pd.Print();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.Graphics.DrawString(content,printFont , Brushes.Black,
ev.MarginBounds.Left, 0, new StringFormat());
}

Related

Programmatically print to PDF using "Microsoft Print to PDF" in c# windows 10

I am trying to print to pdf using "Microsoft Print to PDF" in c#. I worked really hard on it and wrote below code.
It is creating an empty pdf file instead of filling it with the content of I sent to the printer.
Could anyone help me?
try
{
PrintDocument pd = new PrintDocument();
ProcessStartInfo info = new ProcessStartInfo("E:\\ba\\Asp.pdf");
info.Verb = "Print";
pd.PrinterSettings.PrintToFile = true;
pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
pd.PrinterSettings.PrintToFile = true;
pd.PrinterSettings.PrintFileName = Path.Combine("e://", "hktespri" + ".pdf");
pd.Print();
info.CreateNoWindow = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
you have not given what to print to the pdf document.
heres my code I am using it for having my panel to print
protected void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
pdoc.PrintPage += pdoc_PrintPage;
if (pd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
pdoc.Print();
}
}
void pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bitmap = new Bitmap(outerPanel.Width, outerPanel.Height);
outerPanel.DrawToBitmap(bitmap, new System.Drawing.Rectangle(5, 5, outerPanel.Width, outerPanel.Height));
e.Graphics.DrawImage(bitmap, 5, 5);
bitmap.Dispose();
}

C# Printing invoices from a generated, formatted string, one invoice per printer page

I've generated a single long string of invoices formatted as required. I now need to print them out on a printer with one invoice displayed per page.
I've looked at these tutorials/help as well as some code I was:
https://msdn.microsoft.com/en-us/library/cwbe712d%28v=vs.110%29.aspx
https://social.msdn.microsoft.com/Forums/en-US/93e54c4f-fd07-4b60-9922-102439292f52/c-printing-a-string-to-printer?forum=csharplanguage
I've primarily followed the second one.
What I've ended up with is (Working VS C# project with a single form with a single button):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestPrint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string stringToPrint = "Hello\r\nWorld\r\n\r\n<<< Page >>>World\r\nHello";
private void button1_Click(object sender, EventArgs e)
{
// Convert string to strings
string[] seperatingChars = { "<<< Page >>>" };
string[] printString = stringToPrint.Split(seperatingChars, System.StringSplitOptions.RemoveEmptyEntries);
// Connect to the printer
PrintDocument printDocument1 = new PrintDocument(); // Stream to the printer
// Send to printer (reference: https://social.msdn.microsoft.com/Forums/en-US/93e54c4f-fd07-4b60-9922-102439292f52/c-printing-a-string-to-printer?forum=csharplanguage)
foreach (string s in printString)
{
printDocument1.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(s, new Font("Times New Roman", 12), new SolidBrush(Color.Black),
new RectangleF(0, 0, printDocument1.DefaultPageSettings.PrintableArea.Width,
printDocument1.DefaultPageSettings.PrintableArea.Height));
};
try
{
printDocument1.Print();
printDocument1.Dispose();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
}
}
}
I break the long string into it's parts that I want printed to each individual page and then sent that to the printer. This works fine for the first invoice/page but after that it just adds each page on to image of the first (I added the printDocument1.Dispose(); to try and sort that but that didn't work).
What I want to know is how can I print the string as a single string while keeping one invoice per page.
EDIT: How do I generate the string as multi-page image for the printer?
EDIT: complete solution.
public partial class Form1 : Form
{
//string to print
private string stringToPrint = "Hello\r\nWorld\r\n\r\n<<< Page >>>World\r\nHello";
//list of strings/pages
private List<string> pageData = new List<string>();
//enumerator for iteration thru "pages"
private IEnumerator pageEnumerator;
//print document
PrintDocument printDocument1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Connect to the printer
printDocument1 = new PrintDocument();
//handle events
printDocument1.BeginPrint += new PrintEventHandler(BeginPrint);
printDocument1.PrintPage += new PrintPageEventHandler(PrintPage);
try
{
//do print
printDocument1.Print();
printDocument1.Dispose();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
void BeginPrint(object sender, PrintEventArgs e)
{
// Convert string to strings
string[] seperatingChars = { "<<< Page >>>" };
//generate some dummy strings to print
pageData = stringToPrint.Split(seperatingChars, System.StringSplitOptions.RemoveEmptyEntries).ToList();
// get enumerator for dummy strings
pageEnumerator = pageData.GetEnumerator();
//position to first string to print (i.e. first page)
pageEnumerator.MoveNext();
}
private void PrintPage(object sender, PrintPageEventArgs e)
{
//define font, brush, and print area
Font font = new Font("Times New Roman", 12);
Brush brush = Brushes.Black;
RectangleF area = new RectangleF(0, 0, printDocument1.DefaultPageSettings.PrintableArea.Width,
printDocument1.DefaultPageSettings.PrintableArea.Height);
//print current page
e.Graphics.DrawString(pageEnumerator.Current.ToString(), font, brush, area);
// advance enumerator to determine if we have more pages.
e.HasMorePages = pageEnumerator.MoveNext();
}
}
From what I can see, this line is causing the problem that you described:
printDocument1.PrintPage += delegate(object sender1,
PrintPageEventArgs e1)
Try changing it to:
printDocument1.PrintPage = delegate(object sender1,
PrintPageEventArgs e1)

C# - Use Windows 10 'Microsoft Print to PDF' for multiple images

I want to print multiple images to a pdf file, but not using the regular print-dialogue, but the 'print pictures' dialogue (see image below). As a printer, I want to use the 'Microsoft print to PDF'-Printer, which comes with windows 10.
My current code looks like this:
string fileName = #"C:\Users\mt\Pictures\test\test.jpg";
var p = new Process();
p.StartInfo.FileName = fileName;
p.StartInfo.Verb = "Print";
p.Start();
So far so good, the right dialogue is showing. I tried it first with other methods, which didn't give me this one. I can now print one image to a pdf page, but how do I add other images? Additionally, in this solution, I can't see how to set the printing-settings, like size of the image, which should be as large as possible without cutting the image and changing to horizontal format.
Earlier, I had this code:
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.PrinterSettings.PrinterName = STR_PRINTER_NAME;
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromFile(#"C:\Users\mt\Pictures\test\1.jpg");
Point loc = new Point(100, 100);
e.Graphics.DrawImage(img, loc);
img.Dispose();
}
which I changed for the 'Print Picture'-Dialog. In the end, the dialog itself doesn't matter, but the 'Print Picture'-Dialog got all settings I need. The only thing the user has to set, is the name for the pdf-file.
Solved the 'Multiple-Page' problem with the following code:
private void button1_Click(object sender, EventArgs e)
{
imgs.Add(img1);
imgs.Add(img2);
imgs.Add(img3);
imgs.Add(img4);
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
Point p = new Point(10, 10);
Image img = Image.FromFile(imgs.ElementAt(page));
graphic.DrawImage(img, p);
page++;
e.HasMorePages = page < imgs.Count;
img.Dispose();
}
Still couldn't figure out how to set maximum size

Printpreview controller does not display the file

I have the codes below
fName =E:\Csharp\NewMacaron\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\\data00.txt"
From a method within my program I create, into application folder, a series of datas as fName above
After lunching the printing form I have the printcontroller preview on screen with Previous Next and some other buttons for printing and zooming.
On form_load I have ShowPage();
PrintPageEventHandler does not work and nothing is displayed.
However when I click the print_button correct page is printed:
What is wrong with the printpreviewcontroller ?
I'am using .net 3.5 and c# 2008
private void ShowPage()
{
try
{
streamToPrint = new StreamReader(fName, Encoding.UTF8);
pd = new PrintDocument();
pd.DocumentName = fName;
PrinterSettings ps = new PrinterSettings();
printFont = new Font("Courier", 10);
pd.PrinterSettings.PrinterName = prnName; // GetDefaultPrinter returns prName
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("PaperA4", 840, 1180);
ppc = new PrintPreviewControl();
ppc.Document = pd;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
}
catch (Exception es)
{
MessageBox.Show(es.Message.ToString());
}
}
private void print_button(object sender, EventArgs e)
{
streamToPrint = new StreamReader(fName, Encoding.UTF8);
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
try
{
pd.Print();
}
catch (Win32Exception es)
{
MessageBox.Show(es.Message.ToString());
streamToPrint.Close();
}
streamToPrint.Close();
PublicVariables.PrintFormStat = false;
PublicVariables.PrintData = 0;
this.Hide();
I have a CRIMINAL BUG in the program the printform was named ppc and the printpreviewcontroller also.
I don't know how assembly has accepted that.
After the correction of that tI can only use one time printpreviewcontroller
The second page is not displayed.

How to Print with Margins

I am making a Wordpad program. I am making this feature in which you click this button, and it prints to your default printer. I have done some research, and I found some functional code that prints to my printer:
private void buttonPrint_Click(object sender, EventArgs e)
{
string print = "" + textBody.Text;
PrintDocument p = new PrintDocument();
p.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(print, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));
};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
}
This works currently, but I was wondering if I could make it WITH margins, which it does not have now. All it does is this:
<Top of Page>
<Message>
There are no margins on the top, sides (left,right), and bottom. How can I modify my code to have margins?
On the PrintDocument you can set the Margins on the DefaultPageSettings object:
Margins margins = new Margins(100,100,100,100);
p.DefaultPageSettings.Margins = margins;

Categories