c# - 如何使用 Windows 10 附带的 Microsoft Print To PDF 打印机以编程方式打印到 PDF 文件而不提示在 C# 中输入文件名

标签 c# pdf printing windows-10

Microsoft Windows 10 附带 Microsoft Print To PDF 打印机,可以将某些内容打印为 PDF 文件。它会提示要下载的文件名。

我如何从 C# 中以编程方式控制它,以不提示输入 PDF 文件名,而是保存到我提供的某个文件夹中的特定文件名?

这用于以编程方式将大量文档或其他类型的文件打印为 PDF 的批处理。

最佳答案

要使用 Microsoft Print to PDF 打印机打印 PrintDocument 对象而不提示输入文件名,这里是执行此操作的纯代码方法:

// generate a file name as the current date/time in unix timestamp format
string file = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString();

// the directory to store the output.
string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// initialize PrintDocument object
PrintDocument doc = new PrintDocument() {
    PrinterSettings = new PrinterSettings() {
        // set the printer to 'Microsoft Print to PDF'
        PrinterName = "Microsoft Print to PDF",

        // tell the object this document will print to file
        PrintToFile = true,

        // set the filename to whatever you like (full path)
        PrintFileName = Path.Combine(directory, file + ".pdf"),
    }
};

doc.Print();

您还可以将此方法用于其他另存为文件 类型的打印机,例如Microsoft XPS 打印机

关于c# - 如何使用 Windows 10 附带的 Microsoft Print To PDF 打印机以编程方式打印到 PDF 文件而不提示在 C# 中输入文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896952/

相关文章:

pdf - sphinx用latexpdf删除我pdf中的章节标题?

java - PdfBox PDF 到图像转换 linux(字符间距问题)

python - 结果未打印,为什么 `print` 在 `return` 之后被忽略?

java - 具有多行单元格渲染器的 JTable 打印非常奇怪

c# - 客户端消息功能

c# - 仅使用正则表达式在字符串中查找中间字符

c# - delphi 导入具有指定入口点的dll函数

android - 创建 PDF 时出错

Android:无法从 WebView 打印/PDF html 文档(版本:86.0.4240.75)

c# - C#中的关键字实现