Unable to open PDF after it's generated (vb.net) (asp.net) - asp.net

Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
PdfWriter.GetInstance(pdfDoc, New
FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
pdfDoc.Open()
pdfDoc.Add(New Paragraph("What is going on?"))
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
End Sub
Thank you in advance!
P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF

Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?
It would be better if you created the PDF file in memory first:
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();
Then you take the bytes of that file in memory, and send them to the Response:
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response

Related

set default name to PDF document with itextsharp

i am sending a PDF to my page and i want to set a default name when the user tries to save the PDF document.
i am using ItextSharp and VB.Net
Using s As MemoryStream = New MemoryStream()
Dim Pdf_Writer As PdfWriter = PdfWriter.GetInstance(DocumentPDF, s)
DocumentPDF.Open()
DocumentPDF.SetMargins(10.0F, 10.0F, 10.0F, 10.0F)
DocumentPDF.Add(Table)
DocumentPDF.Close()
contentX= s.ToArray()
HttpContext.Current.Response.Buffer = False
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ContentType = "Application/pdf"
HttpContext.Current.Response.BinaryWrite(contentX)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
End Using
.
Response.AddHeader("content-disposition", #"attachment;filename=""MyFile.pdf""");
this way download the file(yea, it sets a default name), but i just want to show the file and if the user wants to save it, well... save it(with a default name)
how can i set a default name to my PDF document?
try with this code:
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "inline; filename="filename".pdf")
Response.TransmitFile("filename")
Response.End()
I had a similar problem delivering a PDF via a handler page (.ashx). No matter what I set in the HTTP headers, saving from the browser PDF reader would always set the filename to "getpdf.pdf" when I used this url.
http://www.thepdfchef.com/handlers/getpdf.ashx?id=5188p
So what I did was add an escaped string after the handler path then the querystring at the end of that, like so:
http://www.thepdfchef.com/handlers/getpdf.ashx/Wellbeing%20And%20Domestic%20Assistance%20From%20John%20Paul?id=5188p
You should check for invalid characters and strip out any that could cause the name to be dangerous.

iTextSharp generate PDF and show it on the browser directly

How to open the PDF file after created using iTextSharp on ASP.Net? I don't want to save it on the server, but directly when the new PDF is generated, it shows on the browser. Is it possible to do that?
Here is the example for what I mean: Click here . But on this example, the file directly downloaded.
How can I do that?
Dim doc1 = New Document()
'use a variable to let my code fit across the page...
Dim path As String = Server.MapPath("PDFs")
PdfWriter.GetInstance(doc1, New FileStream(path & "/Doc1.pdf", FileMode.Create))
doc1.Open()
doc1.Add(New Paragraph("My first PDF"))
doc1.Close()
The code above do save the PDF to the server.
Thank you very much in advance! :)
You need to set Content Type of the Response object and add the binary form of the pdf in the header
private void ReadPdfFile()
{
string path = #"C:\Somefile.pdf";
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length",buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
(or) you can use System.IO.MemoryStream to read and display:
Here you can find that way of doing it
Open Generated pdf file through code directly without saving it onto the disk
The problem solved with the code below:
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim pdfDoc As New Document()
PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream)
pdfDoc.Open()
'WRITE PDF <<<<<<
pdfDoc.Add(New Paragraph("My first PDF"))
'END WRITE PDF >>>>>
pdfDoc.Close()
HttpContext.Current.Response.Write(pdfDoc)
HttpContext.Current.Response.End()
Hope help! :)

Export to Excel file as .zip to reduce file size. How to compress xmldata before sending it to the client?

I like to compress the xmldata before the data is provided to the client as an excel file. I am trying to compress and deliver it as a .zip file. its not working Here's my code below. Please help
I tried compressing it, converting it to bytes etc etc. The issue with below code is, the XSL transformation is not happening properly and the output excel file is raw xml with some .net exception at the end. (that's what I see on the .xls file that's downloaded at the end)
Before I started working on compression my below code was working fine that gives properly formatted excel file from the xml input. the excel file is so nice you can't even tell it was from XML.
pLEASE HELP with compression
Dim attachment As String = "attachment; filename=DataDownload.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
'Response.ContentType = "text/csv"
Response.Charset = ""
Dim ds As New DataSet()
Dim objXMLReader As XmlReader
objXMLReader = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteXmlReader(ConnectionString, CommandType.StoredProcedure, "SPName")
ds.ReadXml(objXMLReader)
Dim xdd As New XmlDataDocument(ds)
Dim xt As New XslCompiledTransform()
'xt.Transform(xdd, Nothing, Response.OutputStream)
Dim bytearr() As Byte
bytearr = System.Text.Encoding.Default.GetBytes(xdd.OuterXml)
Dim objMemStream As New MemoryStream()
objMemStream.Write(bytearr, 0, bytearr.Length)
objMemStream.WriteTo(Response.OutputStream)
xt.Transform(xdd, Nothing, Response.OutputStream)
Response.End()
Why you don't use XLSX-Format instead of XLS? It is already XML-Data compressed in a ZIP file. You can rename a XLSX file to ZIP to verify this.
Updated: By the way, ContentType in the case should be "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" instead of "application/vnd.ms-excel".

How do I create an XML file with ASP.NET and have it prompt to download?

I'm currently trying to write data (client machine) into a xml file where the user can save. However, I want the users to be able to decide on where they want to save this written xml file. Is there any controls or codes that I can use to allow the users to save the file?.
Update:
is that right way to do?
**HttpContext.Current.Response.Write(xw.ToStroing()); <<< ??????**
HttpContext.Current.Response.End();
update:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xw = XmlWriter.Create(ms, settings))
{
xw.WriteStartDocument();
xw.WriteStartElement("Name");
xw.WriteStartElement("Application");
................
......................
HttpContext.Current.Response.Write(xw.ToStroing());
HttpContext.Current.Response.End();
When you begin a file download, the client's browser will handle the file saving location.
If you want to force the file to download instead of open, add this HTTP header to your response:
Content-Disposition: attachment; filename="myFile.xml"
here is the link helps me :)
Where is the MemoryStream being used? You should pass the StringWriter to the XmlTextWriter constructor then Response.Write() the contents of the StringWriter
Add this after the Response.AddHeader line:
Response.ContentType = "application/octet-stream";
This will force download of files, regardless the file type.

ASP.NET page to image or PDF

I have an ASP.NET page like this:
http://farm4.static.flickr.com/3631/3690714302_c17b259863.jpg
My table is Gridview and some Label, anybody can tell me how to create a button to convert my page to image or PDF file and save it to desktop.
It can be done by code on the backend that renders the html into a memory Graphic object and then serves that resultant bitmap back, or by printing the page (on the server) through a PDF writer and then capturing the result.
Javascript, no.
Or google "online convert html pdf" and use one of those services.
Hai use iTextSharp to convert your webpage to pdf.
It looks very nice.
Just download the dll file and add reference to your application.
Then in button click give the coding as follows.
Response.ClearHeaders()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", attachment; filename="jaison.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(iTextSharp.text.PageSize.A2, 10, 10, 10, 10)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
Surely this code will help you.
All the best!

Resources