如何使用VB.NET对项目窗口截图并将内容导出转换为PDF格式
VB.NET 税务计算器界面导出PDF实现方案
你当前要实现的税务计算器界面导出PDF效果参考如下:
图中数字仅为测试使用可忽略。
一、现有代码问题说明
你现有两个按钮的代码都存在基础逻辑错误:
- 保存文件按钮先弹出保存对话框再设置标题、初始目录,配置项不会生效;重复调用对话框显示方法,保存方法传入参数错误,无法正常保存文件
- 生成PDF按钮仅实现了窗体截图保存为本地图片的逻辑,缺少图片转PDF的核心步骤
二、修复后的保存文件按钮代码
Private Sub Screenshot_Click(sender As Object, e As EventArgs) Handles Screenshot.Click ' 生成窗体截图 Dim bmp As New Bitmap(Me.Width, Me.Height) Me.DrawToBitmap(bmp, New Rectangle(0, 0, Me.Width, Me.Height)) PictureBox1.Image = bmp ' 配置保存对话框 SaveFileDialog1.Title = "保存截图文件" SaveFileDialog1.InitialDirectory = "E:\French" SaveFileDialog1.Filter = "PNG图片|*.png|JPG图片|*.jpg" SaveFileDialog1.FileName = "税务计算器截图_" & DateTime.Now.ToString("yyyyMMddHHmmss") ' 弹出对话框并保存 If SaveFileDialog1.ShowDialog() = DialogResult.OK Then bmp.Save(SaveFileDialog1.FileName) MessageBox.Show("文件保存成功") End If ' 释放资源 bmp.Dispose() End Sub
三、生成PDF按钮实现方案
前置准备
先在你的项目中通过NuGet包管理器安装iTextSharp库,这是.NET平台常用的PDF处理库,无需额外依赖。
完整实现代码
Imports iTextSharp.text Imports iTextSharp.text.pdf Imports System.Drawing.Imaging Private Sub PDFbutton_Click(sender As Object, e As EventArgs) Handles PDFbutton.Click ' 1、生成窗体截图 Dim bmpScreenshot As Bitmap = New Bitmap(Me.Width, Me.Height, PixelFormat.Format32bppArgb) Dim gfxScreenshot As Graphics = Graphics.FromImage(bmpScreenshot) gfxScreenshot.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, Me.Size, CopyPixelOperation.SourceCopy) ' 2、配置PDF保存对话框 SaveFileDialog1.Title = "导出PDF文件" SaveFileDialog1.InitialDirectory = "E:\French" SaveFileDialog1.Filter = "PDF文件|*.pdf" SaveFileDialog1.FileName = "税务计算器计算结果_" & DateTime.Now.ToString("yyyyMMddHHmmss") If SaveFileDialog1.ShowDialog() = DialogResult.OK Then ' 3、创建PDF文档 Dim pdfDoc As New Document(PageSize.A4, 10, 10, 10, 10) PdfWriter.GetInstance(pdfDoc, New FileStream(SaveFileDialog1.FileName, FileMode.Create)) pdfDoc.Open() ' 4、将截图转换为PDF可插入的图片,适配A4页面大小 Dim pdfImg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bmpScreenshot, ImageFormat.Png) If pdfImg.Width > pdfDoc.PageSize.Width Or pdfImg.Height > pdfDoc.PageSize.Height Then pdfImg.ScaleToFit(pdfDoc.PageSize.Width - 20, pdfDoc.PageSize.Height - 20) End If pdfImg.Alignment = Element.ALIGN_CENTER ' 5、插入图片到PDF并保存 pdfDoc.Add(pdfImg) pdfDoc.Close() MessageBox.Show("PDF导出成功") End If ' 释放资源 gfxScreenshot.Dispose() bmpScreenshot.Dispose() End Sub
优化提示
- 如果窗体尺寸过大导出后显示不全,可以在生成截图时只截取计算结果区域,不需要截取整个窗体,只要修改
CopyFromScreen的坐标和尺寸参数即可 - 导出的PDF如果需要加入文字说明,可以在插入图片前调用
pdfDoc.Add(new Paragraph("你的说明文字"))实现
内容的提问来源于stack exchange,提问作者alkhanate458
相关产品推荐
相关产品推荐

