javascript - Using a webservice to Create PDF only works when the service is called directly -
i'm novice webservices, 1 has me stumped. have created webservice (eventually) accept block of html , create pdf file it. keep simple, i'm not passing parameters service; i'm creating pdf document "hello world" in it. in debug mode, when call service directly (i.e. start debugging asmx page), can invoke exportpdf() method , results perfect -- creates pdf i'd hoped.
the problem when call webservice javascript, nothing happens. i've set breakpoint inside service, know it's getting called, , mentioned there no parameters being passed in, don't understand why works when it's invoked directly, not when it's invoked javascript call.
my javascript , webservice code below...any greatly, appreciated!!
javascript:
function getpdf(elem) { var param = { html: elem.innerhtml }; $.ajax({ type: "post", contenttype: "application/json; charset=utf-8", url: "../webservices/exporting.asmx/exportpdf", data: "{ }", datatype: "json", success: function (response) { } }) }
webservice:
using dmc.classes; using nreco.pdfgenerator; using system; using system.io; using system.web; using system.web.services; using system.web.ui; namespace dmc.webservices { [webservice(namespace = "http://tempuri.org/")] [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)] [system.componentmodel.toolboxitem(false)] [system.web.script.services.scriptservice] public class exporting : system.web.services.webservice { [webmethod] public void exportpdf() { writedocument("htmltopdf.pdf", "application/pdf", converthtmltopdf()); } public byte[] converthtmltopdf() { htmltopdfconverter nrecohtmltopdfobj = new htmltopdfconverter(); nrecohtmltopdfobj.orientation = pageorientation.portrait; nrecohtmltopdfobj.pagefooterhtml = createpdffooter(); nrecohtmltopdfobj.customwkhtmlargs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0"; return nrecohtmltopdfobj.generatepdf(createpdfscript() + "hello world" + "</body></html>"); } public string createpdfscript() { return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var x=document.location.search.substring(1).split('&');for(var in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" + "var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var in x) {var y = document.getelementsbyclassname(x[i]);" + "for(var j=0; j<y.length; ++j) y[j].textcontent = vars[x[i]];}}</script></head><body onload=\"subst()\">"; } public string createpdffooter() { return "<div style='text-align:center;font-family:tahoma; font-size:9px;'>page <span class=\"page\"></span> of <span class=\"topage\"></span></div>"; } public void writedocument(string filename, string contenttype, byte[] content) { httpcontext.current.response.clear(); httpcontext.current.response.contenttype = contenttype; httpcontext.current.response.addheader("content-disposition", "attachment; filename=" + filename); httpcontext.current.response.cachecontrol = "no-cache"; httpcontext.current.response.binarywrite(content); httpcontext.current.response.flush(); } } }
thanks response, mason! i've been working on , found solution; , while admit it's not perfect, don't think it's bad. different material read, started feeling web service more of "go between" passing data , not meant handle functionality posting pdf documents. let away when debugging , invoking directly, that's it.
so instead of using web service, created class object. created hidden field in html. field gets populated desired div.innerhtml content via javascript when clicks "export pdf" button. upon postback, codebehind checks see if hidden field empty , if isn't, calls exportpdf function, in turn instantiates class object creates/downloads pdf. biggest pitfall doing way, , may consider big pitfall, read in field in codebehind has html markup in have turn off validation web page, opens code malicious attacks.
below highlights of code:
web.config
add requestvalidationmode = "2.0" web.config file
<system.web> <httpruntime requestvalidationmode="2.0" targetframework="4.5" /> </system.web>
.aspx page:
set validaterequest="false" in page reference
<%@ page title="referrals" language="c#" masterpagefile="~/behavior/behavior.master" autoeventwireup="true" codebehind="referrals.aspx.cs" inherits="dmc.behavior.referrals" clientidmode="static" enableeventvalidation="false" validaterequest="false" %> . . . <asp:linkbutton id="linkbutton2" runat="server" onclientclick="createpdf();"> <img src='../images/icons/pdf.png'>pdf</asp:linkbutton> . . . <div id="export_pdf" class="pdfwidth_portrait pdfsection" style="margin-top: 10px;" runat="server"> <div class="alert-info text-center" style="margin: 0; padding: 0;"> <table class="table table-condensed" style="margin-top: 0; padding: 30px; width: 100%;"> . . . </table> </div> </div> . . . <asp:hiddenfield id="pdfdata" runat="server" /> . . . <script type="text/javascript"> function createpdf() { document.getelementbyid("pdfdata").value = document.getelementbyid("export_pdf").innerhtml; } </script>
code behind:
protected void page_load(object sender, eventargs e) { if (!ispostback) { //set hidden pdf field null pdfdata.value = ""; } //if field no longer null, means wanting export pdf if (pdfdata.value != "") { exportpdf(); } } public void exportpdf() { string filename = null; export dmc = new export(); filename = lbllocation.text + " behavior statistics ytd " + lbldate.text; dmc.exportpdf(filename, "portrait", pdfdata.value); //pdf downloaded, reset value "" pdfdata.value = ""; }
export class
using nreco.pdfgenerator; using system.configuration; using system.data; using system.data.sqlclient; using system.io; using system.text; using system.web; using system.web.ui; using system.web.ui.htmlcontrols; using system.web.ui.webcontrols; namespace dmc.classes { public class export { public void exportpdf(string filename, string orientation, string html) { htmltopdfconverter pdf = new htmltopdfconverter(); //remove these control characters, interfere formatting of pdf document html = html.replace("\n", ""); html = html.replace("\t", ""); html = html.replace("\r", ""); switch (orientation) { case "portrait": pdf.orientation = pageorientation.portrait; break; case "landscape": pdf.orientation = pageorientation.landscape; break; default: pdf.orientation = pageorientation.default; break; } //in case needed future //pdf.customwkhtmlargs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0"; pdf.margins.top = 25; pdf.pagefooterhtml = createpdffooter(); var pdfbytes = pdf.generatepdf(createpdfscript() + html + "</body></html>"); httpcontext.current.response.contenttype = "application/pdf"; httpcontext.current.response.contentencoding = system.text.encoding.utf8; httpcontext.current.response.addheader("content-disposition", "attachment; filename=" + filename + ".pdf"); httpcontext.current.response.binarywrite(pdfbytes); httpcontext.current.response.flush(); httpcontext.current.response.end(); } private string createpdfscript() { return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var x=document.location.search.substring(1).split('&');for(var in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" + "var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var in x) {var y = document.getelementsbyclassname(x[i]);" + "for(var j=0; j<y.length; ++j) y[j].textcontent = vars[x[i]];}}</script></head><body onload=\"subst()\">"; } private string createpdffooter() { return "<div><table style='font-family:tahoma; font-size:9px; width:100%'><tr><td style='text-align:left'>research dept|rr:mm:jpg</td><td style='text-align:right'>page <span class=\"page\"></span> of <span class=\"topage\"></span></td></div>"; } } }
Comments
Post a Comment