Converting Asp.net page to pdf with Itextsharp (XMLWorker) returning damaged/blank pdf -
Converting Asp.net page to pdf with Itextsharp (XMLWorker) returning damaged/blank pdf -
not sure if skipped step in code, using itextsharp version 5.5.1 , xml worker version 5.5.1. doc.close throws exception "the document has no pages", watched sw.tostring (it has html content).
private void exporttopdf() { httpcontext.current.response.clear(); httpcontext.current.response.addheader("content-disposition", "attachment;filename=requestsummaryreport.pdf"); httpcontext.current.response.charset = ""; httpcontext.current.response.contenttype = "application/pdf"; stringwriter sw = new stringwriter(); htmltextwriter htw = new htmltextwriter(sw); var doc = new document(pagesize.a3, 45, 5, 5, 5); pdfwriter author = pdfwriter.getinstance(doc, response.outputstream); doc.open(); htmlpipelinecontext htmlcontext = new htmlpipelinecontext(null); htmlcontext.settagfactory(tags.gethtmltagprocessorfactory()); icssresolver cssresolver = xmlworkerhelper.getinstance().getdefaultcssresolver(false); ipipeline pipeline = new cssresolverpipeline(cssresolver, new htmlpipeline(htmlcontext, new pdfwriterpipeline(doc, writer))); xmlworker worker = new xmlworker(pipeline, true); xmlparser xmlparse = new xmlparser(true, worker); pnlreport.rendercontrol(htw); stringreader sr = new stringreader(sw.tostring()); xmlparse.parse(sr); xmlparse.flush(); doc.close(); response.write(doc); }
i spent 2 hours same symptoms, , figured out cause of problem. i'm guessing may have figured out (since, question asked 5 months ago) thought i'd post reply in case there others run same problem.
when create pdfwriter
, pass in stream (in case response.outputstream
) destination generated pdf content. when pdfwriter
writes content stream, stream position incremented accordingly. when author finishes, stream position @ end of content, , makes sense because farther calls write should go on pdfwriter
left off.
the problem when mvc pipeline takes response.outputstream
(after method returns) , attempts read send contents client (or in general, whenever pdf destination stream consumed), stream position @ end of content, , means consumer appears stream empty, hence empty pdf output.
to solve this, reset the position of stream immediate after finished writing it, , before tries read it. in case insert:
response.outputstream.position = 0;
right after line xmlparse.flush()
, since lastly line write stream.
pdf itextsharp httpresponse xmlworker
Comments
Post a Comment