We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Broken PDF File


Hello,

I have something like this(which is rendered in the backend and which needs to be transferred to the frontend):

BACKEND:
public byte[] HelloWorldPDF(ref string filename)
{
// Create a new PdfDocument
PdfDocument document = new PdfDocument();

// Add a page to the document
PdfPage page = document.Pages.Add();

// Create Pdf graphics for the page
PdfGraphics graphics = page.Graphics;

// Create a solid brush
PdfBrush brush = new PdfSolidBrush(Color.Black);

// Set the font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20f);

// Draw the text
graphics.DrawString("Hello world!", font, brush, new PointF(20, 20));

//Export the document after saving
using (MemoryStream customStream = new MemoryStream())
{
document.Save(customStream as Stream);
document.Close();

return customStream.ToArray();
}
}

FRONTEND:
#region Private Methoden
// Hilfsfunktion, die das byte array als PDF-Datei herunterlädt
private FileResult PDFDownload(byte[] content, string filename)
{
return File(content, "application/pdf", filename + ".pdf");
}
#endregion
// GET: Test
public ActionResult Start()
{
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);

var result = client.PostAsync(_webservice + "test/....?sid=" + _sid, null).Result;//calls helloworld

if (result.IsSuccessStatusCode)
{
var content = result.Content.ReadAsByteArrayAsync().Result;
return PDFDownload(content, "sample_" + DateTime.Now.Ticks.ToString());
}
else
{
string message = Helper.ReadResponse(result).Result;
return View("Result", (object)message);
}

}
}

,
1. What is wront here ?
2. How could I solve it better ?

28 Replies

KK Karthik Krishnaraj Syncfusion Team March 23, 2016 06:06 AM UTC

Hi,
Thank you for contacting syncfusion support,
I have attached a sample link for your reference which helps to generate PDF as per your requirement, Please check through the below link and let us know if you have any other query.
Sample Link:
http://mvc.syncfusion.com/demos/reporting/pdf/GettingStarted/HelloWorld
Thanks,
Karthik.


TE Testname March 23, 2016 07:11 AM UTC

Hi,

in my Backend I am generating the document and than I send the "Stream" which the frontend converts the to pdf(without any additional library).


KK Karthik Krishnaraj Syncfusion Team March 24, 2016 05:32 AM UTC

Hi,
Here we have attached a simple sample in which we used WCF application as backend to return the byte data of pdf, and consumed the same in MVC application as frontend. Can you please try this sample and let us know whether it meets your need.
Sample Link:
http://www.syncfusion.com/downloads/support/forum/123489/ze/HelloWorldMVC1821485674
Thanks,
Karthik


TE Testname March 24, 2016 12:08 PM UTC

What should I do excatly for my problem, the document is 900 page big ... ?!


KC Karthikeyan Chandrasekar Syncfusion Team March 25, 2016 10:45 AM UTC

Hi,
We could directly download the PDF document in the frontend, please use the below code snippet to download the PDF document.
//Export the document after saving
document.Save("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open);
 
You can also download by using Export as ActionResult which will be available by adding the below attached helper files.

return doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open);


Use the below helper.

http://www.syncfusion.com/downloads/support/forum/123489/ze/PdfResult2014998850


Please correct me if I have misunderstood your requirement.
Regards,
Karthikeyan.C


TE Testname March 26, 2016 06:02 AM UTC

hi, thank you for your response.

In the FrontEnd I don't have the syncfusion library only the byte array or some kind of stream from the backend.

The BackEnd will render the document with the syncfusion library into a stream or byte array, so that the Frontend can consume it, after converting it.

This should be the overall aim.

Thank you.


KK Karthik Krishnaraj Syncfusion Team March 28, 2016 09:01 AM UTC

Hi,
Yes it is possible to download PDF from byte array rendered using syncfusion library, please include the below code snippet in your front end to achieve your requirement. Can you please confirm whether the provided solution meets your requirement?
Example:

Response.Clear();

MemoryStream ms = new MemoryStream(pdfContent); //Pass the rendered byte array from back end.

Response.ContentType = "application/pdf";

