C#学习教程:以编程方式提供文件路径作为“MicrosoftPrinttoPDF”打印机的输入文件默认安装Windows10打印机“MicrosoftPrinttoPDF”将文件打印为新的PDF。当您选择此打印机作为默认打印机并使用文件上下文菜单并选择打印时,它只会要求保存目录和名称。之后,它会立即转换为PDF并保存文件。只要安装了MSOffice,这就适用于Word、Excel、PowerPoint文件类型。但也适用于常见的图像类型和纯文本文件。我想通过提供默认路径自动执行此操作。我试过的Stackoverflow上已经有这个相关问题,但它没有解决我的具体问题,而且它相当不完整并且不起作用。但是我想出了这个C#控制台程序,它使用PDF打印机在桌面上生成一个新的PDF,其中“HelloWorld”作为字符串名称空间PrintToPdf_Win10{usingSystem;使用系统绘图;使用System.Drawing。印刷;classProgram{publicstaticvoidMain(string[]args){PrintDocumentprintDoc=newPrintDocument{PrinterSettings=newPrinterSettings{PrinterName="MicrosoftPrinttoPDF",PrintToFile=true,PrintFileName=Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/test.pdf"}};printDoc.PrintPage+=printDoc_PrintPage;printDoc.Print();控制台.ReadKey(true);}staticvoidprintDoc_PrintPage(objectsender,PrintPageEventArgse){e.Graphics.DrawString("HelloWorld",newFont("Arial",12),Brushes.Black,50,50);}}}问题我如何设置——比方说一个Word文档——作为我的printDoc对象的输入?有没有一种通用的方法可以将printDoc设置为只为我要打印的文件提供文件路径?或者我是否必须为每个可能的文件类型系列创建自定义函数,例如:这是一个如何打印图像或文本的简单解决方案(它将帮助您处理png、bmp、jpg、txt、ini等格式)privatestaticStreamReader流打印;静态无效主要(字符串[]参数){字符串打印格式;printFormat="txt";尝试{streamToPrint=newStreamReader(@"D:TestText.txt");PrintDocumentprintDoc=newPrintDocument{PrinterSettings=newPrinterSettings{PrinterName="MicrosoftPrinttoPDF",PrintToFile=true,PrintFileName=Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/test.pdf"}};printDoc.DefaultPageSettings.PaperSize=newSystem.Drawing.Printing.PaperSize("A4",210,290);printDoc.PrinterSettings.DefaultPageSettings.Landscape=false;printDoc.PrinterSettings.DefaultPageSettings.Margins.Top=0;printDoc.PrinterSettings.DefaultPageSettings.Margins.Left=0;switch(printFormat){case"jpg":printDoc.PrintPage+=printDoc_PrintImage;休息;case"txt":printDoc.PrintPage+=printDoc_PrintText;休息;默认值:中断;}printDoc.Print();}最后{streamToPrint.Close();}Console.ReadKey(true);}staticvoidprintDoc_PrintImage(objectsender,PrintPageEventArgse){图像photo=Image.FromFile(@"D:TestImage.jpg");点pPoint=新点(0,0);e.Graphics.DrawImage(照片,pPoint);}staticvoidprintDoc_PrintText(objectsender,PrintPageEventArgse){字体printFont;printFont=newFont("宋体",10);浮动每页行数=0;//计算每页的行数。linesPerPage=e.MarginBounds.Height/printFont.GetHeight(e.Graphics);浮动yPos=0;整数计数=0;floatleftMargin=e.MarginBounds.Left;floattopMargin=e.MarginBounds.Top;字符串行=空;while(算你知道docx,xl??sx就像zip文件,你可以解压得到xml的内容所以如果你想打印它们,这是很多工作它被使用并且需要更多了解C#学习教程。我希望大家多多关注---本文收集自网络,不代表立场,如涉及侵权,请点击右边联系管理员删除,如需转载请注明出处:
