How to create a pdf using webservice - asp.net

I am using jquery ajax to call function from webservice.
In that function I am creating a pdf file using itextsharp tool.
I want that my pdf file created should open in browser when return.
can anyone help me what should be my return type for that
Below is the code I am using in webservice
public void GeneratePDf(string ID) {
string attachment = "attachment; filename=" + ID + ".pdf";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
htextw.AddStyleAttribute("font-size", "12px");
htextw.AddStyleAttribute("color", "Black");
Page pg = new Page();
HtmlForm frm = new HtmlForm();
pg.EnableEventValidation = false;
pg.RenderControl(htextw);
Document document = new Document();
document = new Document(PageSize.A4, 10, 10, 0, 0);
PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
document.Open();
Font verdana = FontFactory.GetFont("Verdana", 10, Font.BOLD, new CMYKColor(75, 68, 67, 90));
PdfPCell blank1 = new PdfPCell(new Phrase("Hello ", verdana));
document.Add(blank1);
//document.Add(tablegrid);
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
HttpContext.Current.Response.Write(document);
}
Can anyone tell me what I am doing wrong

The short answer is, "don't use AJAX for this", you are creating unnecessary complication. Instead, just make a normal GET/POST request via your browser. You can still use JavaScript if you want but the important part is that you have the browser make the request so that it can receive the response.
The long answer is...
Web servers respond to requests from web browsers and things happen just as you expect them to (usually). Web browsers have a list of content types that they are aware and use this list to sometimes parse the server's response and sometimes hand it off to a 3rd party application. Once you start messing around with AJAX and other similar technologies you break this model and are saying that you want to handle the processing instead of the browser. The browser will broker your request and the server's response but otherwise it won't do anything unless you tell it to. This works great for string-like things but gets much more complicated when you deal with binary data.

Related

How to convert aspx page to pdf file? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Directly convert .aspx to .pdf
I have made one aspx page and generated chart on it through chart control of asp.net.
But i am not able to generate this generated chart to pdf document. i want to make my aspx page as pdf document. Thank you in advance for support.
When you try to convert the aspx page to pdf that means inturn you are going to convert the rendered html to pdf so here is a good link that may help you though i did not tried it but looks promising
It's Here
NB:I am assuming that your page does not include any flash charting.
use itextsharp.dll I m sure you can get ur page in pdf using this dll
very easy to implement.
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
// This will be on button's click
string attachment = "attachment; filename=" + filename+ ".pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
htextw.AddStyleAttribute("font-size", "7pt");
htextw.AddStyleAttribute("color", "Black");
Panel_Name.RenderControl(htextw);//Name of the Panel
Document document = new Document();
document = new Document(PageSize.A4, 5, 5, 15, 5);
FontFactory.GetFont("Arial", 50, iTextSharp.text.BaseColor.BLUE);
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
Response.Write(document);
Paste this some where on page
public override void VerifyRenderingInServerForm(Control control)
{
}

ASP.Net page export to pdf

I got stuck with my ASP.Net export to PDF. Below are my codes. Please help.
Response.Clear();
Response.Buffer = true;
Response.Charset = Encoding.UTF8.HeaderName;
Response.ContentEncoding = Encoding.UTF8;
Response.Write(string.Format("<meta http-equiv=Content-Type content=text/html;charset={0}>", Encoding.UTF8.HeaderName));
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-disposition", "attachment; filename=pdffilename.pdf");
StringBuilder sb = new StringBuilder();
sb.Append("MIME-Version: 1.0\r\n");
sb.Append("X-Document-Type: Worksheet\r\n");
sb.Append("Content-Type: multipart/related; boundary=\"----=mtrSystem\"\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-Type: text/html; charset=\"utf-8\"\r\n");
sb.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");
sb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:pdf\">\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-ID: baiduimg\r\n");
sb.Append("Content-Transfer-Encoding: base64\r\n");
sb.Append("Content-Type: image/png\r\n\r\n");
Can i use this way to export my ASP.Net page to PDF?
Html-to-pdf.net allows for converting html to pdf. TO get the html from an asp.net page, use the following code:
StringWriter sw = new StringWriter();
Server.Execute("PageToConvert.aspx", sw);
string htmlCodeToConvert = sw.GetStringBuilder().ToString();
Then pass the html to the pdf generator:
public byte[] GetPdfBytesFromHtmlString (string htmlString)
You can then save the bytes to the response to send to client, or save on the server as a local file.
EDIT:
Something to keep in mind, html-to-pdf does cost money, but for my last project it was a justified expense. You can use the trial version to figure out what you needd.
I'm not entirely sure what you're trying to do, but generally I can highly recommend PDFSharp for creating PDF documents in code...

