The document has no pages - asp.net

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/

Related

How to write text on different page based on text of exiting pdf using itextsharp

How to write Text on different pages on exiting pdf which have more then 1 page.
For example 'Hitesh Second Page' I want to write this word on second page
'Hitesh Third Page' I want to write this word on Third page
Below code work only for pdf which have one page.
string fileName = "test.pdf";
string oldFile = System.Web.Hosting.HostingEnvironment.MapPath("~/AuthDoc/CoverPage.pdf");
string newFile = System.Web.Hosting.HostingEnvironment.MapPath(fileName);
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
string text = "";
cb.BeginText();
text = "Hitesh Third Page";
cb.ShowTextAligned(3, text,500,500, 0);
cb.EndText();
cb.BeginText();
text = "Hitesh Second Page";
cb.ShowTextAligned(2, text,500,500, 0);
cb.EndText();
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate( page, 0, 0);
document.Close();
fs.Close();
writer.Close();
reader.Close();
byte[] bytes = System.IO.File.ReadAllBytes(newFile);
return bytes;
Thanks,
Hitesh
When using a Document / PdfWriter pair to create a document, you create the pages in their final order, i.e. you first create the first page, then the second, then the third, ...
In your code you appear to try to start by creating the third page and then continue by creating the second one. You'll have to sort the code accordingly.
As soon as you have sorted your code, you can use the Document method NewPage to switch to the next page:
document.NewPage();
Beware, though, iText ignores the NewPage call if there is no content whatsoever on the page in question. To override this, you can make iText believe it is not empty using the PdfWriter property PageEmpty before calling NewPage:
writer.PageEmpty = false;
document.NewPage();
That been said, though...
How to write Text on different pages on exiting pdf
For such a task you should not use a Document / PdfWriter pair to start with, use a PdfReader / PdfStamper pair! In a PdfStamper you can quite freely jump between pages...

How to create a pdf using webservice

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.

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)
{
}

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