如果图像源不是包含协议的完全限定 URL,则 iTextSharp 假定它是基于文件的 URL。解决方案是将所有图像链接转换为绝对形式http://YOUR_DOMAIN/File/Image?path=Root/001.jpg
.
您还可以在解析器上设置一个全局属性,其工作方式与 HTML 几乎相同<BASE>
tag:
//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://YOUR_DOMAIN");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);
下面是一个针对 iTextSharp 5.1.2.0 的完整工作 C# 2010 WinForms 应用程序,它展示了如何使用相对图像并使用全局提供程序设置其基础。一切都与你的代码几乎相同,尽管我通过了一堆using
声明以确保正确清理。确保观察所有内容的前导和尾随正斜杠,基本 URL 仅直接添加到前面SRC
属性,如果做得不正确,你可能会得到双斜杠。我在这里硬性地设置了一个域,但您应该能够轻松使用System.Web.HttpContext.Current.Request
object.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string html = @"<img src=""/images/home_mississippi.jpg"" />";
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "HtmlTest.pdf");
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(PageSize.TABLOID)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
using (StringReader reader = new StringReader(html)) {
using (HTMLWorker worker = new HTMLWorker(doc)) {
//Create a provider collection to set various processing properties
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
//Set the image base. This will be prepended to the SRC so watch your forward slashes
providers.Add(HTMLWorker.IMG_BASEURL, "http://www.vendiadvertising.com");
//Bind the providers to the worker
worker.SetProviders(providers);
worker.Parse(reader);
}
}
doc.Close();
}
}
}
this.Close();
}
}
}