1 | initial version |
Add the required using statements:
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using System.Drawing.Printing;
Create a new PdfDocument object:
var doc = new PdfDocument();
Add a new page to the document:
var page = doc.AddPage();
Create a graphics object to draw on the page:
var gfx = XGraphics.FromPdfPage(page);
Add text or graphics to the page using the graphics object:
gfx.DrawString("Hello, World!", new XFont("Verdana", 20), XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
Create a PrintDocument object:
var printDoc = new PrintDocument();
Set the printer name and page settings:
printDoc.PrinterSettings.PrinterName = "<printer name>";
printDoc.DefaultPageSettings.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom", (int)page.Width.Point, (int)page.Height.Point);
Attach an event handler to the PrintPage event:
printDoc.PrintPage += (sender, args) =>
{
var stream = new MemoryStream();
doc.Save(stream);
var bytes = stream.ToArray();
args.Graphics.DrawImage(Image.FromStream(new MemoryStream(bytes)), args.PageBounds);
};
Print the document:
printDoc.Print();
Dispose of the graphics and document objects:
gfx.Dispose();
doc.Dispose();
Note: You may need to adjust the code to suit your specific use case.