Fit PrintDocument to an A4 - c#

I wrote(copied) a small code to select some image files and print it every five minutes.
When it prints, the image doesn't fit to the paper. It's smaller or bigger. So I want to fit the Images to an A4 Page Size.
I couldn't find any properties for that.
Is there a way to do that?
Here is my code:
private async void button1_Click(object btnSender, EventArgs e)
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
// Read the files
foreach (string file in openFileDialog1.FileNames)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "Print Document";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
printDoc.DefaultPageSettings.Landscape = true;
printDoc.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(file);
Point p = new Point(0, 0);
args.Graphics.DrawImage(i, p);
};
printDoc.Print();
await Task.Delay(300000);
}
Process.Start("shutdown.exe", "-s -t 00");
}
}

You do not need to define Point;
To fit image to a page just use args.Graphics.DrawImage(i, args.PageBounds);
instead of args.Graphics.DrawImage(i, p);

Related

C# Winform PrintDialog Pages popup

in C# Winform, i'm sending an Image to the printer using the PrintDialog... using this code:
private void PrintSnippedImage()
{
PrintDocument pDoc = new PrintDocument();
pDoc.PrintPage += PrintPage;
PrintDialog pDialog = new PrintDialog();
pDialog.ShowHelp = true;
pDialog.AllowSelection = false;
pDialog.AllowSomePages = false;
pDialog.Document = pDoc;
if (pDialog.ShowDialog() == DialogResult.OK)
{
pDoc.Print();
};
}
private void PrintPage(object o, PrintPageEventArgs e)
{
System.Drawing.Image img = Glob.SnippedImage;
Point loc = new Point(10, 10);
e.Graphics.DrawImage(img, loc);
}
I get a popup that shows "Printing... Page 1 of document" with a Cancel button.
it appears in seemingly random locations on one of my monitors.
is there a way to inhibit this popup, or at least force it to appear on the monitor in the general location of the application that called it?
it looks like this:
It should be a case of swapping the PrintController implementation from PrintControllerWithStatusDialog (the default) to StandardPrintController. See https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument.printcontroller?view=dotnet-plat-ext-6.0#system-drawing-printing-printdocument-printcontroller

C# print document from two printers on 1 form

On 1 Form I have two buttons (one to print to PDF printer, second to normal printer). I print some bitmap image. However behaviour of the program is strange. Sometimes both buttons work as expected. Sometimes normal printer prints blank, while pdf prints proper, sometimes normal printer do not print anything while pdf printer prints some "code".
Below my code
private void printBtn_Click(object sender, EventArgs e)
{ ... BmpToPrint = new Bitmap(tmp_bmp);
tmp_bmp.Dispose();
string file = "sometext";
pdoc.PrinterSettings.PrinterName = System.Configuration.ConfigurationManager.AppSettings["Printer"];
pdoc.DocumentName = file;
pdoc.DefaultPageSettings.Landscape = false;
ppv.Document = pdoc; //printpreviewdialog ppv, printdocument pdoc
printDialog1.Document = pdoc;
if (printDialog1.PrinterSettings.IsValid) { pdoc.Print(); } }
private void printPdfBtn_Click(object sender, EventArgs e)
{... BmpToPrint = new Bitmap(tmp_bmp);
tmp_bmp.Dispose();
string file = "sometext" + ".pdf";
if (!Directory.Exists(directory)) { directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); }
pdoc.PrinterSettings.PrinterName = System.Configuration.ConfigurationManager.AppSettings["PdfPrinter"];
pdoc.PrinterSettings.PrintToFile = true;
pdoc.DocumentName = file;
pdoc.PrinterSettings.PrintFileName = Path.Combine(directory, file);
pdoc.DefaultPageSettings.Landscape = false;
ppv.Document = pdoc;
printDialog1.Document = pdoc;
if (printDialog1.PrinterSettings.IsValid) { pdoc.Print(); } }
private void pdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.Clear(Color.White);
Point PktWst = new Point(5, 0);
e.Graphics.DrawImage(BmpToPrint, PktWst);
e.HasMorePages = false;
}
sometimes in pdf instead of image appears this
Sometimes it works perfectly printing image both to pdf and printer while sometimes the same image as before is either not printed/blank printed/ or pdf has this artifacts instead.
Shall I reset some settings while using second printer or clean some data somehow?

Exception for image size

How can I set exception for image size? for instance, I am trying to select a file (image) through openfiledialogue but I want to throw an exception if the image size is less than 250x150 (assume).
public void select_image_button17_Click(object sender, EventArgs e)
{
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
AddImagesToButtons(images);
break;
}
}
}
Windows Exceptions is a class used for when the program receive errors that occur during application execution in other words it's for when the programme receive an unusual behavior , for exemple something that will make the programme 'crash' or stop working
Exeptions and validations are 2 different but similar concept
What you are looking for is a validation mechanism and there are many way to do so :
One of the thing you can do is force the image to the desired size this will avoid undesired image size :
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Size = new Size(210, 110);///--add here your desired size
AddImagesToButtons(images);
break;
}
}
}
But if you insist on displaying an error you can use a message box instead ,make a loop and when the desired size is met exit the loop , otherwise display a message Box to the user:
foreach (Button b in game_panel1.Controls)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "JPG|*.jpg;*.jpeg|PNG|*.png";
// openFileDialog1.InitialDirectory = #"C:\Users\DELL_PC";
if (openFileDialog1.ShowDialog() != DialogResult.OK)
{
break;
}
else
{
bool correctSize=false;
var imageH=null;
var imageW=null
while(!correctSize) //make a loop so only desired size will be taken
{
string a = openFileDialog1.FileName;
Image ToBeCropped = Image.FromFile(a, true);
*ReturnCroppedList(ToBeCropped, 320, 320);
pictureBox1.Image = ToBeCropped;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
if(PictureBox1.Image.Size.Width==yourWidth && PictureBox1.Image.Size.height==yourHeight) //Validate size
{ correctSize =true;
AddImagesToButtons(images);
break;
}
else
MessageBox.Show("Please enter image size your desired size ")
}
}
}
OpenFileDialog is likely concerned with simply selected a file on the file system. Once you've selected, it is up to you to validate that selection meets the criteria, whatever that criteria may be. So once selection is made, and you now know path to the file, use image library to load the file, validate that file loads without issues (remember, may not be a valid file to begin with), and then validate its dimensions. If something doesn't pass, act accordingly, e.g. letting the user know why file is being rejected and suggesting picking a new one.

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# - 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

Categories