c# - iTextSharp produces invalid PDF -


using itextsharp 4.2.0, have made following function generate dummy pdf in memory , send client:

internal override byte[] generatepdfdocument(pdfcontent content) {     document document = new document(pagesize.a4, 30f, 30f, 30f, 30f);      memorystream output = new memorystream();     pdfwriter writer = pdfwriter.getinstance(document, output);     document.open();     document.add(new paragraph("hello world"));     byte[] response = output.toarray();     document.close();     return response; } 

which called static function:

public static byte[] print(string jsondata) {     pdfgeneratorbase generator;     generator = new itextsharpgenerator();     return generator.generatepdfdocument(view.getviewdata()); } 

which called webapi controller:

public httpresponsemessage printpdf(httprequestmessage req) {     httpresponsemessage result = new httpresponsemessage(httpstatuscode.ok);     byte[] pdfdata = printreport.print(printjobstring);     result.content = new bytearraycontent(pdfdata);     result.content.headers.contenttype = new mediatypeheadervalue("application/pdf");     result.content.headers.contentdisposition = new contentdispositionheadervalue("attachment");     result.content.headers.contentdisposition.filename = "printpdf.pdf";     return result; } 

if open resulting pdf in foxit reader 7.2, error message "format error: not pdf or corrupted".

what doing wrong here?

you need close document before grabbing byte array. closing document flushes internal buffers of "finishes" document. swap this:

byte[] response = output.toarray(); document.close(); 

with this:

document.close(); byte[] response = output.toarray(); 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -