JavaScript代码生成PDF文件的方法
如何使用js生成pdf文件呢?相信很多朋友都被这一问题迷惑着,下面由毛票票小编通过本文给大家简单介绍下。
可以使用javascript生成PDF的类库–jsPDF,先下载jsPDF-0.9.0rc2下载地址:;请点这里,以下是完整实例代码:
<!doctype> <html> <head> <title>jsPDF</title> <metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/> <scripttype="text/javascript"src="js/jquery/jquery-1.7.1.min.js"></script> <scripttype="text/javascript"src="js/jquery/jquery-ui-1.8.17.custom.min.js"></script> <scripttype="text/javascript"src="../jspdf.js"></script> </head> <body> <iframeframeborder="0"width="500"height="400"></iframe> <script> $(document).ready(function(){ varpdf=newjsPDF('p','in','letter') ,sizes=[12,16,20] ,fonts=[['Times','Roman'],['Helvetica',''],['Times','Italic']] ,font,size,lines ,margin=0.5//inchesona8.5x11inchsheet. ,verticalOffset=margin ,loremipsum='ipsumdolorsitamet,consecteturadipiscingelit.Phasellusiderosturpis.Vivamustemporurnavitaesapienmollismolestie.Vestibuluminlectusnonenimbibendumlaoreetatatlibero.Etiammalesuadaeratsedsemblanditinvariusorciporttitor.Sedatsapienurna.Fusceaugueipsum,molestieetadipiscingat,variusquisenim.Morbisedmagnaest,velvestibulumurna.Sedtemporipsumvelmipretiumatelementumurnatempor.Nullafaucibusconsecteturfelis,elementumvenenatismimollisgravida.Aliquammiante,accumsaneutempusvitae,viverraquisjusto.\n\nProinfeugiataugueinauguerhoncuseucursustelluslaoreet.Pellentesqueeusapienatdiamporttitorvenenatisnecvitaevelit.Donecultricesvolutpatlectusegetvehicula.Nameueratmi,inpulvinareros.Maurisviverraportaorci,etvehiculalectussagittisid.Nullamatmagnavitaenuncfringillaposuere.Duisvolutpatmalesuadaornare.Nullainerosmetus.Vivamusaposuerelibero.' //Margins: pdf.setDrawColor(0,255,0) .setLineWidth(1/72) .line(margin,margin,margin,11-margin) .line(8.5-margin,margin,8.5-margin,11-margin) //the3blocksoftext for(variinfonts){ if(fonts.hasOwnProperty(i)){ font=fonts[i] size=sizes[i] lines=pdf.setFont(font[0],font[1]) .setFontSize(size) .splitTextToSize(loremipsum,7.5) //Don'twanttopresetfont,sizetocalculatethelines? //.splitTextToSize(text,maxsize,options) //allowsyoutopassanobjectwithanyofthefollowing: //{ //'fontSize':12 //,'fontStyle':'Italic' //,'fontName':'Times' //} //Withoutthese,.splitTextToSizewillusecurrent/default //fontFamily,Style,Size. //console.log(lines); pdf.text(0.5,verticalOffset+size/72,lines) verticalOffset+=(lines.length+0.5)*size/72 } } varstring=pdf.output('datauristring'); $('iframe').attr('src',string); }); </script> </body> </html>
以上内容给大家介绍了JavaScript代码生成PDF文件的方法,希望对大家有所帮助!