Reputation: 4559
I am trying to add a web image to a pdf using iTextSharp
I am attempting to use the same code that you would use for a local image
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();
}
Upvotes: 5
Views: 3999
Reputation: 9372
Contrary to the other posted answer, you do NOT need to make a separate HTTP request. Just make sure you use an absolute URI when calling Image.GetInstance()
:
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);
}
This is clearly documented for the overloaded method call.
Upvotes: 4
Reputation: 14955
You have to make a http web request to download the image first.
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();
}
Use this method to make a HttpWebRequest and download the image. Now write it in to pdf now.
Upvotes: 5