Programmatically set filename and path in Microsoft Print to PDF printer

后端 未结 3 1302
春和景丽
春和景丽 2021-01-18 02:30

I have a C# .net program that creates various documents. These documents should be stored in different locations and with different, clearly defined names.

3条回答
  •  我在风中等你
    2021-01-18 03:07

    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();
        }
    }
    

提交回复
热议问题