KillemAll
KillemAll

Reputation: 701

Generating pdf in a web API (ItextSharp 5.5.13)

I need to create a PDF file in memory within a web API and send it. I do create the PDF and the web API sends it, but I can't open it once received.

I do create the PDF as a byte array with this:

private byte[] createPDF()
    {
        MemoryStream memStream = new MemoryStream();
        byte[] pdfBytes;

        Document doc = new Document(iTextSharp.text.PageSize.LETTER);
        PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
        doc.AddTitle("test");
        doc.AddCreator("I am");

        doc.Open();//Open Document to write
        Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
        Phrase pharse = new Phrase("This is my second line using Pharse.");
        Chunk chunk = new Chunk(" This is my third line using Chunk.");
        doc.Add(paragraph);
        doc.Add(pharse);
        doc.Add(chunk);
        pdfBytes = memStream.ToArray();
        doc.Close(); //Close 
        return pdfBytes;
    }

This method is called by the method in the web API which sends the PDF, and it is this one:

 [HttpGet]
    public HttpResponseMessage GetFiniquitopdf()
    {
        try
        {
            byte[] buffer = createPDF();

            response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            response.Content = new StreamContent(new MemoryStream(buffer));

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            response.Content.Headers.ContentLength = buffer.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "myFirstPDF.pdf"
            };

        }
        catch (Exception e)
        {
            response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
        }

        return response;
    }

The problem is when the PDF is downloaded it is useless, can't be opened, I don't understand why the PDF can't be opened, I thought it was the security of the Windows 10, so once downloaded I do check it as a secure file, but it doesn't open anyway. I guess there is something wrong in the way I send it or maybe I lack of something in the creation of the PDF file

thanks in advance

Upvotes: 1

Views: 2498

Answers (1)

mkl
mkl

Reputation: 95938

You retrieve the bytes from the memory stream before closing the document:

    pdfBytes = memStream.ToArray();
    doc.Close(); //Close 
    return pdfBytes;

But the pdf in the memory stream is not complete before the document is closed. Thus, simply switch the order of instructions:

    doc.Close(); //Close 
    pdfBytes = memStream.ToArray();
    return pdfBytes;

Upvotes: 2

Related Questions