asp.net mvc - iTextSharp creating file in memory resulting corrupted file -



asp.net mvc - iTextSharp creating file in memory resulting corrupted file -

i trying create pdf file in mvc using itextsharp. have next simple used case. file getting created when open pdf getting error file corrupted unable open file. idea/help ?

my controller code follows

public filestreamresult getpdfmemory() { itextsharp.text.document doc = new itextsharp.text.document(); memorystream mem = new memorystream(); pdfwriter pdfwriter = pdfwriter.getinstance(doc, mem); //pdfwriter.closestream = false; doc.open(); doc.add(new paragraph("charts")); mem.position = 0; filestreamresult filestreamresult = new filestreamresult(mem, system.net.mime.mediatypenames.application.pdf) { filedownloadname = "chart_" + ".pdf" }; homecoming filestreamresult; }

view : @html.actionlink("pdf memory", "getpdfmemory", "home", null, new { id = "download"})

fyi : when seek utilize filestream instead of memorystream works fine. need create pdf using memorystream.

you manipulate (mem.position = 0) , utilize (new filestreamresult(mem, ...)) memorystream before signalling itextsharp can finalize document. thus, depending on whether implicit destruction of document , pdfwriter or utilize of info in memory stream comes first, either have pdf missing closing parts or closing parts (being written after reposition memory stream) overwriting start of data.

to signal itextsharp can finalize document, please phone call doc.close() before manipulating memory stream or alternatively utilize document in using block, e.g.:

using (memorystream ms = new memorystream()) { // step 1 using (document document = new document()) { // step 2 pdfwriter.getinstance(document, ms); // step 3 document.open(); // step 4 document.add(new paragraph("helloworldmemory")); } httpcontext.current.response.binarywrite(ms.toarray()); }

(shamelessly copied sample helloworldmemory.cs webified itextsharp examples) itext in action — 2nd edition)

using using implicitly causes document closed.

asp.net-mvc itextsharp

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -