如何获取文本框中的文件路径并实现打印功能?
解决PrintDocument打印PDF空白页的问题
你的代码打印空白页是因为**PrintDocument本身只是提供打印的框架,它不会自动读取和渲染PDF文件内容**,设置DocumentName只是给打印任务命名,不会让它加载文件内容。以下是两种适合新手的解决方案:
方案1:用系统默认程序打印(最简单)
直接调用系统中能打开PDF的程序(比如Edge、Adobe Reader)来执行打印,不需要自己处理PDF渲染,代码简单易上手:
Private Sub BtnPrint_Click(sender As Object, e As RoutedEventArgs) Handles btnPrint.Click Dim filePath As String = txtTest.Text.Trim() ' 先检查文件是否存在 If Not System.IO.File.Exists(filePath) Then MessageBox.Show("文件不存在,请检查路径!") Return End If ' 调用系统默认程序执行打印 Dim printStartInfo As New ProcessStartInfo(filePath) printStartInfo.Verb = "print" ' 指定操作类型为打印 printStartInfo.CreateNoWindow = True ' 不显示程序窗口 printStartInfo.WindowStyle = ProcessWindowStyle.Hidden ' 隐藏窗口 Try Process.Start(printStartInfo) MessageBox.Show("打印任务已提交!") Catch ex As Exception MessageBox.Show("打印失败:" & ex.Message) End Try End Sub
注意点
- 确保用户电脑上有能打开PDF的默认程序(一般Windows自带Edge就能处理)
- 输入的文件路径要去掉多余的后缀,比如你例子里的
.pdf.要改成.pdf
方案2:用第三方库自定义打印(适合需要控制打印细节)
如果需要自定义打印缩放、页面范围等,可以用PDF处理库PdfSharp来实现:
- 右键你的项目 → 管理NuGet程序包 → 搜索安装
PdfSharp-wpf - 使用以下代码:
Imports PdfSharp.Pdf Imports PdfSharp.Drawing Imports PdfSharp.Printing Private Sub BtnPrint_Click(sender As Object, e As RoutedEventArgs) Handles btnPrint.Click Dim filePath As String = txtTest.Text.Trim() If Not System.IO.File.Exists(filePath) Then MessageBox.Show("文件不存在,请检查路径!") Return End If Dim printDlg As New PrintDialog() printDlg.AllowSomePages = True ' 允许选择打印页面范围 If printDlg.ShowDialog() = True Then Try ' 打开PDF文件 Dim pdfDoc As PdfDocument = PdfReader.Open(filePath, PdfDocumentOpenMode.Import) Dim printDoc As New PrintDocument() ' 绑定打印事件,逐页渲染PDF内容 AddHandler printDoc.PrintPage, Sub(s, args) ' 获取当前要打印的PDF页面(注意索引从0开始) Dim pdfPage As PdfPage = pdfDoc.Pages(args.PageSettings.PrintablePageRange.FromPage - 1) Using gfx As XGraphics = XGraphics.FromPrintPageEventArgs(args) ' 计算缩放比例,适配打印纸张 Dim scale As Double = Math.Min(args.PageBounds.Width / pdfPage.Width, args.PageBounds.Height / pdfPage.Height) ' 绘制PDF页面到打印画布 gfx.DrawImage(XImage.FromGdiPlusImage(pdfPage.GetDrawingImage()), 0, 0, pdfPage.Width * scale, pdfPage.Height * scale) End Using End Sub ' 应用打印对话框的设置 printDoc.PrinterSettings = printDlg.PrinterSettings printDoc.Print() MessageBox.Show("打印完成!") Catch ex As Exception MessageBox.Show("打印失败:" & ex.Message) End Try End If End Sub
注意点
- 这个方案可以完全控制打印过程,不会弹出外部阅读器窗口
- 安装NuGet包时要选择适配WPF的
PdfSharp-wpf版本
内容的提问来源于stack exchange,提问作者AppleIT
相关产品推荐
相关产品推荐

