I have a C# .net
program that creates various documents. These documents should be stored in different locations and with different, clearly defined names.
As noted in other answers, you can force PrinterSettings.PrintToFile = true
, and set the PrinterSettings.PrintFileName
, but then your user doesn't get the save as popup. My solution is to go ahead and show the Save As dialog myself, populating that with my "suggested" filename [in my case, a text file (.txt) which I change to .pdf], then set the PrintFileName
to the result.
DialogResult userResp = printDialog.ShowDialog();
if (userResp == DialogResult.OK)
{
if (printDialog.PrinterSettings.PrinterName == "Microsoft Print to PDF")
{ // force a reasonable filename
string basename = Path.GetFileNameWithoutExtension(myFileName);
string directory = Path.GetDirectoryName(myFileName);
prtDoc.PrinterSettings.PrintToFile = true;
// confirm the user wants to use that name
SaveFileDialog pdfSaveDialog = new SaveFileDialog();
pdfSaveDialog.InitialDirectory = directory;
pdfSaveDialog.FileName = basename + ".pdf";
pdfSaveDialog.Filter = "PDF File|*.pdf";
userResp = pdfSaveDialog.ShowDialog();
if (userResp != DialogResult.Cancel)
prtDoc.PrinterSettings.PrintFileName = pdfSaveDialog.FileName;
}
if (userResp != DialogResult.Cancel) // in case they canceled the save as dialog
{
prtDoc.Print();
}
}
It seems like the PrintFilename
is ignored if the PrintToFile
property is not set to true
. If PrintToFile
is set to true
and a valid filename (full path) is provided, the filedialog where the user selects filename will not be displayed.
Tip: When setting the printername of the printersettings you can check the IsValid
property to check that this printer actually exists. For more info on printersettings and finding installed printers check this post
I did some experimenting myself but like yourself was also not able to prefill the SaveAs dialog in the PrintDialog with the DocumentName or PrinterSettings.PrintFileName already filled in the PrintDocument instance. This seems counterintuitive, so maybe I'm missing something
If you want to, you can however bypass the printdialog and print automatically without any user interaction at all. If you choose to do so, you must make sure beforehand that the directory to which you want to add a document to is in existence and that the document to be added is not in existence.
string existingPathName = @"C:\Users\UserName\Documents";
string notExistingFileName = @"C:\Users\UserName\Documents\TestPrinting1.pdf";
if (Directory.Exists(existingPathName) && !File.Exists(notExistingFileName))
{
PrintDocument pdoc = new PrintDocument();
pdoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
pdoc.PrinterSettings.PrintFileName = notExistingFileName;
pdoc.PrinterSettings.PrintToFile = true;
pdoc.PrintPage += pdoc_PrintPage;
pdoc.Print();
}