The product requires that the company’s mini-programs and websites need to export product details into pdf, so today I’m thinking about how to export the front-end page into pdf
Reminder: Please modify the following code image address yourself.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>title</title> <style> .btn { width: 300px; height: 100px; } img { width: 100%; object-fit: cover; } </style> <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script> <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> </head> <body> <button type="button" > <h2> 微信小程序 </h2> <blockquote> <p>说明:公司小程序项目是用的uniapp开发的</p> </blockquote> <h3> 方法1:通过wx.miniProgram.postMessage将pdf数据传给小程序 </h3> <blockquote> <p>提醒:以下代码图片地址,请自行修改一下。</p> </blockquote>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>title</title> <style> .btn { width: 300px; height: 100px; } img { width: 100%; object-fit: cover; } </style> <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script> <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> </head> <body> <button type="button" > <ul> <li>uniapp 页面代码</li> </ul> <blockquote> <p>特别提醒:请将页面部署至自己的服务器下,然后修改一下地址,然后在小程序后台把部署的域名配置到web合法域名列表下,不然webview无法加载页面<br> </p> </blockquote> <pre class="brush:php;toolbar:false"> <template> <PageLayout> <web-view src="https://xxx.com/pdf_test.html" @message="handleGetMessage"></web-view> </PageLayout> </template> <script> export default { data() { return { imageData: "", } }, methods: { handleGetMessage(e) { console.log("收到webview消息:", e) this.imageData = e.detail.data[0].imageData console.log("收到webview消息: imageData=", this.imageData); const base64 = this.imageData.split("base64,")[1] console.log("收到webview消息: path=", base64); this.download(base64) }, async download(base64) { base64 = base64.replace(/[\r\n]/g, ""); const fs = wx.getFileSystemManager(); const buffer = wx.base64ToArrayBuffer(base64); const filePath = wx.env.USER_DATA_PATH + "/" + Date.now() + ".pdf" fs.writeFile({ filePath, data: buffer, success(res) { uni.openDocument({ showMenu: true, fileType: "pdf", filePath, success: function (res) { console.log("打开文档成功") } }) }, fail(err) { console.log("错误", err) } }) }, }, onLoad(e) { } } </script> <style scoped></style>
Additional note: If you encounter h5 sending a message through wx.miniProgram.postMessage, the mini program will not be able to search for the message, and returning and sharing will be useless. Solution: You can save the data to the backend, then pass the parameters to the applet through navigation, and then download the pdf. The specific codes are listed here, let’s briefly talk about the ideas
The above is the detailed content of uniapp Getting Started Practical Export the front-end page to pdf. For more information, please follow other related articles on the PHP Chinese website!