Showing Print Preview in C# - c#

Right now, I'm trying to build my form on a PrintDocument, but the only way for me to see where stuff is actually appearing on the page is to print a paper. It works, but I have a lot of stuff I need to add, and I'd rather not waste tons of paper. Right now I have a print dialogue come up, but theres no print preview button. Is there a way I can make one appear? Thanks!
public partial class Form4 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components;
private System.Windows.Forms.Button printButton;
public Form4()
{
// The Windows Forms Designer requires the following call.
InitializeComponent();
}
// The Click event is raised when the user clicks the Print button.
private void printButton_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
if (pdi.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
Single yPos = 0;
Single leftMargin = e.MarginBounds.Left;
Single topMargin = e.MarginBounds.Top;
Image img = Image.FromFile("logo.bmp");
Rectangle logo = new Rectangle(40, 40, 50, 50);
using (Font printFont = new Font("Arial", 20.0f))
{
e.Graphics.DrawImage(img, logo);
e.Graphics.DrawString("Header", printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
}
using (SolidBrush blueBrush = new SolidBrush(Color.Black))
{
Rectangle rect = new Rectangle(100, 100, 500, 120);
e.Graphics.FillRectangle(blueBrush, rect);
}
}
// The Windows Forms Designer requires the following procedure.
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.printButton = new System.Windows.Forms.Button();
this.ClientSize = new System.Drawing.Size(504, 381);
this.Text = "Print Example";
printButton.ImageAlign =
System.Drawing.ContentAlignment.MiddleLeft;
printButton.Location = new System.Drawing.Point(32, 110);
printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
printButton.TabIndex = 0;
printButton.Text = "Print the file.";
printButton.Size = new System.Drawing.Size(136, 40);
printButton.Click += new System.EventHandler(printButton_Click);
this.Controls.Add(printButton);
}
}

You can use a PrintPreviewDialog for this:
private void printButton_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
PrintDialog printdlg = new PrintDialog();
PrintPreviewDialog printPrvDlg = new PrintPreviewDialog();
// preview the assigned document or you can create a different previewButton for it
printPrvDlg.Document = pd;
printPrvDlg.ShowDialog(); // this shows the preview and then show the Printer Dlg below
printdlg.Document = pd;
if (printdlg.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}

Related

Label printer not printing correctly starts from the begining instead of the end

I have the following code, but its printing from the start of the label and trying to print forward when it should start from the end of the label and print forward.. I have an image below for reference, I have looked on stackoverflow for similar questions but no luck. Thank you for your time and efforts to help me.
using System;
using System.Drawing;
using System.Drawing.Printing;
using Gtk;
public partial class MainWindow : Gtk.Window
{
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
public void Print()
{
using (PrintDocument pd = new PrintDocument())
{
var width = 2.44 * 100;
var height = 100;
var s = new System.Drawing.Printing.PaperSize("Custom", (int)width, (int)height);
pd.DefaultPageSettings.PaperSize = s;
pd.DefaultPageSettings.Landscape = true;
pd.DocumentName = "Label";
pd.OriginAtMargins = true;
pd.PrintPage += Pd_PrintPage;
pd.Print();
}
}
private void Pd_PrintPage(object sender, PrintPageEventArgs e)
{
Font drawFont = new Font("Arial", 60);
SolidBrush drawBrush = new SolidBrush(Color.Black);
StringFormat drawFormat = new StringFormat();
e.HasMorePages = false;
e.Graphics.DrawString(LabelPreview.Buffer.Text, drawFont, drawBrush, 0, 0, drawFormat);
}
protected void OnButton1Released(object sender, EventArgs e)
{
Print();
}
}
Here is the image
Please try to add pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0); after pd.OriginAtMargins = true;.
The default value of pd.DefaultPageSettings.Margins is 1-inch margins on all sides.

How can I check if user has cancelled printing from printing queue?

