C# iTextSharp Html 到 Pdf 图像 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13593758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iTextSharp Html to Pdf image src
提问by Ovi
Convert a html to pdf using iTextSharp
使用 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;
}
}
The html contains several embedded images this way. This method was preferred as the same HTML is sent via email using LinkedResourcesin an AlternateView.
html 以这种方式包含几个嵌入的图像。这种方法是首选,因为相同的 HTML 是通过电子邮件发送LinkedResources的AlternateView。
foreach (var a in attachments)
{
//not production code
html += string.Format("<img src=\"cid:{0}\"></img>", a.Id.ToString());
}
However, when the pdf gets generated, there is no way to link the image id with the srcpart of the imghtml tag.
Ultimately, the pdf contains all the images up top and then the HTML with the <img src...ignored.
但是,当生成 pdf 时,无法将图像 ID 与html 标签的src一部分链接起来img。最终,pdf 包含顶部的所有图像,然后包含<img src...忽略的 HTML 。
I've read several possible solutions using either Paragraphs or the ImageAbsolutePosition but they don't seem to fit in.
我已经使用 Paragraphs 或 ImageAbsolutePosition 阅读了几种可能的解决方案,但它们似乎不适合。
回答by COLD TOLD
I found before that there is an issue when you use relative path in Itextsharp html pdf generation as you mentioned you can use the ImageAbsolutePosition which would require you to use paragraph to position your image correctly or if you still want to use html you would have to give direct path something like
我之前发现,当您在 Itextsharp html pdf 生成中使用相对路径时会出现问题,正如您提到的,您可以使用 ImageAbsolutePosition 这将要求您使用段落来正确定位您的图像,或者如果您仍然想使用 html,您将不得不给出直接路径类似的东西
html += string.Format("<img src=https://www.mysite.com/"+a.Id.ToString()+".imageext"></img>");
回答by mRizvandi
or you can convert virtual path to physical path with Server.MapPath like this:
或者您可以使用 Server.MapPath 将虚拟路径转换为物理路径,如下所示:
imgPhoto.ImageUrl = Server.MapPath(imgPhoto.ImageUrl);
回答by Prasanth
Try this way:
试试这个方法:
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();
回答by Pierre
Look at this site, looks like this can work.
看看这个网站,看起来这可以工作。
EDIT:
编辑:
Here is the code and text from the Referenced Site
这是来自参考站点的代码和文本
The people which have been working with iTextSharp and its HTMLWorker class for rendering one HTML page to PDF knows what I'm talking about: if the HTML contains images with relative path you'll probably get the "friendly" yellow screen!
使用 iTextSharp 及其 HTMLWorker 类将 HTML 页面渲染为 PDF 的人知道我在说什么:如果 HTML 包含具有相对路径的图像,您可能会看到“友好”的黄色屏幕!


It means that iTextShap tried to get one image with the relative path "images/screenshot.3.jpg" as the local file "C:\images\screenshot.3.jpg", so, that image doesn't exist. After doing a lot of research about how to provide to iTextSharp the correct image I found that one guy mentioned the "IImageProvider" interface that gives to iTextSharp the ability of find the image using custom methods. Well, I have done one example using iTextSharp 5.0.2.0. you can download it here.
这意味着 iTextShap 试图获取一张具有相对路径“images/screenshot.3.jpg”的图像作为本地文件“C:\images\screenshot.3.jpg”,因此,该图像不存在。在对如何向 iTextSharp 提供正确图像进行了大量研究后,我发现有人提到了“IImageProvider”接口,该接口使 iTextSharp 能够使用自定义方法查找图像。好吧,我已经使用 iTextSharp 5.0.2.0 做了一个例子。您可以在这里下载。
First at all you have to create one class that implements the IImageProvider Interface:
首先,您必须创建一个实现 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
}
After it, you have to assign this image provider as the "img_provider" interface property of the HTMLWorker class before rendering the HTML Content:
之后,您必须在呈现 HTML 内容之前将此图像提供程序分配为 HTMLWorker 类的“img_provider”接口属性:
HTMLWorker worker = new HTMLWorker(document);
Dictionary<string, object> interfaceProps = new Dictionary<string, object>() {
{"img_provider", new CustomItextImageProvider()}
};
worker.InterfaceProps = interfaceProps;
Now, when you render your HTML it should work with relative images.
现在,当您渲染 HTML 时,它应该可以使用相关图像。
Althought this is one example made for ASP.Net, the main idea is how to create one custom Image Provider for iTextSharp when rendering HTML and it could be used on any application, also, this could help you not only for getting images from a relative location, I have used it (with more code, obviously) for getting images from SharePoint or Sites that require authentication.
虽然这是为 ASP.Net 制作的一个示例,但主要思想是如何在呈现 HTML 时为 iTextSharp 创建一个自定义图像提供程序,并且它可以在任何应用程序上使用,此外,这不仅可以帮助您从亲戚那里获取图像位置,我已经使用它(显然有更多代码)从需要身份验证的 SharePoint 或站点获取图像。
回答by Venkatesh
var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("../Images/mevantage-logo.jpg"));

