在Microsoft Print to PDF打印机中以编程方式设置文件名和路径



我有一个C# .net程序,它可以创建各种文档。这些文件应存储在不同的位置,并使用不同的、明确定义的名称。

为此,我使用了System.Drawing.Printing.PrintDocument类。我选择Microsoft Print to PDF作为打印机,并使用以下语句:

PrintDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF"

在这样做的同时,我可以在pdf file中打印我的文档。用户将获得一个文件选择对话框。然后,他可以在这个对话框中指定pdf文件的名称和存储位置

由于文件量很大,总是找到正确的路径和名称很烦人,也很容易出错,所以我想在这个对话框中以编程方式设置正确的路径或文件名。

我已经测试了这些属性:

PrintDocument.PrinterSettings.PrintFileName PrintDocument.DocumentName

将所需的路径和文件名写入这些属性没有帮助。有人知道如何在C#中设置Microsoft Print to PDF打印机的路径和文件名的默认值吗?

注意:我的环境:Windows 10,Visual Studio 2010,.net框架4.5

如其他答案中所述,您可以强制PrinterSettings.PrintToFile = true,并设置PrinterSettings.PrintFileName,但您的用户不会得到另存为弹出窗口。我的解决方案是自己显示"另存为"对话框,用我的"建议"文件名[在我的情况下,是一个文本文件(.txt),我将其更改为.pdf]填充该对话框,然后将PrintFileName设置为结果。

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

我自己也做了一些实验,但和自己一样,也无法在PrintDialog中的SaveAs对话框中预先填充PrintDocument实例中已经填充的DocumentName或PrinterSettings.PrintFileName。这似乎违反直觉,所以也许我错过了

但是,如果您愿意,您可以绕过打印对话框并自动打印,而无需任何用户交互。如果选择这样做,则必须事先确保要向其中添加文档的目录存在,并且要添加的文档不存在。

string existingPathName = @"C:UsersUserNameDocuments";
string notExistingFileName = @"C:UsersUserNameDocumentsTestPrinting1.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();
 }

如果PrintToFile属性是而不是设置为true,则似乎会忽略PrintFilename。如果PrintToFile设置为true,并且提供了有效的文件名(完整路径),则不会显示用户选择文件名的文件对话框。

提示:当设置打印机设置的打印机名称时,您可以检查IsValid属性以检查此打印机是否确实存在。有关打印机设置和查找已安装打印机的更多信息,请查看此文章

今天我发现我一定有某种未确诊的精神问题。我毫无理由地痴迷于做一些完全不重要的事情,这很有效!

在VS 2010上进行了测试,如果有人使用它,请分享它是否适用于您的VS版本。

private void changePrintPreviewDialogButton(PrintPreviewDialog printPrvDlg, String fullFilePath)
{
    // Find the print button in the PrintPreviewDialog and replace it with ours
    Control.ControlCollection cc = (printPrvDlg as Form).Controls;
    foreach (Control ctrl in cc)
    {
        // Find the toolStrip where the button should be
        if (ctrl.Name == "toolStrip1")
        {
            ToolStrip ts = (ToolStrip)ctrl;
            foreach (ToolStripItem tsi in ts.Items)
            {
                // Find the print button it self
                if (tsi.Name == "printToolStripButton")
                {
                    // Replace the old button with a our new customized one
                    ToolStripButton newTsi =
                        new ToolStripButton(
                            "", // No text, or it appears after the image
                            tsi.Image,
                            new EventHandler((Object sender, EventArgs e) => 
                            {
                                // Create our customized save dialog
                                SaveFileDialog sfd = new SaveFileDialog();
                                sfd.Title = "Save Print Output As";
                                sfd.InitialDirectory = Path.GetDirectoryName(fullFilePath);
                                sfd.FileName = Path.GetFileNameWithoutExtension(fullFilePath) + ".pdf";
                                sfd.Filter = "PDF File(*.pdf)|*.pdf";
                                
                                if (sfd.ShowDialog(printPrvDlg) == DialogResult.OK)
                                {
                                    printPrvDlg.Document.PrinterSettings.PrintFileName = sfd.FileName;
                                    printPrvDlg.Document.PrinterSettings.PrintToFile = true;
                                    // Perform a click in the original button
                                    ((ToolStripButton)(sender as ToolStripButton).Tag).PerformClick();
                                }
                            }),
                            tsi.Name);
                    newTsi.ToolTipText = tsi.ToolTipText;
                    newTsi.Tag = tsi; // Keep the original button to call latter
                    ts.Items.Remove(tsi);
                    ts.Items.Insert(0, newTsi);
                    return;
                }
            }
        }
    }
}
//Context for using it
private void configPrinterPreview()
{
    PrintDocument pd = new PrintDocument();
    pd.DefaultPageSettings.Landscape = false;
    pd.DocumentName = Path.GetFileNameWithoutExtension(file) + ".pdf";
    pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    pd.PrintPage += new PrintPageEventHandler(this.PrintPage);
    PrintPreviewDialog printPrvDlg = new PrintPreviewDialog();
    printPrvDlg.Document = pd;
    printPrvDlg.ShowIcon = true;
    printPrvDlg.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
    printPrvDlg.Width = parentForm.Width;
    printPrvDlg.Height = parentForm.Height;
    (printPrvDlg as Form).WindowState = FormWindowState.Maximized;
    changePrintPreviewDialogButton(printPrvDlg, file);
    printPrvDlg.ShowDialog(parentForm);
}

最新更新