Response.AddHeader("content-disposition", "attachment;filename=Sample.pdf");

Response.Buffer = true;

ms.WriteTo(Response.OutputStream);

Response.End();



Thanks,
Karthik


TE Testname March 29, 2016 10:17 AM UTC

What if I have an "ActionResult" as  return type , how should I write my cdoe then ?


TE Testname March 29, 2016 10:49 AM UTC

by the way the the example can still not be opend, take a look at the attachment

Attachment: Sample635948510828255868_3c58eccb.7z


KK Karthik Krishnaraj Syncfusion Team March 30, 2016 08:49 AM UTC

Hi,
Can you please share us the simplified sample to reproduce the issue, so that it will be helpful for us to investigate further and provide better solution.
Thanks,
Karthik.


TE Testname March 30, 2016 12:59 PM UTC

Hi,

At the moment I have the following situation:

FRONTEND:

 public void Start()
        {
            using (var client = new HttpClient())
            {
                var result = client.PostAsync(_webservice + "test/xxx?sid=" + _sid, null).Result; //it will make a call to the backend

                if (result.IsSuccessStatusCode)
                {
                    var pdfContent = result.Content.ReadAsByteArrayAsync().Result;

                    Response.Clear();
                    MemoryStream ms = new MemoryStream(pdfContent);
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=Sample" + DateTime.Now.Ticks.ToString() + ".pdf");
                    Response.Buffer = true;
                    ms.WriteTo(Response.OutputStream);
                    Response.End();
                }
                else
                {
                    string message = Helper.ReadResponse(result).Result;
                }

            }
        }
       
BACKEND:

The "client.PostAsync(_webservice + "test/xxx?sid=" + _sid, null).Result;" statement reads a normal pdf file with "return File.ReadAllBytes(fileName);" without any changes to it and the FRONTEND should just take that Byte[] and transform it to a normal PDF File.

In my backend I can use the syncfusion library, but not in my frontend.

The strange thing is, that outputfile is much smaller thatn the inpout file....


Attachment: output_72b82075.7z


TE Testname March 31, 2016 07:24 AM UTC

Forgot to upload the original file

Attachment: original_ff46561b.7z


KK Karthik Krishnaraj Syncfusion Team March 31, 2016 01:15 PM UTC

Hi,
I have attached a simplified sample to download the PDF file in front end without using syncfusion library, Can you please check this at your end and let us know whether it fulfill your needs.
Sample Link:
http://www.syncfusion.com/downloads/support/forum/123489/ze/HelloWorldMVC-1144891277
Thanks,
Karthik.


TE Testname April 1, 2016 08:22 AM UTC

Thank you, can you tell me what is the problem with this file, I can not open it ?(attachment)

Attachment: Sample635951026369768508_25c33f0e.7z


TE Testname April 1, 2016 08:24 AM UTC

I was using the code snippet(modified it a little bit):

 var pdfContent = result.Content.ReadAsByteArrayAsync().Result;

                    Response.Clear();
                    MemoryStream ms = new MemoryStream(pdfContent);
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=Sample" + DateTime.Now.Ticks.ToString() + ".pdf");
                    Response.Buffer = true;
                    ms.WriteTo(Response.OutputStream);
                    Response.End();


From your Sample:
http://www.syncfusion.com/downloads/support/forum/123489/ze/HelloWorldMVC-1144891277


TE Testname April 1, 2016 08:27 AM UTC

                    //ms.Close();
                    //ms.Dispose();

By the way is closing and disposing useful here ?


KK Karthik Krishnaraj Syncfusion Team April 4, 2016 02:29 PM UTC

Hi,

Thank you, can you tell me what is the problem with this file, I can not open it ?(attachment)


Attachment: 
Sample635951026369768508_25c33f0e.7z

Here the attached document is not in proper PDF structure. It just contains the byte values. Hence it causes the document to be corrupted.

 //ms.Close();
   //ms.Dispose();

By the way is closing and disposing useful here ?

Yes, it will help to reduce the memory consumed by the application.


Thanks,
Karthik.


TE Testname April 4, 2016 03:01 PM UTC

