每次我遇到这个问题时,问题都是图像对于画布来说太大。更具体地说,即使是裸体IMG
标签内部将被包裹在Chunk
将会被包裹在Paragraph
,我认为图像溢出了段落,但我不能 100% 确定。
两个简单的修复方法是放大画布或在 HTML 上指定图像尺寸IMG
标签。第三种更复杂的途径是使用额外的提供商IMG_PROVIDER
。为此,您需要实施IImageProvider
界面。下面是一个非常简单的版本
public class ImageThing : IImageProvider {
//Store a reference to the main document so that we can access the page size and margins
private Document MainDoc;
//Constructor
public ImageThing(Document doc) {
this.MainDoc = doc;
}
Image IImageProvider.GetImage(string src, IDictionary<string, string> attrs, ChainedProperties chain, IDocListener doc) {
//Prepend the src tag with our path. NOTE, when using HTMLWorker.IMG_PROVIDER, HTMLWorker.IMG_BASEURL gets ignored unless you choose to implement it on your own
src = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\" + src;
//Get the image. NOTE, this will attempt to download/copy the image, you'd really want to sanity check here
Image img = Image.GetInstance(src);
//Make sure we got something
if (img == null) return null;
//Determine the usable area of the canvas. NOTE, this doesn't take into account the current "cursor" position so this might create a new blank page just for the image
float usableW = this.MainDoc.PageSize.Width - (this.MainDoc.LeftMargin + this.MainDoc.RightMargin);
float usableH = this.MainDoc.PageSize.Height - (this.MainDoc.TopMargin + this.MainDoc.BottomMargin);
//If the downloaded image is bigger than either width and/or height then shrink it
if (img.Width > usableW || img.Height > usableH) {
img.ScaleToFit(usableW, usableH);
}
//return our image
return img;
}
}
要使用此提供程序,只需将其添加到提供程序集合中,就像您所做的那样HTMLWorker.IMG_BASEURL
:
providers.Add(HTMLWorker.IMG_PROVIDER, new ImageThing(doc));
应该注意的是,如果您使用HTMLWorker.IMG_PROVIDER
你有责任弄清楚关于图像的一切。上面的代码假设所有图像路径都需要在前面添加一个常量字符串,您可能需要更新它并检查HTTP
在开始时。另外,因为我们说我们希望完全处理提供者的图像处理管道HTMLWorker.IMG_BASEURL
不再需要。
主代码循环现在看起来像这样:
string html = @"<img src=""Untitled-1.png"" />";
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.A4, 50, 50, 80, 100)) {
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
using (StringReader sr = new StringReader(html)) {
System.Collections.Generic.Dictionary<string, object> providers = new System.Collections.Generic.Dictionary<string, object>();
providers.Add(HTMLWorker.IMG_PROVIDER, new ImageThing(doc));
var parsedHtmlElements = HTMLWorker.ParseToList(sr, null, providers);
foreach (var htmlElement in parsedHtmlElements) {
doc.Add(htmlElement as IElement);
}
}
doc.Close();
}
}
}
最后一件事,请确保在此处发帖时指定您所针对的 iTextSharp 版本。上面的代码针对 iTextSharp 5.1.2.0,但我认为您可能使用的是 4.X 系列。