PDF doesn't Download itextsharp [duplicate] - asp.net

This code work perfect. The problem was the button was inside a control update panel and that cause some problem. But i already fixed and now works.
Dim documentoPDF As New Document(PageSize.A4, 10, 10, 10, 10)
Dim memStream As MemoryStream = New MemoryStream()
Dim writer As PdfWriter = PdfWriter.GetInstance(documentoPDF, memStream)
documentoPDF.Open()
Dim Paragraph1 As Paragraph = New Paragraph("First paragraph")
documentoPDF.Add(New Paragraph(Paragraph1))
documentoPDF.Close()
Dim bytesInStream As Byte() = memStream.ToArray()
memStream.Close()
'Dim memorystreaam As MemoryStream = New MemoryStream(bytesInStream)
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf")
Response.Buffer = True
Response.Cache.SetCacheability(HttpCacheability.NoCache)
'Response.OutputStream.Write(memStream.GetBuffer(), 0, memStream.GetBuffer().Length)
Response.BinaryWrite(bytesInStream)
Response.End()

It looks like you are not saving the PDF document into the stream somewhere.
Dim bin() As Byte
Dim stream As MemoryStream = New MemoryStream
documentoPDF.Save(stream, false)
bin = stream.ToArray
Response.ClearHeaders
Response.Clear
Response.Buffer = true
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", bin.Length.ToString)
Response.AddHeader("content-disposition", "attachment; filename="""" + txtnombre.Text + ".pdf, "")
Response.OutputStream.Write(bin, 0, bin.Length)

Related

Send Excel file to Browser Asp.net

I have been breaking my head for the last two days and can't get this to work. I have a report, which I am exporting to Excel and saving on the server file directory. That part works perfectly, I can see the file, and open it, all good. The issue relies on when I try to send it to the browser for download from the server. It does not download anything, I do see the Response Header with all the info on the browser but nothing happens.
Here's one of my many tries
Private Sub dxgvPOAll_ToolbarItemClick(source As Object, e As ASPxGridViewToolbarItemClickEventArgs) Handles dxgvPOAll.ToolbarItemClick
Select Case e.Item.Name
Case "ExportAll"
Using report As DevExpress.XtraReports.UI.XtraReport = New POs_Dashboard_Report()
Using ms As New System.IO.MemoryStream()
report.Name = "Backorder Tickets"
report.ExportOptions.PrintPreview.SaveMode = DevExpress.XtraPrinting.SaveMode.UsingSaveFileDialog
Dim xlsxExportOptions As New DevExpress.XtraPrinting.XlsxExportOptions() With {.ExportMode = DevExpress.XtraPrinting.XlsxExportMode.SingleFile, .ShowGridLines = True, .FitToPrintedPageHeight = True}
Dim folderPath As String = "~/Account/TemporaryFiles/" & Utilities.RetrieveEmployeeNumber() & "/" & Guid.NewGuid.ToString & "/"
Dim serverPath As String = Server.MapPath(folderPath)
Dim xlsxExportFilePath As String = serverPath & report.Name & ".xlsx"
Dim folderInf As New DirectoryInfo(serverPath)
If Not folderInf.Exists Then folderInf.Create()
report.ExportToXlsx(xlsxExportFilePath, xlsxExportOptions)
Try
Dim objRequest As FileWebRequest = CType(WebRequest.Create(xlsxExportFilePath), FileWebRequest)
Dim objResponse As FileWebResponse = CType(objRequest.GetResponse(), FileWebResponse)
Dim bufferSize As Integer = 1
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.AppendHeader("Content-Disposition:", "attachment; filename=" & xlsxExportFilePath)
Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString())
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim byteBuffer As Byte() = New Byte(bufferSize + 1 - 1) {}
Dim memStrm As MemoryStream = New MemoryStream(byteBuffer, True)
Dim strm As Stream = objRequest.GetResponse().GetResponseStream()
Dim bytes As Byte() = New Byte(bufferSize + 1 - 1) {}
While strm.Read(byteBuffer, 0, byteBuffer.Length) > 0
Response.BinaryWrite(memStrm.ToArray())
Response.Flush()
End While
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Catch e1 As ThreadAbortException
Catch ex As Exception
End Try
End Using
End Using
End Select
End Sub
Here's what I see on the browser's Response-Header:

Issue with saving files into SQL as varbinary(max)

So, I have a web application that saves some attachments into SQL database as VarBinary(max), everything working smoothly until I realized that when I download the attachment from the database, the file is very big comparing to the original size, so a file with 400KB, the downloaded one would be 5MB! what I'm doing wrong?
The upload code is:
Dim img As FileUpload = CType(FileUpload1, FileUpload)
Dim imgByte As Byte() = Nothing
If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
Dim File As HttpPostedFile = FileUpload1.PostedFile
imgByte = New Byte(File.ContentLength - 1) {}
File.InputStream.Read(imgByte, 0, File.ContentLength)
cmd.Parameters.AddWithValue("#filetype", Path.GetExtension(FileUpload1.FileName).ToLower)
cmd.Parameters.AddWithValue("#attachment", imgByte)
End If
The download code:
Dim imagem As Byte() = CType((dr("attachment")), Byte())
Response.Clear()
Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0")
Response.AddHeader("Pragma", "no-cache")
Response.AddHeader("Content-Description", "File Download")
Response.AddHeader("Content-Type", "application/force-download")
Response.AddHeader("Content-Transfer-Encoding", "binary\n")
Dim fileName As String = "attachment; filename=" & "DOC_REFNO_" & "_" & regref_txt.Text.Replace("/", "_") & dr("filetype")
Response.AddHeader("content-disposition", fileName)
Response.BinaryWrite(imagem)
Thank you all.
so I found out that the download code is not correct, I changed it to the following code and worked perfectly.
Dim imagem As Byte() = CType((dr("attachment")), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = ContentType
Dim fileName As String = "attachment; filename=" & "DOC_REFNO_" & "_" & regref_txt.Text.Replace("/", "_") & dr("filetype")
Response.AddHeader("content-disposition", fileName)
Response.BinaryWrite(imagem)
Response.Flush()
Response.End()

Merge PDF by streams

I am in trouble with a .ashx which should merge some PDF memory-stream, in a simplest case, where I have in output only one stream, the output PDF stream are corrupted, but when I call another ashx which get in output only the single stream works, what I miss in the following code?
I collect memory-streams:
Dim streamDocument As MemoryStream = FumForm.CreatePdfDocument(context, _fumForm, _formTemplate, _match)
lReader.Add(New PdfReader(streamDocument))
then I would like append all pdf pages in an other pdf:
Dim document As Document = New Document(PageSize.A4, 0, 0, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, context.Response.OutputStream)
document.Open()
For Each r As PdfReader In lReader
For i As Integer = 1 To r.NumberOfPages
Dim page As PdfImportedPage = writer.GetImportedPage(r, i)
document.Add(Image.GetInstance(page))
Next
Next
Dim filename = String.Format("{0}{1}.pdf", "pippo", "test")
document.Close()
context.Response.Clear()
context.Response.ContentType = "application/pdf"
context.Response.AppendHeader("content-disposition", "inline; filename=""" & filename & """")
context.Response.Flush()
context.Response.Close()
context.Response.End()
CreatePdfDocument works well, and have this signature
static public MemoryStream CreatePdfDocument(HttpContext context,
FumForm form,
FumFormTemplate formTemplate,
Match match)
Any help will be really appreciated
The code first writes the whole PDF to context.Response.OutputStream
Dim document As Document = New Document(PageSize.A4, 0, 0, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, context.Response.OutputStream)
...
document.Close()
and thereafter clears and changes headers of the context.Response
context.Response.Clear()
context.Response.ContentType = "application/pdf"
context.Response.AppendHeader("content-disposition", "inline; filename=""" & filename & """")
To work correctly, all response object clearing and header manipulations have to be finished before the data may be written to the response stream.

How do I export only a datatable to Excel using only standard .Net and not a 3rd party dll?

I know this has been answered on here and a thousand other sites on the web, but every single one I've tried does not work as I want it to. I want to export ONLY a datatable, not the page I'm running the code from, and I want to do this without having to download a 3rd party dll. Every piece of code I've tried ends up exporting the page I'm running it from. Here's the current iteration I'm using...
Private Sub ExporttoExcel(table As DataTable)
Dim attachment As String = "attachment; filename=file.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
Dim tab As String = ""
For Each dc As DataColumn In table.Columns
Response.Write(tab + dc.ColumnName)
tab = vbTab
Next
Response.Write(vbLf)
Dim i As Integer
For Each dr As DataRow In table.Rows
tab = ""
For i = 0 To table.Columns.Count - 1
Response.Write(tab & dr(i).ToString())
tab = vbTab
Next
Response.Write(vbLf)
Next
Response.End()
End Sub
Can anyone explain why this doesn't work or how I can export ONLY the datatable into Excel?
I usually do this and it has worked for me (ds is a DataSet which has the data I want to push to excel):
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
string filename = "TEMP/ex1.xls";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// 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);
response.Write(sw.ToString());
response.End();
}
}
this should work with EPPlus
Public Shared Function ExportToExcel(FileName As String, SheetName As String, data As DataTable) As Boolean
Dim pck As ExcelPackage
pck = New ExcelPackage()
Try
Dim ws = pck.Workbook.Worksheets.Add(SheetName)
ws.Cells("A1").LoadFromDataTable(data, True)
Dim excel = pck.GetAsByteArray()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.Clear() 'really clear it :-p
HttpContext.Current.Response.BufferOutput = False
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AddHeader("cache-control", "max-age=0")
HttpContext.Current.Response.AddHeader("Pragma", "public")
HttpContext.Current.Response.AddHeader("Content-Length", excel.Length.ToString())
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=""" & FileName & ".xlsx""")
HttpContext.Current.Response.BinaryWrite(excel)
HttpContext.Current.Response.[End]()
Return True
Catch
Return False
Finally
pck.Dispose()
End Try
End Function
The only way to do this without some kind of 3rd party dll is to write a csv file.
Columns separated by semicolon, rows separated by /n

