How to convert pdf Byte[] Array to downloadable file using iTextSharp - c#

Hei guys I have this byte array i want to convert to pdf and make it available for download. Anybody has any idea how this is done?
here is my Action Controller
public ActionResult DownloadLabTestResult(string labTestResultID)
{
PdfReader pdfReader = new PdfReader("Xue_Tang.pdf");
MemoryStream stream = new MemoryStream();
PdfStamper stamper = new PdfStamper(pdfReader, stream);
pdfReader.Close();
stamper.Close();
stream.Flush();
stream.Close();
byte[] pdfByte = stream.ToArray();
// So i got the byte array of the original pdf at this point. Now how do i convert this
// byte array to a downloadable pdf? i tried the method below but to no avail.
MemoryStream ms = new MemoryStream(pdfByte);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=labtest.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

I am using similar code with a few differences:
Response.Clear();
MemoryStream ms = new MemoryStream(pdfByte);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=labtest.pdf");
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.End();
Call Reponse.Clear() earlier.
Use MemoryStream.WriteTo to write to Response.OutputStream.
Edit: sorry, I didn't see that you are using ASP.NET MVC, the above code is in a WebForms aspx page.
For ASP.NET MVC, couldn't you just do
return new FileStreamResult(ms, "application/pdf");
?

Related

iTextSharp is generating single page pdf

Converting Binary "data:image/jpeg;base64," to pdf but not getting correct output, my binary string is very long which content 10 pages of pdf, Image url i am getting full image, but when i am generation ToBase64String to pdf then only one page
string folderPath = Server.MapPath("~/ImageFiles/");
WebBrowser webrowse = sender as WebBrowser;
Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height, PixelFormat.Format16bppRgb565);
webrowse.DrawToBitmap(bitmap, webrowse.Bounds);
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] strbytes = stream.ToArray();
imgscreenshot.Visible = true;
imgscreenshot.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(strbytes);
string base64 = Convert.ToBase64String(strbytes);
byte[] imageBytes = Convert.FromBase64String(base64);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
document.Add(image);
document.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=Image.pdf");
Response.ContentType = "application/pdf";
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
In below Image is single page generated and not in center position also and arround 10 pages should come but that is not generated

PDFsharp not giving pdf file in response

I am working on export functionality using PDFsharp in .Net MVC I am not getting any error in my code but not getting PDF file in response.
I have tried doing it manually writing it to specific path with the help of : System.IO.File.WriteAllBytes(path1, bytes); and it's working perfectly, but I am not getting PDF in Response with the help of
Response.BinaryWrite(bytes);
Response.OutputStream.Write(bytes, 0, bytes.Length);
Anyone have faced this type of issue or someone from community please help
Here is my code :
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Myfile.pdf");
Response.ContentType = "application/pdf";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document =
PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4,
30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
var path1 = Server.MapPath("~/Images/" +
DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.BinaryWrite(bytes);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.End();
return true;
}
thank you,

Error : http query string is too long

I use the below code in mvc to download Excel file but it shows error query string too long.
public ActionResult Download(string input)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment; filename= download.xlsx");
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "application/vnd.ms-excel";
Response.WriteFile(input);
Response.End();
return Content(String.Empty);
}
This code works for me for PDF:
public FileStreamResult DownnloadPDF(int id)
{Document document = new Document();
MemoryStream stream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
pdfWriter.CloseStream = false;
document.Open();
formatPDF(document, model);
document.Close();
stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required
return File(stream, "application/pdf", "title" + ".pdf");
}
I really think that your ActionResult will not work.

ZipStorer - Zip Text in MemoryStream, Transmit through httpResponse, unable open as Zip File

Note: I have solved the problem myself. See the below answer.
I'm using ZipStorer to zip files in ASP.NET C# 4.0 WebForm.
After I created the Zip in MemoryStream and transmitted it using httpResponse, the client user was unable to open the file as a Zip File.
Any tips? Thanks.
Below is my code:
string text = GetLongText();
byte[] ba = Encoding.UTF8.GetBytes(text);
using (MemoryStream ms = new MemoryStream())
{
using (ZipStorer zip = ZipStorer.Create(ms, "My Zip File"))
{
zip.AddStream(ZipStorer.Compression.Deflate, "MyText.txt", new MemoryStream(ba), DateTime.Now, "My Text");
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=MyZip.zip");
Response.ContentType = "application/zip";
ms.WriteTo(Response.OutputStream);
Response.End();
}
}
I have solve the problem myself. Below is the codes:
string text = GetLongText();
byte[] ba = Encoding.UTF8.GetBytes(text);
using (MemoryStream ms = new MemoryStream())
{
using (ZipStorer zip = ZipStorer.Create(ms, "My Zip"))
{
zip.AddStream(ZipStorer.Compression.Deflate, "text.txt", new MemoryStream(ba), DateTime.Now, "My Text");
}
Response.AppendHeader("content-disposition", "attachment; filename=MyZip.zip");
Response.ContentType = "application/zip";
Response.BinaryWrite(ms.ToArray());
Response.End();
}
}

PdfReader from MemoryStream()

Can anyone give me an example of how to get a PdfReader from a MemoryStream? I can see that the PdfReader class has a couple of methods which look like likely candidates (GetStreamBytes & GetStreamBytesRaw), however these seem to want iText-specific streams, mine is just a regular Byte[] or MemoryStream.
This is using C# and .NET 4.
iTextSharp.text.pdf.PdfReader rdr = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw
You can create a PdfReader from a MemoryStream, so long as the MemoryStream is a valid PDF object. If the MemoryStream is a valid PDF object, then one way to initiate the PdfReader is this way:
PdfReader _reader = new PdfReader((byte[])_memoryStream.ToArray());
In the code below, the PdfReader is initialized from .Net Resource which is returned as a byte[] when called from the Properties.Resources object, so the Resource and the MemoryStream are returning the same type to the PdfReader, a byte[]. I then create a PdfStamper object from the PdfReader object, and use a MemoryStream as the resulting container for the PdfStamper.
PdfReader _srcDoc = new PdfReader(Properties.Resources.Resource1);
MemoryStream _output = new MemoryStream();
PdfStamper _scratchDoc = new PdfStamper(_srcDoc, _output);
Maybe a bit late.
Try to set the streams position to 0.
...
stream.Flush(); // Don't know if this is necessary
stream.Position = 0;
PdfReader reader = new PdfReader(stream.ToArray());
...
If you want to just open the pdf in browser using bytes then do this :
public void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
try
{
if (!string.IsNullOrEmpty(attachmentFilename))
{
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
}
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
}
catch (Exception ex)
{
throw ex;
}
finally
{
response.End();
response.Flush();
response.Clear();
}
}

Categories