首先说明,最佳方案是方式一。
方式二也可以实现,但是有点麻烦,兼容性还不见得好。
方式三,英文环境下挺好的,但不兼容中文。
方式一:html2pdf
使用 html2pdf.js 这个类库。具体使用方法可参考官方说明。
项目地址:html2pdf
源码下载地址:https://github.com/iJoeychang/convert_html_to_pdf_pro
方式二:jsPDF library
jsPDF library 这种方式也可以实现导出 pdf,但是没有第一种方式好。
使用方式
- 引入类库
<!-- jQuery library -->
<script src="js/jquery.min.js"></script>
<!-- jsPDF library -->
<!-- <script src="js/jsPDF/dist/jspdf.min.js"></script> -->
<script src="js/jsPDF/dist/jspdf.debug.js"></script>
<script src="js/jsPDF/html2canvas.js"></script>
- 实现代码
<script>
var pdf,page_section,HTML_Width,HTML_Height,top_left_margin,PDF_Width,PDF_Height,canvas_image_width,canvas_image_height;
function calculatePDF_height_width(selector,index){
page_section = $(selector).eq(index);
HTML_Width = page_section.width();
HTML_Height = page_section.height();
top_left_margin = 15;
PDF_Width = HTML_Width + (top_left_margin * 2);
PDF_Height = (PDF_Width * 1.2) + (top_left_margin * 2);
canvas_image_width = HTML_Width;
canvas_image_height = HTML_Height;
}
function generatePDF() {
var target = document.getElementById("content");//要转化页面内容的id