I want to print UserControl that contains labels, barcode, and a datagridview but when I want to print it on paper it is blury. But when i print it to PDF it's clean. Here is my code:
{
Graphics g = control.CreateGraphics();
var bitmap = new Bitmap(control.Width, control.Height, g);
bitmap.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
control.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, control.Width, control.Height));
var pd = new PrintDocument();
pd.PrintPage += (s, e) => e.Graphics.DrawImage(bitmap, 0, 0);
PaperSize ps = new PaperSize();
ps.RawKind = (int)PaperKind.A4;
pd.DefaultPageSettings.PaperSize = ps;
pd.DefaultPageSettings.Landscape = false;
pd.Print();
}
I'm trying to print an image however my aspect ration on the A4 papaer is incorrect. I did my search and tried to use the same mm size as the A4 paper but no luck. I'm working on Unity3D 2017.0.3f using .NET 3.5.
As you can see in the image above, it's in the bottom right and leaving all the space behind. I want it just landscape normal A4 printed.
Here's my code that I'm using to print:
public void btnPrint_Click()
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = availablePrinter[0];
pd.DefaultPageSettings.Margins = new Margins(100, 100, 100, 100);
pd.OriginAtMargins = true;
pd.DefaultPageSettings.Landscape = true;
pd.PrinterSettings.DefaultPageSettings.Landscape = true;
pd.PrintPage += new PrintPageEventHandler(pqr);
pd.Print();
}
void pqr(object o, PrintPageEventArgs e)
{
Debug.Log("PrintingImage");
System.Drawing.Image i = System.Drawing.Image.FromFile(path);
e.Graphics.DrawImage(i, e.MarginBounds);
}
I tried using a rect and making it manually but still didn't work.
So i managed to fix it but changing the Margins
pd.DefaultPageSettings.Margins = new Margins(0, 0, 50, 125);
I want to show the print dialog box before printing the document, so the user can choose another printer before printing. The code for printing is:
private void button1_Click(object sender, EventArgs e)
{
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintImage);
pd.Print();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ToString());
}
}
void PrintImage(object o, PrintPageEventArgs e)
{
int x = SystemInformation.WorkingArea.X;
int y = SystemInformation.WorkingArea.Y;
int width = this.Width;
int height = this.Height;
Rectangle bounds = new Rectangle(x, y, width, height);
Bitmap img = new Bitmap(width, height);
this.DrawToBitmap(img, bounds);
Point p = new Point(100, 100);
e.Graphics.DrawImage(img, p);
}
will this code be able to print the current form?
You have to use PrintDialog
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
PrintDialog pdi = new PrintDialog();
pdi.Document = pd;
if (pdi.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
else
{
MessageBox.Show("Print Cancelled");
}
Edited(from Comment)
On 64-bit Windows and with some versions of .NET you may have to set pdi.UseExDialog = true; for the dialog window to appear.
For the sake of completeness, the code should include a using directive
using System.Drawing.Printing;
for further reference please goto
PrintDocument Class
I am trying to print an image in C#. It is a full 8.5x11 size tiff created by Adobe Acrobat from a PDF. When I print it with C# using the code below, it prints correct vertically, but not horizontally, where it is pushed over about a half inch. I set the origin of the image to 0,0. Am I missing something?
private FileInfo _sourceFile;
public void Print(FileInfo doc, string printer, int tray)
{
_sourceFile = doc;
PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = printer;
pd.DocumentName = _sourceFile.FullName;
using (Image img = Image.FromFile(_sourceFile.FullName)) {
if (img.Width > img.Height) {
pd.DefaultPageSettings.Landscape = true;
}
}
pd.PrintPage += PrintPage;
foreach (PaperSource ps in pd.PrinterSettings.PaperSources) {
if (ps.RawKind == tray) {
pd.DefaultPageSettings.PaperSource = ps;
}
}
pd.Print();
}
private void PrintPage(object o, PrintPageEventArgs e)
{
using (System.Drawing.Image img = System.Drawing.Image.FromFile(_sourceFile.FullName)) {
Point loc = new Point(0, 0);
e.Graphics.DrawImage(img, loc);
}
}
look at the code from this below for a good example this code is from this link below
Print Image in C#
private void PrintImage()
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.OriginAtMargins = false;
pd.DefaultPageSettings.Landscape = true;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
printPreviewDialog1.Document = pd;
printPreviewDialog1.ShowDialog();
//pd.Print();
}
void pd_PrintPage(object sender, PrintPageEventArgs e)
{
double cmToUnits = 100 / 2.54;
e.Graphics.DrawImage(bmIm, 100, 1000, (float)(15 * cmToUnits), (float)(10 * cmToUnits));
}
private void button5_Click(object sender, EventArgs e)
{
PrintImage();
}
In C#, I am trying to print an image using PrintDocument class with the below code. The image is of size 1200 px width and 1800 px height. I am trying to print this image in a 4*6 paper using a small zeebra printer. But the program is printing only 4*6 are of the big image. that means it is not adjusting the image to the paper size !
PrintDocument pd = new PrintDocument();
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile("C://tesimage.PNG");
Point p = new Point(100, 100);
args.Graphics.DrawImage(i, 10, 10, i.Width, i.Height);
};
pd.Print();
When i print the same image using Window Print (right click and select print, it is scaling automatically to paper size and printing correctly. that means everything came in 4*6 paper.) How do i do the same in my C# program ?
The parameters that you are passing into the DrawImage method should be the size you want the image on the paper rather than the size of the image itself, the DrawImage command will then take care of the scaling for you. Probably the easiest way is to use the following override of the DrawImage command.
args.Graphics.DrawImage(i, args.MarginBounds);
Note: This will skew the image if the proportions of the image are not the same as the rectangle. Some simple math on the size of the image and paper size will allow you to create a new rectangle that fits in the bounds of the paper without skewing the image.
Not to trample on BBoy's already decent answer, but I've done the code that maintains aspect ratio. I took his suggestion, so he should get partial credit here!
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
pd.DefaultPageSettings.Landscape = true; //or false!
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(#"C:\...\...\image.jpg");
Rectangle m = args.MarginBounds;
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
args.Graphics.DrawImage(i, m);
};
pd.Print();
The solution provided by BBoy works fine. But in my case I had to use
e.Graphics.DrawImage(memoryImage, e.PageBounds);
This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!
You can use my code here
//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintPage;
//here to select the printer attached to user PC
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = pd;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
pd.Print();//this will trigger the Print Event handeler PrintPage
}
}
//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
try
{
if (File.Exists(this.ImagePath))
{
//Load the image from the file
System.Drawing.Image img = System.Drawing.Image.FromFile(#"C:\myimage.jpg");
//Adjust the size of the image to the page to print the full image without loosing any part of it
Rectangle m = e.MarginBounds;
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
catch (Exception)
{
}
}
Answer:
public void Print(string FileName)
{
StringBuilder logMessage = new StringBuilder();
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));
try
{
if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.
PrintDocument pd = new PrintDocument();
//Disable the printing document pop-up dialog shown during printing.
PrintController printController = new StandardPrintController();
pd.PrintController = printController;
//For testing only: Hardcoded set paper size to particular paper.
//pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
//pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrintPage += (sndr, args) =>
{
System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);
//Adjust the size of the image to the page to print the full image without loosing any part of the image.
System.Drawing.Rectangle m = args.MarginBounds;
//Logic below maintains Aspect Ratio.
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
//Calculating optimal orientation.
pd.DefaultPageSettings.Landscape = m.Width > m.Height;
//Putting image in center of page.
m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
args.Graphics.DrawImage(i, m);
};
pd.Print();
}
catch (Exception ex)
{
log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
}
finally
{
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
log.Info(logMessage.ToString());
}
}
Agree with TonyM and BBoy - this is the correct answer for original 4*6 printing of label. (args.PageBounds). This worked for me for printing Endicia API service shipping Labels.
private void SubmitResponseToPrinter(ILabelRequestResponse response)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(response.Labels[0].FullPathFileName.Trim());
args.Graphics.DrawImage(i, args.PageBounds);
};
pd.Print();
}
all these answers has the problem, that's always stretching the image to pagesize and cuts off some content at trying this.
Found a little bit easier way.
My own solution only stretch(is this the right word?) if the image is to large, can use multiply copies and pageorientations.
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
BitmapImage bmi = new BitmapImage(new Uri(strPath));
Image img = new Image();
img.Source = bmi;
if (bmi.PixelWidth < dlg.PrintableAreaWidth ||
bmi.PixelHeight < dlg.PrintableAreaHeight)
{
img.Stretch = Stretch.None;
img.Width = bmi.PixelWidth;
img.Height = bmi.PixelHeight;
}
if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)
{
img.Margin = new Thickness(0);
}
else
{
img.Margin = new Thickness(48);
}
img.VerticalAlignment = VerticalAlignment.Top;
img.HorizontalAlignment = HorizontalAlignment.Left;
for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)
{
dlg.PrintVisual(img, "Print a Image");
}
}