I am trying to print a WPF component through XPS document writer, There are lots of pages (in 100). It takes lot of time to print. That is why I used Thread.Sleep to simulate that. While printing those pages. User can cancel the print from print queue of windows. I can print it easily but if user cancel it. It throws an exception at
collator.EndBatchWrite();
Exception Message
private void Print_Click(object sender, RoutedEventArgs e)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
PrintQueue printQueue = printDialog.PrintQueue;
XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printQueue);
SerializerWriterCollator collator = writer.CreateVisualsCollator();
collator.BeginBatchWrite();
collator.Write(VisualLE());
Thread.Sleep(20000);
collator.Write(VisualLE());
collator.EndBatchWrite();
}
}
private static ContainerVisual VisualLE()
{
ContainerVisual newPage = new ContainerVisual();
FixedPage fixedPage;
Border border = new Border();
border.Height = 400;
border.Width = 400;
border.BorderThickness = new Thickness(1);
border.BorderBrush = new SolidColorBrush(Color.FromRgb(1, 1, 1));
fixedPage = new FixedPage();
Size size = new Size(600, 600);
fixedPage.Height = size.Height;
fixedPage.Width = size.Width;
fixedPage.Children.Add(border);
fixedPage.Measure(size);
fixedPage.Arrange(new Rect(new Point(), size));
fixedPage.UpdateLayout();
newPage.Children.Add(fixedPage);
return newPage;
}
Printing Queue

Print an image multiple times on the same sheet c#

Hi I would like to print a product barcode in a sheet but if the user write 6 products on stock it must print 6 times this code on the sheet, I have a code but it prints just one code per image, please see it below.
private void generar_codigo_btn_Click(object sender, EventArgs e)
{
string codigo_generado = nom_prd_txt.Text;
BarcodeLib.Barcode Codigo = new BarcodeLib.Barcode();
Codigo.IncludeLabel = true;
codigo_pic.BackgroundImage = Codigo.Encode(BarcodeLib.TYPE.CODE128, codigo_generado, Color.Black, Color.White, 173, 102);
PrintDialog pd = new PrintDialog();
PrintDocument doc = new PrintDocument();
doc.PrintPage += Doc_PrintPage;
pd.Document = doc;
if (pd.ShowDialog() == DialogResult.OK)
doc.Print();
}
private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bm = new Bitmap(codigo_pic.Width, codigo_pic.Height);
codigo_pic.DrawToBitmap(bm, new Rectangle(5, 5, codigo_pic.Width, codigo_pic.Height));
e.Graphics.DrawImage(bm, 0, 0);
bm.Dispose();
}
You have to draw your bar-code multiple times in bitmap
int NoOfTimesToPrint = 5;
private void Doc_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bm = new Bitmap(codigo_pic.Width, codigo_pic.Height);
for(int i=1;i<=NoOfTimesToPrint;i++)
{
codigo_pic.DrawToBitmap(bm, new Rectangle(5, i*5, codigo_pic.Width, codigo_pic.Height));
}
e.Graphics.DrawImage(bm, 0, 0);
bm.Dispose();
}
Please Note you have to Change NoOfTimesToPrint variable in order to work this code as you need
int NumOfLabel = Convert.ToInt16(textBox_StockAddQuntity_StockEntry.Text); /* here for example i set to total copy */
PrintDialog pDlg = new PrintDialog();
pDlg.Document = printDocument_Barcode;
pDlg.AllowSelection = true;
pDlg.AllowSomePages = true;
pDlg.PrinterSettings.Copies = (short)NumOfLabel;
printDocument_Barcode.Print();

How to print a panel in WinFormc#?

