Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# iTextSharp Html到Pdf图像src_C#_Itextsharp - Fatal编程技术网

C# iTextSharp Html到Pdf图像src

C# iTextSharp Html到Pdf图像src,c#,itextsharp,C#,Itextsharp,使用iTextSharp将html转换为pdf public static MemoryStream CreatePdfFromHtml( string html, List<Attachment> attachments) { MemoryStream msOutput = new MemoryStream(); using (TextReader reader = new StringReader(html))

使用iTextSharp将html转换为pdf

public static MemoryStream CreatePdfFromHtml(
        string html, List<Attachment> attachments)
    {
        MemoryStream msOutput = new MemoryStream();

        using (TextReader reader = new StringReader(html))
        using (Document document = new Document())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
            document.Open();

            foreach (var a in attachments)
            {
                var image = iTextSharp.text.Image.GetInstance(a.File);
                document.Add(image);
            }

            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);

            writer.CloseStream = false;
            document.Close();
            msOutput.Position = 0;
            return msOutput;
        }
    }
但是,生成pdf时,无法将图像id与
img
html标记的
src
部分链接。 最终,pdf包含顶部的所有图像,然后是忽略
的HTML


我已经阅读了使用段落或ImageAbsolutePosition的几种可能的解决方案,但它们似乎不适合。

我以前发现,在Itextsharp html pdf生成中使用相对路径时存在问题,正如您提到的,您可以使用ImageAbsolutePosition,这要求您使用段落来定位图像正确,或者如果仍要使用html 您必须给出如下的直接路径

 html += string.Format("<img src=https://www.mysite.com/"+a.Id.ToString()+".imageext"></img>");
html+=string.Format(“”);

或者您可以使用Server.MapPath将虚拟路径转换为物理路径,如下所示:

imgPhoto.ImageUrl = Server.MapPath(imgPhoto.ImageUrl);
试着这样做:

           PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
            document.Open();
            HTMLWorker worker = new HTMLWorker(document);

            Dictionary<string, object> providers = new Dictionary<string, object>();
            //Get url of the application
            string url = "http://www.url.com/" //url from which images are loaded
            //Bind image providers for the application
            providers.Add(HTMLWorker.IMG_BASEURL, url);
            //Bind the providers to the worker
            worker.SetProviders(providers);

            document.Open();
            worker.StartDocument();

            // Parse the html into the document

            worker.Parse(reader);
            worker.EndDocument();
            worker.Close();
            document.Close();
PdfWriter writer=PdfWriter.GetInstance(文档,msOutput);
document.Open();
HTMLWorker=新的HTMLWorker(文档);
字典提供者=新字典();
//获取应用程序的url
字符串url=”http://www.url.com/“//从中加载图像的url
//为应用程序绑定图像提供程序
Add(HTMLWorker.IMG_BASEURL,url);
//将提供程序绑定到工作程序
worker.SetProviders(提供者);
document.Open();
worker.StartDocument();
//将html解析到文档中
解析(读取器);
worker.EndDocument();
worker.Close();
document.Close();
看看,看起来这可以用

编辑:

以下是引用站点的代码和文本

使用iTextSharp及其HTMLWorker类将一个HTML页面呈现为PDF的人都知道我在说什么:如果HTML包含具有相对路径的图像,您可能会看到“友好”的黄色屏幕

这意味着iTextShap试图获取一个相对路径为“images/screenshot.3.jpg”的图像作为本地文件“C:\images\screenshot.3.jpg”,因此该图像不存在。 在对如何向iTextSharp提供正确的图像进行了大量研究之后,我发现一个人提到了“IImageProvider”接口,该接口使iTextSharp能够使用自定义方法查找图像。我用iTextSharp 5.0.2.0做了一个例子。你可以在这里下载

首先,您必须创建一个实现IImageProvider接口的类:

public class CustomItextImageProvider : IImageProvider
{
    #region IImageProvider Members
    public iTextSharp.text.Image GetImage(string src, Dictionary<string,string> imageProperties, ChainedProperties cprops, IDocListener doc)
    {
        string imageLocation = imageProperties["src"].ToString();
        string siteUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, "");

        if (siteUrl.EndsWith("/"))
            siteUrl = siteUrl.Substring(0, siteUrl.LastIndexOf("/"));

        iTextSharp.text.Image image = null;

        if (!imageLocation.StartsWith("http:") && !imageLocation.StartsWith("file:") && !imageLocation.StartsWith("https:") && !imageLocation.StartsWith("ftp:"))
            imageLocation = siteUrl + (imageLocation.StartsWith("/") ? "" : "/") + imageLocation; 

        return iTextSharp.text.Image.GetInstance(imageLocation);
    }
    #endregion
}
public类CustomItextImageProvider:IImageProvider
{
#区域IImageProvider成员
public iTextSharp.text.Image GetImage(string src、Dictionary imageProperties、ChainedProperties cprops、IDocListener doc)
{
字符串imageLocation=imageProperties[“src”].ToString();
字符串siteUrl=HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath,“”);
if(siteUrl.EndsWith(“/”)
siteUrl=siteUrl.Substring(0,siteUrl.LastIndexOf(“/”);
iTextSharp.text.Image Image=null;
如果(!imageLocation.StartWith(“http:”)&&&!imageLocation.StartWith(“文件:”)&&!imageLocation.StartWith(“https:”)&&&!imageLocation.StartWith(“ftp:”)
imageLocation=siteUrl+(imageLocation.StartsWith(“/”):“/”+imageLocation;
返回iTextSharp.text.Image.GetInstance(imageLocation);
}
#端区
}
之后,在呈现HTML内容之前,必须将此图像提供程序指定为HTMLWorker类的“img_提供程序”接口属性:

HTMLWorker worker = new HTMLWorker(document);
Dictionary<string, object> interfaceProps = new Dictionary<string, object>() { 
    {"img_provider", new CustomItextImageProvider()}
};
worker.InterfaceProps = interfaceProps;
HTMLWorker-worker=新的HTMLWorker(文档);
Dictionary interfaceProps=新字典(){
{“img_provider”,新CustomItextImageProvider()}
};
worker.InterfaceProps=InterfaceProps;
现在,当您呈现HTML时,它应该可以处理相对图像


虽然这是为ASP.Net制作的一个示例,但主要思想是如何在呈现HTML时为iTextSharp创建一个自定义图像提供程序,它可以用于任何应用程序,而且,这不仅可以帮助您从相对位置获取图像,我还使用了它(显然,还有更多代码)用于从SharePoint或需要身份验证的网站获取图像。

@kleopatra我已添加了引用网站的代码和文本。OP明确指出,图像是最终通过XmlWorker运行的HTML的一部分。因此,您的代码行不匹配。
var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("../Images/mevantage-logo.jpg"));
var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("../Images/mevantage-logo.jpg"));