Question

I want to export my gird view to a PDF but I ran into trouble. I tried two different ways but both had errors. In the first one, VS won't recognize the following code:

Image PNG= Image.GetInstance(imagepath + "/test.PNG");
doc.Add(PNG);

I should mention that my PDF consist some pictures.

// #1
protected void Button1_Click(object sender, EventArgs e)
{
    string pdfpath = Server.MapPath("PDFs");
    string imagepath = Server.MapPath("Images");
    Document doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

    try
    {
        PdfWriter.GetInstance(doc, new FileStream(pdfpath + "Certificates/Dormaj-Certificates.pdf", FileMode.Create));
        doc.Open();
        doc.Add(new Paragraph("GIF"));

        Image gif = Image.GetInstance(imagepath + "/mikesdotnetting.gif");
        doc.Add(gif);
    }
    catch (Exception ex)
    {
        //Log error;
    }
    finally
    {
        doc.Close();
    }
}

Then I tried this code which gave me the error about image, it says that it can not find the image path.

// #2
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pnlPerson.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
var appDataPath = Server.MapPath("~/Certificates/");
if (!Directory.Exists(appDataPath))
{
    //Directory.Create(appDataPath);
}
var filePath = Path.Combine(appDataPath, Path.GetRandomFileName() + ".pdf");
using (var output = File.Create(filePath))
{
    // Do stuff here
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}
Was it helpful?

Solution

I found the problem! I have corrected the first way! That was all because of my image addresses! Because i used images in my grid view, this problem is occurred! The only work is needed to solve this problem is to give a direct address to our images. e.g ~/image/test.jpg should be changed to http..yoursite/image/test.jpg. That is it!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top