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

PDFSharp+System.Drawing转TIF为PDF后,Firefox/react-pdf显示空白

问题分析与解决方案

你的问题出在仅调整PDF页面尺寸,却未对原始TIF图像进行实际缩放。PDFsharp的DrawImage只是在PDF中记录图像的缩放参数,原始大尺寸图像数据仍会被嵌入PDF。当PDF.js(Firefox/react-pdf底层引擎)尝试渲染这种被拉伸的超大图像时,会因内存溢出或图像处理栈溢出触发putBinaryImageData错误。

另外,代码里存在一个笔误:MyImage.Height应该是MyImg.Height,这会导致高度计算错误,进一步加剧渲染问题。

修正方案:先缩放原始图像,再生成PDF

正确的做法是先对System.Drawing.Image进行缩放,生成新的小尺寸图像后,再转换为XImage嵌入PDF。这样PDF中存储的是已缩小的图像数据,PDF.js能正常处理。

修改后的代码

System.Drawing.Image originalImg = System.Drawing.Image.FromStream(inStrm);
System.Drawing.Image scaledImg = originalImg;

double maxPixelSize = 14400.0; // 对应200in @72DPI
if (originalImg.Width > maxPixelSize || originalImg.Height > maxPixelSize)
{
    double scaleFactor = 1.0;
    // 计算等比例缩放因子,确保宽高都不超过最大值
    if (originalImg.Width > originalImg.Height)
    {
        scaleFactor = maxPixelSize / originalImg.Width;
    }
    else
    {
        scaleFactor = maxPixelSize / originalImg.Height;
    }

    // 计算缩放后的尺寸(取整避免浮点精度问题)
    int newWidth = (int)Math.Round(originalImg.Width * scaleFactor);
    int newHeight = (int)Math.Round(originalImg.Height * scaleFactor);

    // 创建缩放后的图像
    scaledImg = new Bitmap(newWidth, newHeight);
    using (var graphics = System.Drawing.Graphics.FromImage(scaledImg))
    {
        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        graphics.DrawImage(originalImg, 0, 0, newWidth, newHeight);
    }
}

// 用缩放后的图像生成PDF
XImage xImage = XImage.FromGdiPlusImage(scaledImg);
var pdfPage = new PdfPage();
pdfPage.Width = xImage.PixelWidth;
pdfPage.Height = xImage.PixelHeight;

doc.Pages.Add(pdfPage);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(xImage, 0, 0, pdfPage.Width, pdfPage.Height);

// 释放资源
originalImg.Dispose();
if (scaledImg != originalImg)
{
    scaledImg.Dispose();
}
xImage.Dispose();

关键优化点

  • 实际缩放图像:通过System.Drawing.Graphics生成缩小后的图像,而非仅在PDF中设置拉伸参数,从根源上减小PDF中的图像数据量。
  • 修正笔误:将MyImage.Height改为originalImg.Height,确保缩放因子计算正确。
  • 精度处理:对缩放后的尺寸取整,避免浮点值导致PDF尺寸异常。
  • 资源释放:显式释放图像资源,避免内存泄漏。
  • 插值模式:使用HighQualityBicubic保证缩放后图像的清晰度。

额外注意事项

  • 若TIF是多页文件,需循环处理每一页并添加到PDF的对应页面中。
  • 检查TIF的色彩模式(如CMYK),部分特殊色彩模式可能导致PDF.js渲染异常,必要时转换为RGB模式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:10:46