The document has no pages

I am using the below code to export gridview to PDF
form1.Controls.Clear();
form1.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
string html = "<html><body>" + sw.ToString() + "</body></html>";
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.AddAuthor("Ram");
document.AddSubject("Export To pdf");
document.Open();
string tempFile = Path.GetTempFileName();
using (StreamWriter tempwriter = new StreamWriter(tempFile, false))
{
tempwriter.Write(html);
}
HtmlParser.Parse(document, tempFile);
document.Close();
writer.Close();
File.Delete(tempFile);
writer = null;
document = null;
Response.End();
I have checked that grridview has 10 rows by putting breakpoint. But I am getting error at
document.Close();
that
The document has no pages.
Any suggestion how to fix it?
1) Setting a breakpoint to see that your grid view has 10 rows helps, but only checks part of the problem. You also need to check the contents of tempFile. That's what iText is actually working with. If it's empty, you'll sill get the "doc has no pages" exception.
2.1) HtmlParser no longer exists within iText. Having said that, I just dug up this code sample via google:
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("html1.pdf"));
HtmlParser.parse(document, "example.html");
}
No opens or closes, just a call to HtmlParser. It's quite possible that HtmlParser checks to see if the document is already open, and won't proceed if it is... that would explain the behavior you're seeing.
2.2) The "correct" way to convert HTML these days goes something like this:
String html = readHtml();
List<Element> objects = HTMLWorker.parseToList(new StringReader(html), null);
for (Element element : objects)
document.add(element);
I had same issue and the below suggestion help and my issue is solved
Document has no pages means your GridView data is lost when you export.
Hence in the Export button event rebind the GridView with data from database
https://www.aspforums.net/Threads/264988/Export-GridView-to-PDF-Error-Document-has-no-pages/

How to get file size of multiple file download

I am writing an ASP.NET web application.
I calculate the total size of my PDF file which is mentioned below. What does this return? When I download a 2KB file, it returns a size of 2KB, which is correct. But when I download 2 files each of size 2KB, then the total size it returns is 2.16KB. Is that correct? Should it return 4KB?
StringReader reader = new StringReader(content);
MemoryStream ms = new MemoryStream();
Document doc = new Document(PageSize.A4, 50, 50, 30, 30);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, ms);
doc.Open();
try
{
parser.Parse(reader);
}
catch (Exception ex)
{
Paragraph paragraph = new Paragraph("Error! " + ex.Message);
paragraph.SetAlignment("center");
Chunk text = paragraph.Chunks[0] as Chunk;
if (text != null)
{
//text.Font.Color = iTextSharp.text.BaseColor.RED;
}
doc.Add(paragraph);
}
finally
{
doc.SetMargins(10, 10, 10, 10);
doc.Close();
}
Byte[] buffer = ms.GetBuffer();
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=FileName.pdf");
//Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
Sounds like you're opening two files into the same buffer and expecting them to be appended one to the other. Instead, the second is replacing the first.
Try all this stand-alone in a simple C# program. If it doesn't work there, it clearly won't work in an ASP page. OTOH, if it does work there, but not in ASP, then its an ASP issue, not a problem with iTextSharp.
PS: I thought doc.close would close the stream used by PdfWriter as well. Looking at the code, it will by default (protected boolean closeStream = true; from the java source). Something might have called setCloseStream(false) somewhere along the line.
PPS: Stacking two PDFs into the same binary stream is Not A Good Idea. You need to write them out as separate attachments... at which point this whole issue is moot.

Export a data set to Excel and raise a file download dialog from an asp.net web method

I am using the following code to export a data set to an Excel sheet.
[WebMethod]
public static void ExporttoExcel()
{
DataSet ds;
productfactory pf=new productfactory();
ds = pf.getproducts();
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";
response.Write(sw.ToString());
// response.End();
}
}
}
The problem is that it's not raising file download and hence no export is taking place. The same code works fine in a normal method. But with the web method it's not working.
I suggest to make an HttpHandler ending in ashx, and place inside him your code that create the excel file.
then call it from your javascript code like that.
document.location.href = "ExporttoExcel.ashx";
The problem is that WebMethods are not designed to allow you to interact with the Response object (evident in that it wasn't available and you had to use HttpContext.Current.Response to get to it). WebMethods are designed to be blackbox to the user. They will perform and action and/or return a value.
Perhaps you can give us a better idea of what you are trying to accomplish and we can suggest an alternate solution.
u can use to create a dynamic iframe with URL set to the Web Handler to generate the Excel this will raise the file download with out posting the current page.

Resources