C# Print PDF programatically

 Implement this answer

https://stackoverflow.com/questions/47857500/c-sharp-how-to-programmatically-print-an-existing-pdf-file-using-printdocument#answer-48537329


1. Make sure you install (via NuGet) PdfiumViewer  but only version 2.10.0other versions does quite a mess...
then run this code and thats it            

var path = @"C:\temp\test2.pdf";

using (var document = PdfDocument.Load(path)) {

  using (var printDocument = document.CreatePrintDocument()) {

    printDocument.PrinterSettings.PrintFileName = "test2.pdf";

    printDocument.PrinterSettings.PrinterName = printersNames[pi];

    printDocument.DocumentName = "test2.pdf";

    printDocument.PrinterSettings.PrintFileName = "test2.pdf";

    printDocument.PrintController = new StandardPrintController();

    printDocument.Print();

  }

}


Now please ask me how to get your printer name            


List<string> printersNames = new List<string>();

int i = 0;

foreach (string printername in PrinterSettings.InstalledPrinters) {

  Console.WriteLine((i++) + " - " + printername);  

  printersNames.Add(printername);

}

Console.WriteLine("\nChoose Printer\n");

string spi = Console.ReadLine(); 

int pi = Convert.ToInt32(spi);






BONUS

how to print only text? string or text file?



//add using (need nuget)

using System.Drawing;

using System.Drawing.Printing;            



//use PrintDocument class

var pd = new PrintDocument();

printDoc.DocumentName = "test";

pd.PrinterSettings.PrinterName = printersNames[pi];

pd.PrintPage += Pd_PrintPage_EV_test1_txt;

pd.Print();



//add this event to generate any text

private static void Pd_PrintPage_EV_test1(object sender, PrintPageEventArgs e) {

  string filePath = "C:\\temp\\test1.txt";

  string line = System.IO.File.ReadAllText(filePath);

  var font = new Font("Arial", 12);

  var area = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);

  e.Graphics.DrawString(line, font, Brushes.Black, area);

  e.HasMorePages = false;

}






Comments

Popular posts from this blog

OverTheWire[.com] Natas Walkthrough - JUST HINT, NO SPOILERS

Asp.Net Ending Response options, Response.End() vs CompleteRequest()

SPFx with Angular, Full tutorial