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

PDFsharp 1.32升级至1.50后System.Drawing.Rectangle无法转换为XRect报错问询

报错原因

PDFsharp 1.50 版本对XGraphics相关API做了不兼容升级:1.32版本中DrawRectangle等方法支持自动将System.Drawing.Rectangle/RectangleF类型隐式转换为PDFsharp原生的PdfSharp.Drawing.XRect类型,1.50版本移除了这部分隐式兼容逻辑,强制要求传入原生XRect类型参数,所以会触发类型转换报错,和配置遗漏无关,属于版本迭代的API规则变更。

适配方案

方案1:直接替换矩形类型(推荐)

XRect的构造参数规则和System.Drawing.Rectangle完全兼容,同时支持传入int、double类型的坐标、宽高参数,还能避免你原代码中把double类型的页面宽高强转int带来的精度损失,修改后的代码如下:

protected void DrawVerticalLines(XGraphics graphics, double pageWidth, double pageHeight, int marginX, int marginY, int topMarginY)
{
    XPen pen = new XPen(XColors.Black, 0.5);
    // 把System.Drawing.Rectangle替换为PdfSharp.Drawing.XRect即可
    graphics.DrawRectangle(pen, new XRect(marginX, topMarginY, pageWidth - marginX * 2, pageHeight - marginY * 2 - topMarginY));
}

方案2:扩展方法兼容(适合存量代码多的场景)

如果项目中有大量System.Drawing.Rectangle传入PDFsharp方法的场景,可以新增扩展方法做快速转换,不需要逐行修改参数构造逻辑:

// 新增扩展方法
public static class RectangleExtensions
{
    public static XRect ToXRect(this System.Drawing.Rectangle rect)
    {
        return new XRect(rect.X, rect.Y, rect.Width, rect.Height);
    }
}

// 原有代码只需追加转换调用即可
graphics.DrawRectangle(pen, new Rectangle(marginX, topMarginY, (int)(pageWidth - marginX * 2), (int)(pageHeight - marginY * 2 - topMarginY)).ToXRect());

内容的提问来源于stack exchange,提问作者Jefferson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:24:05