how to display an image from database?

i know too that this (kind of) question has been asked and answered many times. I myself have asked this once before. But I havnt been successful yet. how do I display the image in an image control for a particular employee ID... Heres my code:
`
bind()
GridView1.Visible = "True"
Dim strQuery As String = "SELECT Image FROM EmployeeTable WHERE EmployeeID =#EmployeeID"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value() = Convert.ToInt32(Request.QueryString("ImageID"))
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
**Dim bytes() As Byte = CType(dt.Rows(1)("Image"), Byte())**
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(1)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If`
Getting error at the line in bold. "There is no row at position 1"...
Actually I want to fetch (display) the image for a particular employee id. How does it concern a row position? I dont know why i have written that line of code. Anyway, I know there are guys who can help me with this and so I thank them in advance...
OK, Heres my code for adding the image to the database. This is working fine.
Dim imageData As Byte() = New Byte(FileUpload1.FileContent.Length) {}
FileUpload1.FileContent.Read(imageData, 0, Convert.ToInt32(FileUpload1.FileContent.Length))
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
If EmployeeIDTextBox.Text = "" Then
MsgBox("Please Enter EmployeeID to Add Photo")
Else
Dim com As New SqlCommand("UPDATE EmployeeTable SET IMAGE = #IM where EmployeeID='" & EmployeeIDTextBox.Text & "'", con)
Dim filePath As String = Server.MapPath(FileUpload1.FileName)
'Dim imageData As Byte() = File.ReadAllBytes(filePath)
com.Parameters.AddWithValue("#IM", imageData)
com.ExecuteNonQuery()
MsgBox("File Saved Successfully!")
End If
End Sub
And now this is my code for retrieving & displaying the same image in an image control...
bind()
GridView1.Visible = "True"
'If Request.QueryString("ImageID") IsNot Nothing Then
Dim strQuery As String = "SELECT Image FROM EmployeeTable WHERE EmployeeID =#EmployeeID"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value() = Convert.ToInt32(Request.QueryString("Image"))
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("Image"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(1)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End IF
This is not working...
Array indexes start from 0
Use
Dim bytes() As Byte = CType(dt.Rows(0)("Image"), Byte())
How is it that you don't know why you have written that?
The code you have will prompt a user to save the image file on his pc.
It will not show the image in an image control.
U can use a Http Handler and use the below code in ProcessRequest()
int Id = Convert.ToInt32(Request.QueryString["ImgId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImgId", conn))
{
command.Parameters.Add("#ImgId", SqlDbType.Int).Value = Id ;
conn.Open();
Response.ContentType = "image/gif"; //u can set it per ur requirement
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Img_Db" runat="server" ImageUrl="Image.ashx?ImgId=1"/>

Resources