一、Unity WebGL 截图功能
附上参考连接:Unity开发WebGL杂记——实现截屏功能_unity中webgl录屏-CSDN博客
我的源码为:
public RawImage rawImage; [Header("存取截图数据")] public Texture2D screenShot; public void CallCoroutine() { StartCoroutine(ScrrenCapture(new Rect(0, 0, Screen.width, Screen.height))); Debug.Log(screenShot.width + " " + screenShot.height +"图片长宽"); rawImage.texture = screenShot; } IEnumerator ScrrenCapture(Rect rect) { screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); yield return new WaitForEndOfFrame(); screenShot.ReadPixels(rect, 0, 0); screenShot.Apply(); }
二、设置Word 模板
参考链接:Unity WebGL 下载替换Word模板数据_unity webgl生成world-CSDN博客
可下载此链接的工程文件进行更改,我就是使用的此链接工程文件进行更改,此链接为更改文本,下面讲一下如何插入图片
注意:图片必须使用%
三、将数据传入前端
[Header("图片数据")] public byte[] imageData; #region 初始化 LabReprotData reprotData = new LabReprotData(); reprotData.eid = "1234567890"; reprotData.name = "子讳"; reprotData.scroe = "88"; reprotData.imageData = ConvertTextureToBytes(jieTu.screenShot); /// <summary> /// 将 Texture2D 转换为字节数组 /// </summary> /// <param name="texture"></param> /// <returns></returns> private byte[] ConvertTextureToBytes(Texture2D texture) { byte[] bytes = texture.EncodeToPNG(); return bytes; }
四、设置前端功能
以下代码加入<head>中
<!--下载Word的插件-->
<script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/docxtemplater.js"></script> <script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/pizzip.js"></script> <script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/FileSaver.js"></script> <script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/pizzip-utils.js"></script> <script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/imagemodule.js"></script>
我的理解是类似于C#de using、后续添加的module模块可放置StreamingAssets/WebGLDownloadWordJS/js/文件夹下
以下代码加入 <script>中
//添加功能--------------------------------------------------------------------------------------- function HtmlDownloadWord(bytes, reportdata) { var blob = new Blob([bytes]); var url = window.URL.createObjectURL(blob); generate(url, reportdata); } function loadFile(url, callback) { PizZipUtils.getBinaryContent(url, callback); } //处理base64数据 const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/; const validBase64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; function base64Parser(dataURL) { if ( typeof dataURL !== "string" || !base64Regex.test(dataURL) ) { return false; } const stringBase64 = dataURL.replace(base64Regex, ""); if (!validBase64.test(stringBase64)) { throw new Error( "Error parsing base64 data, your data contains invalid characters" ); } // For nodejs, return a Buffer if (typeof Buffer !== "undefined" && Buffer.from) { return Buffer.from(stringBase64, "base64"); } // For browsers, return a string (of binary content) : const binaryString = window.atob(stringBase64); const len = binaryString.length; const bytes = new Uint8Array(len); for (let i = 0; i < len; i++) { const ascii = binaryString.charCodeAt(i); bytes[i] = ascii; } return bytes.buffer; } const imageOptions = { getImage(tag) { return base64Parser(tag); }, getSize() { console.log("大小已被调用"); return [100, 100]; }, }; function generate(url, reportdata) { loadFile( url, function (error, content) { if (error) { throw error; } //先处理unity传入的数据得到base64 reportdata = (reportdata.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/</g, '<') .replace(/>/g, '>'); reportdata = JSON.parse(reportdata) var imageBytes = reportdata.imageData; // 图片字节数组数据 // 将图片数据转换为 base64 格式 var imageBase64 = btoa(String.fromCharCode.apply(null, imageBytes)); imageBase64 = "data:image/png;base64," + imageBase64; console.log(imageBase64); var imageModule = new ImageModule(imageOptions); var zip = new PizZip(content); var doc = new window.docxtemplater(zip, { paragraphLoop: true, linebreaks: true, modules: [imageModule] }); //const image = doc.Media.addImage(doc, imageBytes, 230, 230); doc.compile(); const data = { eid: reportdata.eid, name: reportdata.name, scroe: reportdata.scroe, image: imageBase64, } //渲染模板 doc.render(data); var out = doc.getZip().generate({ type: "blob", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", compression: "DEFLATE", }); saveAs(out, "实验报告.docx"); }); }
五、添加docxtemplater-image-module-free模块
链接1:GitHub - Liang-F/docxtemplater-image-module-free:docxtemplater 的开源图像模块
链接2:GitHub - open-xml-templating/docxtemplater:从模板(Word、Powerpoint 和 Excel 文档)、Node.js、浏览器和命令行生成 docx、pptx 和 xlsx / 演示:https://www.docxtemplater.com/demo。#docx #office #generator #templating #report #json #generate #generation #template #create #pptx #docx #xlsx #react #vuejs #angularjs #browser #typescript #image #html #table #chart
此处附上两个链接用于下载模块,放置StreamingAssets/WebGLDownloadWordJS/js/文件夹下
六、演示视频
视频管理-CSDN创作中心
七、开发中遇到的Bug
1、第一个bug没有记录,是按照二中链接进行的时候网页端打不开。解决办法,进行到第五部后不往下进行,而是将下图中index.html的图片所示部分插入至打包后的index.html文件中
插入部分1
<!--下载Word的插件--><script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/docxtemplater.js"></script><script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/pizzip.js"></script><script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/FileSaver.js"></script><script type="text/javascript" src="StreamingAssets/WebGLDownloadWordJS/js/pizzip-utils.js"></script>
插入部分2
function HtmlDownloadWord(bytes,reportdata){var blob = new Blob([bytes]);var url = window.URL.createObjectURL(blob); generate(url,reportdata);}function loadFile(url, callback){ PizZipUtils.getBinaryContent(url, callback); } function generate(url,reportdata) { loadFile( url, function (error, content){ if (error) { throw error; } var zip = new PizZip(content); var doc = new window.docxtemplater(zip, { paragraphLoop: true, linebreaks: true, });reportdata = (reportdata.replace(/<(.|\n)*?>/g, '') || ' ').replace(/</g, '<').replace(/>/g, '>');reportdata = JSON.parse(reportdata) // Render the document (Replace {first_name} by John, {last_name} by Doe, ...) doc.render(reportdata); var out = doc.getZip().generate({ type: "blob", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // compression: DEFLATE adds a compression step. // For a 50MB output document, expect 500ms additional CPU time compression: "DEFLATE", }); // Output the document using Data-URI saveAs(out, "实验报告.docx"); } ); }
插入完成后打开即可正常替换word中文本,在次感谢下此链接作者
2、若模板word设置为
则生成的文档为
务必按照以下方式设置word模板
3、设置word模板应该换行,在一个大佬链接下看到的应该换行,链接找不到了(抱歉哈大佬)、 若按照以下方式设置,报错信息为,
4、报错信息如下
解决办法:在此StreamingAssets/WebGLDownloadWordJS/js/ 文件夹下打开 imagemodule.js文件,注释就行 (咱也不懂,注释了发现没问题就可以了)
八、结语
俺只是一个无情的搬运工,还得向大佬好好学习,若有大佬知其原理请与俺分享,第一次写博客,若有写不清晰之处还请见谅