You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFsharp将控件转PDF:Bitmap无法填充Adobe Reader视图问题

解决PDFsharp控件转PDF后无法填满Adobe Reader视图的问题

看起来你遇到的核心问题是控件生成的Bitmap默认DPI(96)和PDF的标准坐标系统(72点/英寸)不匹配,导致生成的PDF内容在Reader里显示时无法填满A4页面。下面是具体的修复方案和代码调整:

关键问题分析

  • DrawToBitmap生成的Bitmap默认是96 DPI,而PDFsharp遵循的PDF标准是72点/英寸(1英寸=72个PDF点)。
  • 直接按控件原始尺寸生成Bitmap再转PDF,会因为DPI差异导致内容被缩放,最终无法填满A4页面的视图区域。

修复步骤及代码调整

1. 明确A4的PDF标准尺寸

A4的标准PDF尺寸( portrait 竖版)是:

  • 宽度:595.276 PDF点
  • 高度:841.89 PDF点

2. 调整代码:让Bitmap适配PDF页面

我们可以通过计算缩放比例,让控件生成的Bitmap刚好填满A4页面,同时保持内容比例不拉伸。修改你的VB代码如下:

Dim docum As New PdfDocument()
' 获取A4页面的标准PDF尺寸
Dim a4Size = PdfPageSizeConverter.ToPoint(PdfPageSize.A4, PdfPageOrientation.Portrait)
Dim a4Width As Double = a4Size.Width
Dim a4Height As Double = a4Size.Height

For i As Integer = 0 To FoglioFattura1.listaPagIndex.Count - 1
    ' 生成与控件尺寸一致的Bitmap
    Dim memImage = New Bitmap(FoglioFattura1.Width, FoglioFattura1.Height)
    FoglioFattura1.DrawToBitmap(memImage, New Rectangle(0, 0, FoglioFattura1.Width, FoglioFattura1.Height))
    
    ' 创建A4格式的PDF页面
    Dim page As PdfPage = docum.AddPage()
    page.Size = PdfPageSize.A4
    
    Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
    
    ' 计算缩放比例:确保内容按比例填满页面,避免拉伸
    Dim scaleX As Double = a4Width / memImage.Width
    Dim scaleY As Double = a4Height / memImage.Height
    Dim finalScale As Double = Math.Min(scaleX, scaleY)
    
    ' 计算居中位置,让内容在页面里居中显示
    Dim posX As Double = (a4Width - memImage.Width * finalScale) / 2
    Dim posY As Double = (a4Height - memImage.Height * finalScale) / 2
    
    ' 将Bitmap绘制到PDF页面,应用缩放和居中设置
    gfx.DrawImage(XImage.FromGdiPlusImage(memImage), posX, posY, memImage.Width * finalScale, memImage.Height * finalScale)
    
    ' 释放Bitmap资源
    memImage.Dispose()
Next

' 保存并释放PDF文档
docum.Save("你的输出文件路径.pdf")
docum.Dispose()

3. 额外优化:直接设置Bitmap的DPI

如果你希望从源头匹配PDF的DPI,可以在生成Bitmap后修改其DPI属性,这样PDFsharp会按标准比例处理内容:

' 在生成Bitmap后添加这行代码
memImage.SetResolution(72, 72)

注意:这种方式需要确保你的控件尺寸本身是按A4的72DPI设计的(比如595x842像素),否则还是需要配合上面的缩放逻辑。

验证效果

生成PDF后打开Adobe Reader,按下快捷键Ctrl+0切换到「适合页面」视图,此时内容应该会完全填满A4页面的显示区域。

内容的提问来源于stack exchange,提问作者f.rizzo3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:20:19