Click here to Skip to main content
15,887,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have this webservice C# in which i have a web method which when called via a jquery ajax request creates a PDF file using the iTextsharp library and the html data is passed as parameters to the web method.

This is the code
JavaScript
$('a#articlelink').on('click', function () {
 var articletitle = $(document).find('#articleTitle').text();
 var filename = articletitle;
 var articletext = $(document).find('div#articleText').html();
 var articledetails = $(document).find('div#articleDetails').html();
 var htmlcontent = '<div style="color:#ffffff; text-align:center; background-color:#4F9EC9; width:100%;">' + articletitle + '</div><br/><br/><div>' + articletext + '</div><br/><br/><div>' + articledetails + '</div><br/>';

 var param = { filename: filename, HtmlContent: htmlcontent };
 $.ajax({
         type: "POST",
         url: "../MyWebService.asmx" + "/" + "GenerateArticlePDF",
         data: JSON.stringify(param),
         contentType: "application/json; charset=utf-8",                    
         dataType: "json",
         success: function (response) {
          var aid = getParameterByName('aid');
          var eid = readCookie('empid');
          ArticleDownloadByUser(aid, eid);
          alert('PDF generated successfully.');
         },
         error: function (response) {
          alert('PDF generation failed.');
         },
         timeout: 60000
        });
       });


This is the web method
C#
[WebMethod(Description = "Article PDF Generate")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GenerateArticlePDF(string filename, string HtmlContent)
{
  string status = "";

  try
  {
    string DocContent = "";

    if (HtmlContent != null)
    {
       DocContent = HtmlContent.Replace("../cklibrary/", "http://localhost:81/MyApp/cklibrary/");
    }

    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    //HtmlTextWriter hw = new HtmlTextWriter(sw);
    //articleText.RenderControl(hw);
    StringReader sr = new StringReader(DocContent.ToString());
    Document pdfDoc = new Document(PageSize.LETTER, 15f, 15f, 15f, 15f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    HttpContext.Current.Response.Write(pdfDoc);
    //HttpContext.Current.Response.End();
    HttpContext.Current.ApplicationInstance.CompleteRequest();

    status = "success";
  }
  catch (Exception ex)
  {
    status = ex.Message.ToString();
  }

  return status;
}


The issue is that the dynamically generated PDF file is not downloading.

What changes do i need to make to download the pdf file.
Please advise.

Thanks in advance

What I have tried:

I am using iTextsharp 5.5.8 to generate the PDF from the html content that is passed to the web method. The pdf file is generated correctly but the file is not downloading. Instead the content of the pdf are supplied as json to the ajax request.
Posted
Updated 3-Mar-16 17:47pm
Comments
dan!sh 3-Mar-16 23:31pm    
Would it help if you create the PDF file, save it on server and just send the download link to client? Another way could be to send byte array to client which will be opened/saved as PDF.
Christopher Fernandes 3-Mar-16 23:36pm    
How to do either of that?
Christopher Fernandes 3-Mar-16 23:37pm    
Also if you dont mind just tell me why is the file not downloading.
j053pepe 29-Nov-16 12:20pm    
hi, i have other example, show your pdf in new page or div.

/// Call my html and send Id of document

function AbrirArchivo(DocumentoId) {
var url =
"/../WebServices/WS/Beca.asmx/GenerarPDF2?DocumentoId=" + DocumentoId;

var archiv = window;
archiv.open("../Inscritos/Archivos/Archivo.html", "PDF");
archiv.Ruta = url;
}

/*in my Archivo.html i have this code */
<!DOCTYPE html>


<meta charset="utf-8" />
<title>Documento
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta content="" name="description" />
<meta content="" name="author" />
<meta http-equiv="pragma" content="no-cache" />

html, body {
margin: 0;
padding: 0;
border: 0;
height: 100%;
overflow: hidden;
}

iframe {
width: 100%;
height: 100%;
border: 0;
}







$(document).ready(function () {

var Ruta = window.opener.Ruta;
crarPDF();

function crarPDF() {
$('#iframepdf').attr('src', Ruta);
}
});



/* end file */

in my asmx i have function
[WebMethod]
public void GenerarPDF2(string DocumentoId)
{
Stream stream = new MemoryStream(BLLAlumnoInscrito.TraerDocumento(int.Parse(DocumentoId)));
var MemoryStream = new MemoryStream();
stream.CopyTo(MemoryStream);

HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + "Beca" + ".pdf");
HttpContext.Current.Response.BinaryWrite(MemoryStream.ToArray());
HttpContext.Current.Response.Flush();
MemoryStream.Close();
HttpContext.Current.Response.End();
}

1 solution

You can save the PDF on the server and then send the download URL back to client. To do so, you can update the code as follows:

1. Create a FileStream object with path where file is to be saved.
2. Create Document object and create your file.
3. Create a PDFWriter object to save it to disk.
4. Get the file location (you would already have it since you need to mention that while creating FileStream) and return that from your service.

Create -> FileStream
Create -> Document
Create -> PDFWriter using GetInstance method and objects created above
Open -> Document
Write -> Content to Document
Close -> Document
Close -> Writer
Close -> FileStream
Dispose -> All disposable objects
Return -> File URL


On client side, use this URL to download file.

Alternate approach: Use MemoryStream instead of FileStream and use that object to get byte array. Then, write this byte array to output.

Here[^] is a link I just found to send PDF content as bytes.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900