During project development, we occasionally or often encounter some problems. Converting html pages to pdf using js is also a problem, which means that it is equivalent to cutting off the entire page and then saving it as pdf.
In fact, there are many ways to convert html to pdf, probably the following:
1. Most browsers have this function. However, this is not what our customers want. What they want is the export to pdf function that can be actively triggered in the system, so this solution is passed.
2. Use third-party tools. I found a solution using a tool like wkhtmltopdf to export. I tried it in our project, but the effect was not good, and the support for svg images was not good either. pass.
3. Another method is to use the iText class to generate java files in the background. But because the page that needs to be exported is a dynamic page, and if you directly pass the page to the backend, a lot of styles will be lost, so I still pass.
In the end, there is no good solution. I can only settle for the second best, thinking about converting the html page into a picture first, and then exporting the picture to pdf. Because it is necessary to support users to export and download, and to retain the style, it is best to implement a pure js front-end.
If you want to convert html to canvas, use html2canvas js. There are many introductions to this online, so I won’t go into nonsense here.
The more troublesome thing is the svg image. Directly using html2canvas cannot convert the content of the svg tag into canvas. After checking the information, I locked the js canvg. canvg is a Google plug-in that can convert svg tag content into canvas. Specific to our project, another difficulty is how to convert font icons such as glyphicons into canvas, because the support for this font icon is completely different in different browsers. The last method I found was to replace these font icons with char code and redraw them into canvas. There is no need to talk nonsense when generating images from canvas. Generating pdf from pictures is implemented using jsPDF. After struggling for a long time, I finally got the whole process through, and then posted the code step by step.
The first step: Replace all svg elements in the corresponding dom node with canvas
svg2canvas: function(targetElem) { var svgElem = targetElem.find('svg'); svgElem.each(function(index, node) { var parentNode = node.parentNode; //由于现在的IE不支持直接对svg标签node取内容,所以需要在当前标签外面套一层div,通过外层div的innerHTML属性来获取 var tempNode = document.createElement('div'); tempNode.appendChild(node); var svg = tempNode.innerHTML; var canvas = document.createElement('canvas'); //转换 canvg(canvas, svg); parentNode.appendChild(canvas); }); }
The second step: Convert the glyphicons font to canvas. If the glyphicons font icon is not used in the project, you can ignore this step
glyphicons2canvas: function(targetElem, fontClassName, fontFamilyName) { var iconElems = targetElem.find('.' + fontClassName); iconElems.each(function(index, inconNode) { var fontSize = $(inconNode).css("font-size"); var iconColor = $(inconNode).css("color"); var styleContent = $(inconNode).attr('style'); //去掉"px" fontSize = fontSize.replace("px", ""); var charCode = getCharCodeByGlyphiconsName(iconName); var myCanvas = document.createElement('canvas'); //把canva宽高各增加2是为了显示图标完整 myCanvas.width = parseInt(fontSize) + 2; myCanvas.height = parseInt(fontSize) + 2; myCanvas.style = styleContent; var ctx = myCanvas.getContext('2d'); //设置绘图内容的颜色 ctx.fillStyle = iconColor; //设置绘图的字体大小以及font-family的名字 ctx.font = fontSize + 'px ' + fontFamilyName; ctx.fillText(String.fromCharCode(charCode), 1, parseInt(fontSize) + 1); $(inconNode).replaceWith(myCanvas); }); } //根据glyphicons/glyphicon图标的类名获取到对应的char code getCharCodeByGlyphiconsName: function(iconName) { switch (iconName) { case("glyphicons-resize-full"): return "0xE216"; case ("glyphicons-chevron-left"): return "0xE225"; default: return ""; } }
Step 3: Convert html to canvas, convert image to pdf.
html2canvas($("#myExportArea"), { onrendered: function(canvas) { var imgData = canvas.toDataURL('image/jpeg'); var img = new Image(); img.src = imgData; //根据图片的尺寸设置pdf的规格,要在图片加载成功时执行,之所以要*0.225是因为比例问题 img.onload = function() { //此处需要注意,pdf横置和竖置两个属性,需要根据宽高的比例来调整,不然会出现显示不完全的问题 if (this.width > this.height) { var doc = new jsPDF('l', 'mm', [this.width * 0.225, this.height * 0.225]); } else { var doc = new jsPDF('p', 'mm', [this.width * 0.225, this.height * 0.225]); } doc.addImage(imgData, 'jpeg', 0, 0, this.width * 0.225, this.height * 0.225); //根据下载保存成不同的文件名 doc.save('report_pdf_' + new Date().getTime() + '.pdf'); } }, background: "#fff", //这里给生成的图片默认背景,不然的话,如果你的html根节点没设置背景的话,会用黑色填充。 allowTaint: true //避免一些不识别的图片干扰,默认为false,遇到不识别的图片干扰则会停止处理html2canvas });
Although this method can convert html pages into pdf format, the generated pdf effect is obviously not as clear as a normal screenshot. If you have a better way, please give us some advice.
Related recommendations:
C#How to convert HTML to images or PDF?
A summary of how to convert Word to PDF in C
#Use HTML to generate a PDF example code
The above is the detailed content of js to convert html to pdf. For more information, please follow other related articles on the PHP Chinese website!

HTMLtagsareessentialforstructuringwebpages,enhancingaccessibility,SEO,andperformance.1)Theyareenclosedinanglebracketsandusedinpairstocreateahierarchicalstructure.2)SemantictagslikeandimproveuserexperienceandSEO.3)Creativetagslikeenabledynamicgraphics

Self-closingtagsinHTMLandXMLaretagsthatclosethemselveswithoutneedingaseparateclosingtag,simplifyingmarkupstructureandenhancingcodingefficiency.1)TheyareessentialinXMLforelementswithoutcontent,ensuringwell-formeddocuments.2)InHTML5,usageisflexiblebutr

To build a website with powerful functions and good user experience, HTML alone is not enough. The following technology is also required: JavaScript gives web page dynamic and interactiveness, and real-time changes are achieved by operating DOM. CSS is responsible for the style and layout of the web page to improve aesthetics and user experience. Modern frameworks and libraries such as React, Vue.js and Angular improve development efficiency and code organization structure.

Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools
