c# - HTML to PDF convertion issue -
i have 2 problems when converting html (mvc razor page) pdf non utf8 characters.
1) generating pdf chinese characters 2) whenever enable addition of css files exception " input string not in correct format." when comment own css , use getdefaultcss, error doesn't show , pdf being generated chinese characters appear question marks (?)
here code:
public static byte[] buildpdfcontent<t>(t model, string template, controllercontext context) { corecontroller controller = (corecontroller)context.controller; var html = controller.renderrazorviewtostring(template, model); memorystream msinput = new memorystream(asciiencoding.default.getbytes(html)); memorystream msoutput = new memorystream(); string fontawesomecss = httpcontext.current.server.mappath("/content/css/font-awesome.min.css"); string bootstrapcss = httpcontext.current.server.mappath("/content/css/bootstrap.css"); string sitecss = httpcontext.current.server.mappath("/content/css/site.css"); document doc = new document(itextsharp.text.pagesize.a4); doc.setmargins(doc.leftmargin, doc.rightmargin, 35, 0); pdfwriter pdfwriter = pdfwriter.getinstance(doc, msoutput); doc.open(); var tagprocessors = (defaulttagprocessorfactory)tags.gethtmltagprocessorfactory(); tagprocessors.removeprocessor(html.tag.img); // remove default processor tagprocessors.addprocessor(html.tag.img, new customimagetagprocessor()); // use our new processor cssfilesimpl cssfiles = new cssfilesimpl(); cssfiles.add(xmlworkerhelper.getcss(new filestream(fontawesomecss, filemode.open))); cssfiles.add(xmlworkerhelper.getcss(new filestream(bootstrapcss, filemode.open))); cssfiles.add(xmlworkerhelper.getcss(new filestream(sitecss, filemode.open))); //cssfiles.add(xmlworkerhelper.getinstance().getdefaultcss()); styleattrcssresolver cssresolver = new styleattrcssresolver(cssfiles); var hpc = new htmlpipelinecontext(new cssappliersimpl(new unicodefontfactory())); hpc.setacceptunknown(true).autobookmark(true).settagfactory(tagprocessors); // inject tagprocessors htmlpipeline htmlpipeline = new htmlpipeline(hpc, new pdfwriterpipeline(doc, pdfwriter)); ipipeline pipeline = new cssresolverpipeline(cssresolver, htmlpipeline); xmlworker worker = new xmlworker(pipeline, true); xmlparser xmlparse = new xmlparser(true, worker); xmlparse.parse(msinput); doc.close(); return msoutput.toarray();
}
private class unicodefontfactory : fontfactoryimp { private static readonly string fontpath = path.combine(environment.getfolderpath(environment.specialfolder.fonts), "arialuni.ttf"); private readonly basefont _basefont; public unicodefontfactory() { _basefont = basefont.createfont(fontpath, basefont.identity_h, basefont.embedded); } public override font getfont(string fontname, string encoding, bool embedded, float size, int style, basecolor color, bool cached) { return new font(_basefont, size, style, color); } }
Comments
Post a Comment