0

使用图像处理程序将相对路径转换为绝对路径。

    protected byte[] ConvertHTMLToPDF(string HTMLCode)
    {
        if (Request.Url == null)
            throw new Exception();

        var doc = new Document(PageSize.A4);
        doc.Open();

        var interfaceProps = new Hashtable();
        var ih = new ImageHander {BaseUri = Request.Url.ToString()};

        interfaceProps.Add("img_provider", ih);

        foreach (IElement element in HTMLWorker.ParseToList(new StringReader(HTMLCode), null, interfaceProps))
        {
            doc.Add(element);
        }

        var _xmlr = new XmlTextReader(new StringReader(HTMLCode));
        HtmlParser.Parse(doc, _xmlr);

        var stream = new MemoryStream();
        PdfWriter.GetInstance(doc, stream);

        doc.Close();
        return stream.ToArray();
    }

班级:

public class ImageHander : IImageProvider
{
    public string BaseUri;

    public Image GetImage(string src, Hashtable h, ChainedProperties cprops, IDocListener doc)
    {
        string imgPath;

        if (src.ToLower().Contains("http://") == false)
            imgPath = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + src;
        else
            imgPath = src;

        return Image.GetInstance(imgPath);
    }
}

最后的 imgPath 是正确的。但它不是静态文件,它是返回图像的动作 url,所以我需要在请求图像时传递 cookie。可能吗?

4

1 回答 1

1

是的,这是可能的,但您必须自己发送请求,而不是依赖该Image.GetInstance方法。例如,HttpClient您可以将 cookie 与请求一起发送:

var imageUrl = new Uri(imagePath);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
    cookieContainer.Add(
        new Uri(imageUrl.GetLeftPart(UriPartial.Authority)), 
        new Cookie("CookieName", "cookie_value")
    );
    var response = client.GetAsync(imageUrl).Result;
    response.EnsureSuccessStatusCode();
    Stream imageStream = response.Content.ReadAsStreamAsync().Result;

    // You've got the Stream here, read the documentation of iTextSharp 
    // how to create an Image instance from a Stream:
    return Image.FromStream(imageStream); // ?????

    // or maybe there's a method allowing you to create an Image from byte[]
    byte[] imageData = new byte[imageStream.Length];
    imageStream.Read(imageData, 0, imageData.Length);
    return Image.FromByteArray(imageData); // ?????
}
于 2013-07-03T08:31:15.317 回答