Merge PDF by streams - asp.net

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.

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:

download file inside updatepanel with out PostBackTrigger

I am using this part of code to download file using the onClick event for imageButton inside UpdatePanel, it works fine if I add the imageButton as PostBackTrigger for the updatePanel, is there away to do that with out full postback?
Dim stream As IO.Stream = Nothing
Dim bytesToRead As Integer = 10000
Dim buffer As Byte() = New Byte(bytesToRead - 1) {}
Try
Dim fileReq As Net.HttpWebRequest = CType(Net.HttpWebRequest.Create(FileURL), Net.HttpWebRequest)
Dim fileResp As Net.HttpWebResponse = CType(fileReq.GetResponse(), Net.HttpWebResponse)
If fileReq.ContentLength > 0 Then fileResp.ContentLength = fileReq.ContentLength
stream = fileResp.GetResponseStream()
Dim resp = HttpContext.Current.Response
resp.ContentType = "application/octet-stream"
resp.AddHeader("Content-Disposition", "attachment; filename=""" & FileName & """")
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString())
Dim length As Integer
Do
If resp.IsClientConnected Then
length = stream.Read(buffer, 0, bytesToRead)
resp.OutputStream.Write(buffer, 0, length)
resp.Flush()
buffer = New Byte(bytesToRead - 1) {}
Else
length = -1
End If
Loop While length > 0
Finally
If stream IsNot Nothing Then
stream.Close()
End If
End Try
I found the solution.
#HATCHA's answer on Asp:progress won't end anitmation when file is downloaded from ashx file was great.
what #VDWWD said was wonderful , But not in my case, because I need a button to create the pdf file before starting the download. which means the client side click won't be useful.
ScriptManager.RegisterClientScriptBlock(Me, GetType(Page), "downloadFileExport", "javascript:window.location ='" & ResolveUrl("~/report/download.ashx?url=" & url & "&fName=" & fName) & "';", True)

PDF doesn't Download itextsharp [duplicate]

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)

Capture response stream and output to file

We are using an online pdf encoding service where we send them the raw html and they return the pdf document. We want to take the WebResponse and immediately download it as a file to their desktop. This seems so straightforward and yet I can't seem to capture the stream correctly for download. I've tried many different approaches but I always end up with a 0 byte file for download. This is my latest incarnation which has gotten overly complicated but it still doesn't work.
Dim request = DirectCast(HttpWebRequest.Create(Url), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Using dataStream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
Try
Dim response As WebResponse = request.GetResponse
Dim bytes As Byte()
Using st As Stream = response.GetResponseStream
Dim ByteList As New ArrayList
Dim reader As New BinaryReader(st)
Dim length As Integer
While (InlineAssignHelper(bytes, reader.ReadBytes(1024))).Length > 0
ByteList.Add(bytes)
length += bytes.Length
bytes = New Byte(length - 1) {}
Dim position As Integer = 0
For Each b As Byte() In ByteList
Array.Copy(b, 0, bytes, position, b.Length)
position += b.Length
Next
End While
End Using
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf")
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Report Detail.pdf; size={1}", "attachment", bytes.Length.ToString()))
HttpContext.Current.Response.BinaryWrite(bytes)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Close()
HttpContext.Current.Response.End()
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function

how to set password on PDF file using ITextSharp without downloading that PDF File?

i create a simple PDF creator application using ASP.NET. that application will create a PDF file on the fly with the password for securing that document. here's my code:
Sub createPDFFile()
Dim doc As Document = New Document
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"pdf\result.pdf", FileMode.Create))
doc.Open()
doc.Add(New Paragraph("Hello World!! only Testing"))
doc.Close()
SetPDFPassword(Server.MapPath("~/pdf/result.pdf"), "resultwithpassword.pdf", "12345")
Response.Redirect("pdf/1.pdf")
End Sub
and here's my code for add a password to the PDF file:
Private Sub SetPDFPassword(ByVal FullPathPdfFileName As String, ByVal DownloadPDFFileName As String, ByVal ForOpenPassword As String)
Dim sname As String = FullPathPdfFileName
Dim sname1 As String = New System.IO.FileInfo(FullPathPdfFileName).DirectoryName & "/test.pdf"
Dim reader As New PdfReader(sname)
Dim n As Integer = reader.NumberOfPages
Dim document As New Document(reader.GetPageSizeWithRotation(1))
Dim writer As PdfWriter = PdfWriter.GetInstance(document, New IO.FileStream(sname1, IO.FileMode.Create))
writer.SetEncryption(PdfWriter.STRENGTH128BITS, ForOpenPassword, Nothing, PdfWriter.AllowPrinting)
document.Open()
Dim cb As PdfContentByte = writer.DirectContent
Dim page As PdfImportedPage
Dim rotation As Integer
Dim i As Integer = 0
While i < n
i += 1
document.SetPageSize(reader.GetPageSizeWithRotation(i))
document.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 OrElse rotation = 270 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _
reader.GetPageSizeWithRotation(i).Height)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _
0)
End If
End While
document.Close()
writer.Close()
Dim PDFfile As New IO.FileStream(sname1, IO.FileMode.Open)
Dim FileSize As Long
FileSize = PDFfile.Length
Dim buffer As Byte() = New Byte(CInt(FileSize) - 1) {}
PDFfile.Read(buffer, 0, CInt(FileSize))
PDFfile.Close()
System.IO.File.Delete(sname1)
Response.AddHeader("Content-Disposition", "attachment;filename=" & DownloadPDFFileName)
Response.ContentType = "application/pdf"
Response.BinaryWrite(buffer)
Response.Flush()
Response.Close()
End Sub
that code is works perfectly. it can generate a PDF file and add some password to open, but the PDF file will be send to the user. has anyone know how to generate a PDF file with password but that result file still on the server and only can be shown from web browser (not showing a download prompt)?? thanks in advance.. :D
Correct me if I'm wrong but I think that it is up to the browser to show the pdf in the browser or ask you if you want to download it.
Adobe Acrobat plug in can be downloaded at http://www.adobe.com/ and is a plug in to help the user display the pdf in the browser.
How to display the pdf in the broswer with the plugin installed: http://www.okanagan.bc.ca/administration/itservices/edtech/elearn/Configuring_the_browser_to_show_pdf_files.html

Resources