What can I do about it ?

"Here the attached document is not in proper PDF structure. It just contains the byte values. Hence it causes the document to be corrupted."


KC Karthikeyan Chandrasekar Syncfusion Team April 5, 2016 08:55 AM UTC

Hi,

The document which you have sent is not a valid PDF document, you can check this by opening the PDF document in the Adobe Reader. We suspect that the code "result.Content.ReadAsByteArrayAsync().Result" does not returns proper PDF bytes as it contains only junk content.  Could you please check the implementation of this in your code base.





Regards,

Karthikeyan.C



TE Testname April 5, 2016 09:14 AM UTC

Hi,

what to use instead ?


KK Karthik Krishnaraj Syncfusion Team April 6, 2016 02:17 PM UTC

Hi,
I have attached a simple sample to “Download PDF from byte content in backend”, in backend I made changes to return the PDF byte content in HttpResponseMessage, now the document gets downloaded properly. Please check through the sample and let us know whether it meets your need.
BackEnd:

public HttpResponseMessage Post()

{

 PdfDocument document = new PdfDocument();

 // Add a page to the document

 PdfPage page = document.Pages.Add();

  // Create Pdf graphics for the page

  PdfGraphics graphics = page.Graphics;

  // Create a solid brush

  PdfBrush brush = new PdfSolidBrush(Color.Black);

  // Set the font

  PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20f);

  // Draw the text

  graphics.DrawString("Hello world!", font, brush, new PointF(20, 20));

  using (MemoryStream customStream = new MemoryStream())

  {

  document.Save(customStream as Stream);

  document.Close(true);

  HttpResponseMessage result = new HttpResponseMessage();

  result = Request.CreateResponse(HttpStatusCode.OK);

  result.Content = new ByteArrayContent(customStream.ToArray());

 result.Content.Headers.ContentDisposition = new                     System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

 result.Content.Headers.ContentDisposition.FileName = "Sample" + ".pdf";

   return result;

    }

  }


Sample Link:
http://www.syncfusion.com/downloads/support/forum/123489/ze/MvcApp-1569592371
Thanks,
Karthik.


TE Testname April 6, 2016 02:19 PM UTC

ok, but again I have no Syncfusion library, please change it to my case


TE Testname April 6, 2016 02:28 PM UTC

In my backend


KK Karthik Krishnaraj Syncfusion Team April 7, 2016 01:56 PM UTC

Hi,
On our analysis we found that returned byte data from backend contains base64 encoded format, hence I have modified to convert data from base64 to equivalent 8bit array. Now the document gets downloaded properly. Kindly check the modified sample and let us know if you have any other query.
Sample Link:
http://www.syncfusion.com/downloads/support/forum/123489/ze/MvcApp701017441
Thanks,
Karthik.


TE Testname April 7, 2016 02:10 PM UTC

Ok, thanks. This solved the problem.

But how can I distinguish what kind of output format the byte[] array will be ?!

Usually I get a byte[] from the backend and I don't know what kind of format it could be, the backend renders excel, html, pdf and word(docx),

Your example works only for pdf.

How to do it for the rest of my formats  ?!


KK Karthik Krishnaraj Syncfusion Team April 8, 2016 02:57 PM UTC

Hi,
As your query I have attached a modified sample which helps to know the format (i.e PDF, HTML, Word, Excel) rendered from backend. Kindly check through it and let me know if you have any concerns.
Sample Link:
http://www.syncfusion.com/downloads/support/forum/123489/ze/MvcApp-847891954
Thanks,
Karthik.


TE Testname April 8, 2016 06:05 PM UTC

thats great, but your example does only take care of pdfs not if they were send as word and should be send as word to the client without conversion, can you fix tis too ?


SR Suganya Rathinam Syncfusion Team April 11, 2016 04:25 PM UTC

Hi,

We have prepared a sample to generate the Word document and attached the same. Please find the sample from the following link and let us know if it helps.
http://www.syncfusion.com/downloads/support/forum/123489/ze/MvcApp-1548915331.zip

Regards,
Suganya


Loader.
Live Chat Icon For mobile
Up arrow icon