How open byte[] into adobe format? - asp.net

I has image into byte[]. I need to open it into adobe file in asp.net. I using following code :
byte[] bytes = contractimage.Value.Bytes;
if (bytes == null)
{
Response.Write("Not found.");
Response.End();
}
else
{
Response.AddHeader("content-disposition",
"attachment;filename=statement" + contractGuid.ToString() + ".pdf");
Response.ContentType = "application/pdf";
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.End();
}
But this code display an error that adobe canot dispalay this file it may be corrupted.
Please suggest

A byte[] of a bitmap is not a pdf document.
What you need to do is create a pdf doc that contains your Bitmap. If I were in your shoes I would probably use something like ITextSharp to do that.

You would have to format your output in the form of a PDF file, you are currently only sending the raw image data and not a properly formated PDF file.
You can refer to:
http://www.adobe.com/devnet/pdf/pdf_reference.html
for a specification of the PDF format or an easier solution is to use a third-party tool to accomplish your task.
Try a Google search for something like "pdf .net creator"

Related

Getting a corrupted XLSX file when writing it to Response.OutputStream

In ASP.Net, I'm using NPOI to write save to an Excel doc and I've just moved to version 2+. It worked fine writing to xls but switching to xlsx is a little more challenging. My new and improved code is adding lots of NUL characters to the output file.
The result is that Excel complains that there is "a problem with some content" and do I want them to try to recover?
Here is a pic of the xlsx file that was created from my Hex editor:
BadXlsxHexImage Those 00s go on for several pages. I literally deleted those in the editor until the file opened without an error.
Why does this code add so many NULs to this file??
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
byte[] buf = exportData.GetBuffer();
string saveAsFileName = sFileName + ".xlsx";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}; size={1}", saveAsFileName, buf.Length.ToString()));
Response.Clear();
Response.OutputStream.Write(buf, 0, buf.Length);
exportData.Close();
Response.BufferOutput = true;
Response.Flush();
Response.Close();
}
(I've already tried BinaryWrite in place of OutputStream.Write, Response.End in place of Response.Close, and setting Content-Length with the length of the buffer. Also, none of this was an issue writing to xls.)
The reason you are getting a bunch of null bytes is because you are using GetBuffer on the MemoryStream. This will return the entire allocated internal buffer array, which will include unused bytes that are beyond the end of the data if the buffer is not completely full. If you want to get just the data in the buffer (which you definitely do), then you should use ToArray instead.
That being said, why are you writing to a MemoryStream at all? You already have a stream to write to: the OutputStream. Just write the workbook directly to that.
Try it like this:
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", saveAsFileName));
workbook.Write(Response.OutputStream);
Response.Flush();
Response.Close();

Present a PDF Document on a Specific Page in ASP.NET

I am opening PDF documents using the following ASP.NET code,
Response.BufferOutput = true;
Response.Clear();
Response.ContentType = "application/pdf";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(documentURL);
using (HttpWebResponse responseDDRINT = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = responseDDRINT.GetResponseStream())
{
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, bufferSize)) > 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
}
Response.Flush();
}
}
My question is does anyone know how to present the PDF starting at a specifice page. For example, if the PDF document is 15 pages, we would like it to open with page 10 initially showing instead of opening at page 1.
I experimented with the "#page=" open parameter by adding this header, but it did nothing.
Response.AddHeader("content-disposition", "inline; filename=test.pdf#page=3");
You'll have to manipulate the PDF file on the fly.
Use something like http://pdfsharp.com/PDFsharp/ to stream out a copy of the file starting at a certain page.
Current versions of Adobe ready no longer support the page syntax, but they do support the bookmark syntax.
Why don't you make your document reachable through a regular link or through an HTTPHandler?
you may use a PDF manipulation library like ItextSharp to get your work done.

What's the easiest way to convert a BMP to a PDF in ASP.net

What's the easiest way to convert a BMP file to a single page PDF using ASP.net? I'm going to generate the 8.5" x 11" BMP in Flash (which means I can manipulate it to make it as easy as possible), then use a POST to upload it to an ASP page, which will convert it to a PDF and redirect the user to the PDF. I don't want to add any margins or anything else, it will be laid out properly in the BMP for full-bleed.
Would it be easier to convert it to PDF in Flash, then upload?
Thanks!
You can use iTextSharp to create a PDF and insert the image into the document. This can be done all in memory with a final PDF produced to client.
The following is an MVC method, stripped for display, but should see how to do this.
[HttpGet]
public FileStreamResult Export(int? ID)
{
MemoryStream stream = new MemoryStream();
Document pdf = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
PdfPTable tblImage = new PdfPTable(1);
tblImage.AddCell(Image.GetInstance(LogChart())); //The LogChart method returns image
pdf.Add(Image);
pdf.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

asp.net ashx handler prompting download instead of displaying file

I implemented a generic handler in my application which works great for images, but when I manually type the handler URL in the browser with the image's querystring it prompts download instead of displaying. Here is my code:
public void ProcessRequest(HttpContext context)
{
if (this.FileName != null)
{
string path = Path.Combine(ConfigurationManager.UploadsDirectory, this.FileName);
if (File.Exists(path) == true)
{
FileStream file = new FileStream(path, FileMode.Open);
byte[] buffer = new byte[(int)file.Length];
file.Read(buffer, 0, (int)file.Length);
file.Close();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + this.FileName + "\"");
context.Response.BinaryWrite(buffer);
context.Response.End();
}
}
}
I am using the octet-stream because I'm dealing with more than just images and I don't always know the content type of the file. Thanks in advance!
The only way is to specify correct ContentType so the browser know what to do with receiving file, depending on installed plugins (for example, view pdf files in browser frame) and system assosiations (for example, offer to open document in MS Office instead of simple download)
You can try to specify Content Type depending on file extension, i.e.:
if(Path.GetExtension(path) == ".jpg")
context.Response.ContentType = "image/jpeg";
else
context.Response.ContentType = "application/octet-stream";
If you store the ContentType as part of the files metadata, when you pull it back down your could use it.
theFile = GetFile(id)
context.Response.ContentType = theFile.Type;
The content-disposition header is the one that causes your browser to show the download dialog. Remove that line and it will show in the browser.

ASP.NET stream content from memory and not from file

The users have requested the option to "download" a csv file representation of GridView contents. Does anyone know how to do this without saving the file to the server but rather just streaming it to the user from memory?
Thanks
Implement an IHttpHandler.
I used something similar to the following in the ProcessResponse for outputing a CSV that had previously been constructed in a database table...
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
//Get data to output here...
//Turn off Caching and enforce a content type that will prompt to download/save.
response.AddHeader("Connection", "close");
response.AddHeader("Cache-Control", "private");
response.ContentType = "application/octect-stream";
//Give the browser a hint at the name of the file.
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", _filename));
//Output the CSV here...
foreach(BatchDTO.BatchRecordsRow row in dtoBatch.BatchRecords)
response.Output.WriteLine(row.Data);
response.Flush();
response.Close();
}
There are a number of libraries that make generating a CSV easier, you should just be able to pass it the Response.OutputStream to have it write to there rather than to a file stream.
Use context.Response.OutputStream.
Here's an example.
I created a StringBuilder and dump the contents to the Response object using the following code ("csv" is the StringBuilder variable).
Response.ContentType = #"application/x-msdownload";
Response.AppendHeader("content-disposition", "attachment; filename=" + FILE_NAME);
Response.Write(csv.ToString());
Response.Flush();
Response.End();
I have used the RKLib export library a few times to great effect, this uses a memory stream and can be given any datatable which it will export as a csv download:
http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

Resources