我正在尝试使用iTextSharp
将网页图片添加到pdf中我正在尝试使用与本地图像相同的代码
using (var pdfDoc = new Document())
using (var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream)) {
pdfDoc.Open();
Image tif = Image.GetInstance("www.myimage.com");
pdfDoc.Add(tif);
pdfDoc.Close();
}
答案 0 :(得分:4)
您必须先发送http网络请求才能下载图片。
public Image DownloadImageFromURL(string url)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(filename);
httpWebRequest.AllowWriteStreamBuffering = true;
httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
httpWebRequest.Timeout = 30000; //30 seconds
webResponse = httpWebRequest.GetResponse();
webStream = webResponse.GetResponseStream();
Image downloadImage = Image.FromStream(webStream);
webResponse.Close();
return downloadImage;
}
//in your code
using (var pdfDoc = new Document())
using (var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream)) {
pdfDoc.Open();
Image tif = DownloadImageFromURL("www.myimage.com");
pdfDoc.Add(tif);
pdfDoc.Close();
}
使用此方法制作HttpWebRequest并下载图像。现在将其写入pdf。
答案 1 :(得分:3)
与其他发布的答案相反,您 NOT 需要发出单独的HTTP请求。只需确保在致电Image.GetInstance()
时使用an absolute URI:
string url = "http://upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Pollinationn.jpg/320px-Pollinationn.jpg";
using (Document document = new Document()) {
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
Image img = Image.GetInstance(url);
document.Add(img);
}