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

C# MVC使用iText7插入NAS图片至PDF路径错误咨询

解决iText7加载远程NAS图片时拼接本地路径的问题

问题原因

iText7的ImageDataFactory.Create(string)方法会优先把传入的字符串当成本地文件路径处理,不会自动识别为远程URL,所以才会把你的NAS URL拼到项目本地目录下,导致路径语法错误。

解决方案

别直接把URL传给ImageDataFactory.Create(),先通过WebClient把远程图片下载到内存流,再用内存流创建ImageData,就能彻底避免本地路径拼接的问题。

修改后的代码:

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("XXXXXX", "XXXXXXX");
    // 下载图片到内存流
    using (MemoryStream ms = new MemoryStream(client.DownloadData(@"https://202.180.99.51:5006/Jobs/Jobs/Quotes/12391/System/Plan.png")))
    {
        // 从内存流生成图片数据
        img = new Image(ImageDataFactory.Create(ms))
              .SetTextAlignment(TextAlignment.CENTER);
        table.AddCell(new Cell(4, 2).Add(img));
    }
}

重要说明

  • 用WebClient.DownloadData()获取图片字节数据并存入MemoryStream,全程在内存中处理图片,不依赖本地文件路径。
  • ImageDataFactory.Create(Stream)直接读取流里的图片数据,不会触发本地路径解析逻辑,从根源解决问题。
  • URL格式注意:Raw字符串(@)下用https://即可,不用转义成https:\\\\,避免路径格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 06:42:20