I have a panel which have labels and a datagridview. I'm trying to print the panel with its contents using this code
PrintDialog myPrintDialog = new PrintDialog();
System.Drawing.Bitmap memoryImage = new System.Drawing.Bitmap(panel2.Width, panel2.Height);
panel2.DrawToBitmap(memoryImage, panel2.ClientRectangle);
myPrintDialog.ShowDialog();
System.Drawing.Printing.PrinterSettings values;
values = myPrintDialog.PrinterSettings;
myPrintDialog.Document = printDocument1;
printDocument1.PrintController = new StandardPrintController();
printDocument1.Print();
printDocument1.Dispose();
But it prints nothing. I remove the datagridview but still prints nothing. Then I change the panel back color but again it prints white page. Kindly Guide me How I do this?
Add this code to PrintPage event and call the Print() method from PrintDocument class object
private void doc_PrintPage(object sender, PrintPageEventArgs e)
{
float x = e.MarginBounds.Left;
float y = e.MarginBounds.Top;
Bitmap bmp = new Bitmap(panel2.Width, panel2.Height);
panel2.DrawToBitmap(bmp, new Rectangle(0, 0, panel2.Width, panel2.Height));
e.Graphics.DrawImage((Image)bmp, x, y);
}
Call the method like this
PrintDocument doc = new PrintDocument();
doc.PrintPage += this.doc_PrintPage;
PrintDialog dlg = new PrintDialog();
dlg.Document = doc;
if (dlg.ShowDialog() == DialogResult.OK)
{
doc.Print();
}

Centering OK button within a MessageBox in winforms

I am learning C#, and as a part of it I wrote small app that consists of form with two groups of buttons, two buttons each. Button for closing of app is added as well. And everything works ok. Also there is MessageBox, showing that the app is going to be closed. And here is little problem that bugs me: OK button within that MessageBox is NOT centered horizontally. I guess there is a method to align that button, but what puzzles me is why it's is not centered by default? As illustration here are screenshots:
Here is code as well:
using System;
using System.Drawing;
using System.Windows.Forms;
public class myForm : Form
{
private GroupBox gboxGrp1;
private GroupBox gboxGrp2;
private RadioButton butn1a;
private RadioButton butn1b;
private RadioButton butn2a;
private RadioButton butn2b;
private Button btnClose;
public myForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.btnClose = new Button();
this.gboxGrp1 = new GroupBox();
this.gboxGrp2 = new GroupBox();
this.butn1a = new RadioButton();
this.butn1b = new RadioButton();
this.butn2a = new RadioButton();
this.butn2b = new RadioButton();
//myForm
this.Text = "My Form";
this.StartPosition = FormStartPosition.CenterScreen;
this.Height = 350;
this.Width = 200;
//btnClose
this.Controls.Add(btnClose);
this.btnClose.Text = "Close";
this.btnClose.Location = new Point(60, 260);
this.btnClose.Click += new EventHandler(btnClose_Click);
//gboxgrp1
this.gboxGrp1.Location = new Point(20, 20);
this.gboxGrp1.Text = "Group Box 1";
this.gboxGrp1.Width = 150;
this.gboxGrp1.Height = 100;
//gboxgrp2
this.gboxGrp2.Text = "Group Box 2";
this.gboxGrp2.Location = new Point(20, 130);
this.gboxGrp2.Width = 150;
this.gboxGrp2.Height = 100;
//Radio buttons
this.butn1a.Text = "Radio 1a";
this.butn1a.Location = new Point(30, 30);
this.butn1a.Size = new Size(90, 15);
this.butn1b.Text = "Radio 1b";
this.butn1b.Location = new Point(30, 60);
this.butn1b.Size = new Size(90, 15);
this.butn2a.Text = "Radio 2a";
this.butn2a.Location = new Point(30, 30);
this.butn2a.Size = new Size(90, 15);
this.butn2b.Text = "Radio 2b";
this.butn2b.Location = new Point(30, 70);
this.butn2b.Size = new Size(90, 15);
//Controls
this.Controls.Add(gboxGrp1);
this.Controls.Add(gboxGrp2);
this.gboxGrp1.Controls.Add(butn1a);
this.gboxGrp1.Controls.Add(butn1b);
this.gboxGrp2.Controls.Add(butn2a);
this.gboxGrp2.Controls.Add(butn2b);
}
private void btnClose_Click(object sender, EventArgs e)
{
MessageBox.Show("Closing Application");
Application.Exit();
}
}
public class MyApp
{
public static void Main()
{
Application.Run(new myForm());
}
}
You can't restyle the default MessageBox as that's completely depends on the windows OS theme. However you could create your own message box by simply creating a new form and then call it by using newMessagebox.ShowDialog();

Categories