Microsoft Windows 10附带一台Microsoft Print To PDF打印机,可以将某些内容打印到PDF文件中。它会提示输入文件名。
如何从C#以编程方式控制此操作以不提示输入PDF文件名,而是保存到我提供的某个文件夹中的特定文件名?
这是用于以编程方式将大量文档或其他类型的文件打印到PDF的批处理。
答案 0 :(得分:34)
要使用 Microsoft Print to PDF 打印机打印PrintDocument
对象而不提示输入文件名,以下是执行此操作的纯代码方式:
// generate a file name as the current date/time in unix timestamp format
string file = (string)(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 Printer
答案 1 :(得分:2)
您可以使用PrintOut
方法并指定第四个输出文件名参数来打印到Windows 10 PDF打印机,如下例所示:
/// <summary>
/// Convert a file to PDF using office _Document object
/// </summary>
/// <param name="InputFile">Full path and filename with extension of the file you want to convert from</param>
/// <returns></returns>
public void PrintFile(string InputFile)
{
// convert input filename to new pdf name
object OutputFileName = Path.Combine(
Path.GetDirectoryName(InputFile),
Path.GetFileNameWithoutExtension(InputFile)+".pdf"
);
// Set an object so there is less typing for values not needed
object missing = System.Reflection.Missing.Value;
// `doc` is of type `_Document`
doc.PrintOut(
ref missing, // Background
ref missing, // Append
ref missing, // Range
OutputFileName, // OutputFileName
ref missing, // From
ref missing, // To
ref missing, // Item
ref missing, // Copies
ref missing, // Pages
ref missing, // PageType
ref missing, // PrintToFile
ref missing, // Collate
ref missing, // ActivePrinterMacGX
ref missing, // ManualDuplexPrint
ref missing, // PrintZoomColumn
ref missing, // PrintZoomRow
ref missing, // PrintZoomPaperWidth
ref missing, // PrintZoomPaperHeight
);
}
OutputFile
是您要转换的输入文档的完整路径字符串,doc是常规文档对象。有关该文档的详细信息,请参阅_Document.PrintOut()
当您通过指定的PrintOut
打印到inputFile
时,示例中的OutputFileName
会生成无声打印,该.pdf
将与原始文档放在同一文件夹中,但是它将是PDF格式,带有typeString
扩展名。