Skip to content

Instantly share code, notes, and snippets.

@blackholeearth
Last active December 18, 2024 14:38
Show Gist options
  • Save blackholeearth/aba0db981982cf2b84c9a624b9f6c3f0 to your computer and use it in GitHub Desktop.
Save blackholeearth/aba0db981982cf2b84c9a624b9f6c3f0 to your computer and use it in GitHub Desktop.
print to pdf - what can i do inside PrintPage Event...
/*
i pass image into my print fucntion .. which is webbrowser HTML to Image.
to print that image you have to use that "PrintPage Event -> e.DrawImage "
*/
public static void Print(this Image image, string printerName, string printFileName)
{
if (printerName == null)
{
throw new ArgumentNullException("Printer cannot be null.", nameof(printerName));
}
using (PrintDialog printDialog = new PrintDialog())
{
using (PrintDocument printDoc = new PrintDocument())
{
printDialog.Document = printDoc;
printDialog.Document.DocumentName = "My Document";
printDialog.Document.OriginAtMargins = false;
printDialog.PrinterSettings.PrinterName = printerName;
//-- if selected printer is "print to PDF" , save to file Without Promting Dialog
//-- its annoying to write naems for 100 pdf files....
//printDialog.Document.PrinterSettings.PrintFileName = PathFn.CreatePath_toDesktop("invoice.pdf");
if (printerName == "Microsoft Print to PDF")
{
var printFileName_pdf = Path.ChangeExtension(printFileName, ".pdf");
printDialog.Document.PrinterSettings.PrintFileName = PathFn.CreatePath_toDesktop(printFileName_pdf);
printDialog.Document.PrinterSettings.PrintToFile = true;
printDialog.PrinterSettings.PrintToFile = true;
}
printDoc.PrintPage += (sender, e) =>
{
// Draw Image to PrintDoc -- fit image to Page Bound - keep AspectRatio
(image as Bitmap).SetResolution(300, 300);
//var NewSize = image.Size.FitToBound(e.MarginBounds.Size);
var NewSize = image.Size.FitToBound(e.PageSettings.PrintableArea.Size.ToSize());
e.Graphics.DrawImage(image, 0, 0, NewSize.Width, NewSize.Height);
};
printDoc.Print();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment