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
Related
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,
I am working on Export to PDF funtionality using C# and PDFSharp. I am getting this error:
Value cannot be null.
Parameter name: elementId
The error is on this line :
PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4, 30);
Here's the whole method:
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=Myfile.pdf");
//Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
//Response.AppendHeader("Content-Disposition", "attachment; filename=Myfile.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;
//PdfDocument document = PdfGenerator.GeneratePdf(htmlcontenttbl, config);
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.TransmitFile(path1, 0, bytes.Length);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return true;
}
That exception can occur if you have a blank anchor tag.
It is likely ultimately being generated from here.
You should remove the blank anchor tag.
I generate a pdf file on the fly and save it to the server side but i need to save it to the client machine. How to achieve this..
Document doc = new Document();
MemoryStream memoryStream = new MemoryStream();
string PDFName = ProjectName + ".pdf";
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~/ProjectFiles") + "/" +
PDFName, FileMode.Create));
doc.Open();
//PDF Content
doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + PDFName);
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
In Response.OutputStream.Write(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
The memoryStream length is 0. I need to download the saved pdf into Cleint machine.
Please help me to fix this issue..
You are not writing anything to memoryStream.
Since you are generating PDFs on each request there is no need to save them to the file. You could generate the PDF to the MemoryStream directly.
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
If your PDFs are not dynamic (eg. there is no need to generate them on every request) You can generate them to the file system as you do right now and then only read them from disk:
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(YourPdfFile, FileMode.Open, FileAccess.Read)) {
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
}
}
But this makes sens only if the PDFs are generated once and then only served from disk.
EDIT: after writing into stream it was necessary to set memoryStream position to zero because it was at the end.
You have to affect memorystream like that :
PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStream);
I am generating the PDF using iTextSharp.i have a HTMl Page and i am Reading HTML Page then generate the PDF.but the Problem is that the half of the page is in PDF while another half of the Page is running out the page in PDF.i mean half of the Page is displayed in PDF.while half of the Page is cutting in PDF.
my code is like this in Load Event..
string fileContents;
string FilePath = Server.MapPath("print-withoutlogin.html");
StreamReader mstrFileStreamReader = new StreamReader(FilePath);
try
{
fileContents = mstrFileStreamReader.ReadToEnd();
byte[] result = createPDF(fileContents.ToString()).GetBuffer();
Response.Clear();
Response.AddHeader("Content-Length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.AddHeader("Accept-Ranges", "bytes");
Response.Buffer = true;
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Pragma", "public");
Response.AddHeader("content-Transfer-Encoding", "binary");
Response.AddHeader("Content-Disposition", "attachment; filename=kartik.pdf");
Response.BinaryWrite(result);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
mstrFileStreamReader.Close();
}
and
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
Document document = new Document(PageSize.A4, 0, 0, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
HTMLWorker worker = new HTMLWorker(document);
//worker.SetStyleSheet(styles);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Have you Considered using Crystal Reports? I find it much easier and you can use
pdfStream = (MemoryStream)report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
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");
?