Ask Your Question
1

What are the steps to perform server side printing using .net 6 and PdfSharpCore?

asked 2022-08-11 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-06-26 14:00:00 +0000

bukephalos gravatar image
  1. Install the PdfSharpCore package using NuGet.
  2. Create a new Razor page or MVC View where you want to perform server-side printing.
  3. Add the required using statements:

    using PdfSharpCore.Drawing;
    using PdfSharpCore.Pdf;
    using System.Drawing.Printing;
    
  4. Create a new PdfDocument object:

    var doc = new PdfDocument();
    
  5. Add a new page to the document:

    var page = doc.AddPage();
    
  6. Create a graphics object to draw on the page:

    var gfx = XGraphics.FromPdfPage(page);
    
  7. 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);
    
  8. Create a PrintDocument object:

    var printDoc = new PrintDocument();
    
  9. 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);
    
  10. 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);
    };
    
  11. Print the document:

    printDoc.Print();
    
  12. 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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-11 11:00:00 +0000

Seen: 11 times

Last updated: Jun 26 '22