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.
Related
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
Using a memory stream & the correct MIME type with Response.ContentType. Special characters are displayed instead of prompting to open a Word document. I'm using:
using (MemoryStream ms = new MemoryStream())
{
doc.SaveAs(ms);
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
ms.WriteTo(Response.OutputStream);
Response.End();
}
Here's an example of the output I get now rather than a prompt to open a Word document:
Turns out it was not a MIME or Response.ContentType issue at all. Being an MVC application, I was attempting to open the FileResult in a modal. Copy/Paste fail, as other buttons worked this way to display content. Not a Word document!
I'm using ASP.net with VB codebehind.
I need to be able to convert an excel file created in code into a byte array in order to send it to the client. Without saving the file to the server.
this is how i created the excel document
Dim APP As Excel.Application = New Excel.Application
Dim missing As Object = System.Reflection.Missing.Value
Dim Workbook As Excel.Workbook = (APP.Workbooks.Add(missing))
Dim worksheet As Excel.Worksheet = Workbook.ActiveSheet
'..Fill cells in worksheet..
This is how i transmit it:
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.Cookies.Clear()
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.CacheControl = "private"
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8
Response.AppendHeader("Content-Length", filebytes.Length.ToString())
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Expires", 60)
Response.AppendHeader("Conetnt-Disposition", "attachement; filename='MostIssuesByModelReport.xlsx'; size=" & filebytes.Length.ToString() & "; creation-date=" & Date.Now.ToString("R") & "; modification-date=" & Date.Now.ToString("R") & "; read-date=" & Date.Now.ToString("R"))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'write to client
Response.BinaryWrite(filebytes)
Response.End()
I just need to get the content of Workbook into filebytes
EDIT:
After looking around a bit more I can now make it download a file, however this file does not use the filename specified in the above code, it uses the name of the asp server page that the user is on, it also has a .aspx extension..however if I force it to open in excel it is correct. Besides popping up saying the source may be corrupted. Why is this happening and how can I fix it?
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! :)
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".