使用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;
}
}html以这种方式包含几个嵌入的图像。这种方法是首选的,因为在AlternateView中使用LinkedResources通过电子邮件发送相同的超文本标记语言。
foreach (var a in attachments)
{
//not production code
html += string.Format("<img src=\"cid:{0}\"></img>", a.Id.ToString());
}但是,在生成pdf时,无法将图像id与img html标记的src部分联系起来。最终,pdf包含顶部的所有图像,然后是忽略<img src...的超文本标记语言。
我已经阅读了几种可能的解决方案,使用段落或ImageAbsolutePosition,但它们似乎不适合。
发布于 2013-02-05 20:22:38
尝试这样做:
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();发布于 2012-11-28 06:08:13
我之前发现当你在Itextsharp生成中使用相对路径时有一个问题,你可以使用ImageAbsolutePosition,这将要求你使用段落来正确定位你的图像,或者如果你仍然想使用html,你必须给出直接路径,比如
html += string.Format("<img src=https://www.mysite.com/"+a.Id.ToString()+".imageext"></img>");发布于 2013-02-05 20:11:43
或者您可以使用Server.MapPath将虚拟路径转换为物理路径,如下所示:
imgPhoto.ImageUrl = Server.MapPath(imgPhoto.ImageUrl);https://stackoverflow.com/questions/13593758
复制相似问题