I am new to C# windows forms.
I am trying to print the content of a Text file using the PrintDialog as shown in screenshot.
Screenshot
The following code is working correctly and it is printing but the printing process occurs immediately without opening the PrintDialog. I want to open the PrintDialog because I have 3 printers and I want to select a specific printer and when I click OK I want to print it.
Anyone knows how to modify this code so it can display the PrintDialog box so I can select a printer and continue printing?.
private void Print_Click(object sender, EventArgs e)
{
string filename = #"D:\\File1.txt";
//Create a StreamReader object
reader = new StreamReader(filename);
//Create a Verdana font with size 10
verdana10Font = new Font("Verdana", 10);
//Create a PrintDocument object
PrintDocument pd = new PrintDocument();
//Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
//Call Print Method
pd.Print();
//Close the reader
if (reader != null)
reader.Close();
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
{
//Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 0;
float topMargin = 50;
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 / verdana10Font.GetHeight(g);
//Now read lines one by one, using StreamReader
while (count < linesPerPage && ((line = reader.ReadLine()) != null))
{
//Calculate the starting position
yPos = topMargin + (count * verdana10Font.GetHeight(g));
//Draw text
g.DrawString(line, verdana10Font, 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;
}
}
You can do so using PrintDialog.
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
Complete Code
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
Related
using C#, I wrote the below code to print out images in an array (size = totalToPrint) of Picturebox pictureBoxArr[] each in size of 100x100 pixel. I want to print them vertically with the 20-pixel distance between them heightDistanceBetweenImages the problem is that it only prints on 1 page (say letter size) no matter how many images ( then it only prints 8 images and dismisses the rest). How can I solve this problem, and print it on multiple pages?
int totalToPrint;
int xFirstAncorPoint = 100;
int yFirstAncorPoint = 100;
int ImagSize = 100; // Squre of 100x100 pixel
int heightDistanceBetweenImages = 20;
PrintDialog pd = new PrintDialog();
PrintDocument pDoc = new PrintDocument();
pDoc.PrintPage += PrintPicture;
pd.Document = pDoc;
if (pd.ShowDialog() == DialogResult.OK)
{
pDoc.Print();
}
}
public void PrintPicture(Object sender, PrintPageEventArgs e)
{
Bitmap bmp1 = new Bitmap(ImagSize , totalToPrint * (ImagSize + heightDistanceBetweenImages));
for (int i = 0; i < totalToPrint; i++)
{
pictureBoxArr[i].DrawToBitmap(bmp1, new Rectangle(0, i * (heightDistanceBetweenImages + ImagSize), pictureBoxArr[0].Width, pictureBoxArr[0].Height));
}
e.Graphics.DrawImage(bmp1, xFirstAncorPoint, yFirstAncorPoint);
bmp1.Dispose();
}
You are about half way there. PrintDocument would be your future reference.
The PrintPage gives you more than just a drawing space; it also has your page bounds, page margins, etc. It also has HasMorePages property that you set if you need to print more pages. This property defaults to false, so you were only printing 1 page. Also if anything is outside the bounds of the page, it would not print that. With a little change here and there, you would end up with something like this.
// using queue to manage images to print
Queue<Image> printImages = new Queue<Image>();
int totalToPrint;
int xFirstAncorPoint = 100;
int yFirstAncorPoint = 100;
int ImagSize = 100; // Squre of 100x100 pixel
int heightDistanceBetweenImages = 20;
private void btnPrintTest_Click(object sender, EventArgs e) {
PrintDialog pd = new PrintDialog();
PrintDocument pDoc = new PrintDocument();
pDoc.PrintPage += PrintPicture;
pd.Document = pDoc;
if (pd.ShowDialog() == DialogResult.OK) {
// add image references to printImages queue.
for (int i = 0; i < pictureBoxArr.Length; i++) {
printImages.Enqueue(pictureBoxArr[i].Image);
}
pDoc.Print();
}
}
private void PrintPicture(object sender, PrintPageEventArgs e) {
int boundsHeight = e.MarginBounds.Height; // Get height of bounds that we are expected to print in.
int currentHeight = yFirstAncorPoint;
while (currentHeight <= boundsHeight && printImages.Count > 0) {
var nextImg = printImages.Peek();
int nextElementHeight = nextImg.Height + heightDistanceBetweenImages;
if (nextElementHeight + currentHeight <= boundsHeight) {
e.Graphics.DrawImage(nextImg, new PointF(xFirstAncorPoint, currentHeight + heightDistanceBetweenImages));
printImages.Dequeue();
}
currentHeight += nextElementHeight;
}
// how we specify if we may have more pages to print
e.HasMorePages = printImages.Count > 0;
}
Hopefully this gets you on the right path and with some minor tweaks for your code, you will have what you need.
I have been searching for long time to print formatted text and images which are in panel(PanelContain) but I have not get yet to print formatted text and images.Please tell me which text box support early I had used Rich text box but it does not convert in bitmap so I was getting blank text box.
Please help me.It is very very important for my project.
This is my code:
private void PrintPanel()
{
System.Drawing.Printing.PrintDocument doc = new PrintDocument();
doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
doc.Print();
}
private void doc_PrintPage(object sender, PrintPageEventArgs e)
{
try
{
RichTxtRptBody.BorderStyle = BorderStyle.None;
Bitmap bmp = new Bitmap(PanelContain.Width,
PanelContain.Height);
float tgtWidthMM = 210; //A4 paper size
float tgtHeightMM = 297;
float tgtWidthInches = tgtWidthMM / 25.4f;
float tgtHeightInches = tgtHeightMM / 25.4f;
float srcWidthPx = bmp.Width;
float srcHeightPx = bmp.Height;
float dpiX = srcWidthPx / tgtWidthInches;
float dpiY = srcHeightPx / tgtHeightInches;
bmp.SetResolution(dpiX, dpiY);
PanelContain.DrawToBitmap(bmp, PanelContain.ClientRectangle);
e.Graphics.InterpolationMode =
InterpolationMode.HighQualityBicubic;
e.Graphics.PageUnit = GraphicsUnit.Millimeter;
e.Graphics.DrawImage(bmp, 3, 1, tgtWidthMM, tgtHeightMM-24);
}
catch (Exception ex)
{
}
}
private void toolStripBtnPrint_Click(object sender, EventArgs e)
{
try
{
Img = null;
PrintDocument doc = new PrintDocument();
PrintDialog dlgSettings = new PrintDialog();
dlgSettings.Document = doc;
if (dlgSettings.ShowDialog() == DialogResult.OK)
{
PrintPanel();
}
}
catch (Exception ex)
{
}
}
I have also given a snapshot of my panel:
YOU can use webbrowsercontrol populate dynamically and then you can print easily as you want to print with full formatting option as html code can help you to give layout also.
You want to print a rich text box content with formatting
Try this :
Here eintragRichTextBox is a RichTextBox
private void druckenPictureBox_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
PrintDocument documentToPrint = new PrintDocument();
printDialog.Document = documentToPrint;
if (printDialog.ShowDialog() == DialogResult.OK)
{
StringReader reader = new StringReader(eintragRichTextBox.Text);
documentToPrint.PrintPage += new PrintPageEventHandler(DocumentToPrint_PrintPage);
documentToPrint.Print();
}
}
private void DocumentToPrint_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
StringReader reader = new StringReader(eintragRichTextBox.Text);
float LinesPerPage = 0;
float YPosition = 0;
int Count = 0;
float LeftMargin = e.MarginBounds.Left;
float TopMargin = e.MarginBounds.Top;
string Line = null;
Font PrintFont = this.eintragRichTextBox.Font;
SolidBrush PrintBrush = new SolidBrush(Color.Black);
LinesPerPage = e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);
while (Count < LinesPerPage && ((Line = reader.ReadLine()) != null))
{
YPosition = TopMargin + (Count * PrintFont.GetHeight(e.Graphics));
e.Graphics.DrawString(Line, PrintFont, PrintBrush, LeftMargin, YPosition, new StringFormat());
Count++;
}
if (Line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
PrintBrush.Dispose();
}
I am trying to set up an application in VS2013 with Page Setup, Print Preview and Print. The issue I am having is instead of seeing the page in the Print Preview window, all I see is "Document does not contain any pages." Everything I find on the Internet is regarding opening a file and printing/previewing it. I want to be able to print/preview unsaved text in a Rich Textbox.
Here is what I have:
PageSetupDialog psdlg = new PageSetupDialog();
PrintDialog pdlg = new PrintDialog();
PrintPreviewDialog ppdlg = new PrintPreviewDialog();
PrintDocument pd = new PrintDocument();
Event handlers:
private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
{
psdlg.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
psdlg.PageSettings = new System.Drawing.Printing.PageSettings();
psdlg.EnableMetric = false;
psdlg.ShowNetwork = true;
pd.PrinterSettings = psdlg.PrinterSettings;
psdlg.ShowDialog();
if (psdlg.PageSettings != null)
{
pd.DefaultPageSettings = psdlg.PageSettings;
}
}
private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ppdlg.ShowDialog() == DialogResult.OK)
{
pd.DocumentName = strCurrentFile;
ppdlg.Document = pd;
}
}
private void printToolStripMenuItem_Click(object sender, EventArgs e)
{
if(printDialog1.ShowDialog() == DialogResult.OK)
{
pd.PrintPage += new PrintPageEventHandler (pd_PrintPage);
pd.Print();
}
}
PrintPage Event Handler:
private void DocumentToPrint_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
StringReader reader = new StringReader(rtbMain.Text);
float LinesPerPage = 0;
float YPosition = 0;
int Count = 0;
float LeftMargin = e.MarginBounds.Left;
float TopMargin = e.MarginBounds.Top;
string Line = null;
Font PrintFont = this.rtbMain.Font;
SolidBrush PrintBrush = new SolidBrush(Color.Black);
LinesPerPage = e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);
while (Count < LinesPerPage && ((Line = reader.ReadLine()) != null))
{
YPosition = TopMargin + (Count * PrintFont.GetHeight(e.Graphics));
e.Graphics.DrawString(Line, PrintFont, PrintBrush, LeftMargin, YPosition, new StringFormat());
Count++;
}
if (Line != null)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
PrintBrush.Dispose();
}
i am trying to print this document but only gives me a blank page.
i have checked the Password.txt File is not empty so i dont know why its printing out a blank page . this is C# coding
private void button6_Click(object sender, EventArgs e)
{
StreamReader Printfile = new StreamReader("c:\\testDir1\\Password.txt);
try
{
PrintDocument docToPrint = new PrintDocument();
docToPrint.DocumentName = "Password";
printDialog1.AllowSomePages = true;
printDialog1.ShowHelp = true;
printDialog1.Document = docToPrint;
DialogResult result = printDialog1.ShowDialog();
printPreviewDialog1.Document = docToPrint;
printPreviewDialog1.ShowDialog();
Printfile.Close();
if (result == DialogResult.OK)
{
docToPrint.Print();
MessageBox.Show("Printing file");
}
}
catch (System.Exception f)
{
MessageBox.Show(f.Message);
}
finally
{
Printfile.Close();
}
}
The PritnDocument will fire the PrintPage event for every page that needs to be printed. You can hook into that event and "Draw" your page. In your case, draw a string for every line in the text file.
Font printFont = new Font("Arial", 10);
StreamReader Printfile;
private void button6_Click(object sender, EventArgs e)
{
using(StreamReader Printfile = new StreamReader("c:\\testDir1\\Password.txt")) //file path
{
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);
}
}
}
I am attempting to print something using a C# Winforms application. I can't seem to understand how multiple pages works. Let's say I have the following code in my constructor:
private string _stringToPrint;
_stringToPrint = "";
for (int i = 0; i < 120; i++)
{
_stringToPrint = _stringToPrint + "Line " + i.ToString() + Environment.NewLine;
}
Then I have this code on my button click event:
private void MnuFilePrintClick(object sender, EventArgs e)
{
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
var z = new PrintPreviewDialog { Document = pd };
z.ShowDialog(this);
}
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
var font = new Font("Arial", 10f, FontStyle.Regular);
g.DrawString(_stringToPrint, font, Brushes.Black, new PointF(10f, 10f));
}
Right now, when I run this code, it is giving me one page and after like 70 lines, it just runs off the paper. How would I print this string so that it prints enough for one page, then runs over to the second page, etc..?
You could have a counter and set the amount of lines you want per page like so:
private string[] _stringToPrint = new string[100]; // 100 is the amount of lines
private int counter = 0;
private int amtleft = _stringToPrint.Length;
private int amtperpage = 40; // The amount of lines per page
for (int i = 0; i < 120; i++)
{
_stringToPrint[i] ="Line " + i.ToString();
}
Then in pd_PrintPage:
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
int currentamt = (amtleft > 40)?40:amtleft;
Graphics g = e.Graphics;
var font = new Font("Arial", 10f, FontStyle.Regular);
for(int x = counter; x < (currentamt+counter); x++)
{
g.DrawString(_stringToPrint[x], font, Brushes.Black, new PointF(10f, (float)x*10));
// x*10 is just so the lines are printed downwards and not on top of each other
// For example Line 2 would be printed below Line 1 etc
}
counter+=currentamt;
amtleft-=currentamt;
if(amtleft<0)
e.HasMorePages = true;
else
e.HasMorePages = false;
// If e.HasMorePages is set to true and the 'PrintPage' has finished, it will print another page, else it wont
}
I have had bad experiences with e.HasMorePages so this may not work.
Let me know if this works and I hope it helps!