完善Action

增加webgl报告下载功能
This commit is contained in:
shenjianxing 2024-12-23 18:14:25 +08:00
parent 764db1059f
commit 2ea7b6a7a1
98 changed files with 19861 additions and 45 deletions

View File

@ -456,7 +456,7 @@ MonoBehaviour:
m_Name: m_Name:
m_EditorClassIdentifier: m_EditorClassIdentifier:
MarkType: 0 MarkType: 0
CustomComponentName: CustomComponentName: ItemPrefab
CustomComment: CustomComment:
mComponentName: UnityEngine.UI.Image mComponentName: UnityEngine.UI.Image
--- !u!1 &1710378140238201464 --- !u!1 &1710378140238201464
@ -2568,7 +2568,7 @@ MonoBehaviour:
m_Name: m_Name:
m_EditorClassIdentifier: m_EditorClassIdentifier:
MarkType: 0 MarkType: 0
CustomComponentName: CustomComponentName: Title
CustomComment: CustomComment:
mComponentName: TMPro.TextMeshProUGUI mComponentName: TMPro.TextMeshProUGUI
--- !u!1 &5360297828757190794 --- !u!1 &5360297828757190794
@ -5063,6 +5063,6 @@ MonoBehaviour:
m_Name: m_Name:
m_EditorClassIdentifier: m_EditorClassIdentifier:
MarkType: 0 MarkType: 0
CustomComponentName: CustomComponentName: Confirm
CustomComment: CustomComment:
mComponentName: UnityEngine.UI.Button mComponentName: UnityEngine.UI.Button

View File

@ -74,7 +74,8 @@ namespace QFramework
new NetImageResCreator(), new NetImageResCreator(),
new LocalImageResCreator(), new LocalImageResCreator(),
new LocalAudioResCreator(), new LocalAudioResCreator(),
new LocalTextResCreator() new LocalTextResCreator(),
new LocalBytesResCreator()
}; };
} }
@ -127,4 +128,16 @@ namespace QFramework
return LocalTextRes.Allocate(resSearchKeys.AssetName); return LocalTextRes.Allocate(resSearchKeys.AssetName);
} }
} }
public class LocalBytesResCreator : IResCreator
{
public bool Match(ResSearchKeys resSearchKeys)
{
return resSearchKeys.AssetName.StartsWith("localbytes:");
}
public IRes Create(ResSearchKeys resSearchKeys)
{
return LocalBytesRes.Allocate(resSearchKeys.AssetName);
}
}
} }

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dfeefe5a831ef4e408b8a4d30cbb07d1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,269 @@
using UnityEngine;
namespace QFramework
{
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public static class LocalBytesResUtil
{
public static string ToLocalBytesResName(this string selfFilePath)
{
return string.Format("localbytes:{0}", selfFilePath);
}
}
/// <summary>
/// 本地通用文件加载
/// </summary>
public class LocalBytesRes : Res
{
private string mFullPath;
private string mHashCode;
private object mRawAsset;
public byte[] bytes;
UnityWebRequest request;
public static LocalBytesRes Allocate(string name)
{
var res = SafeObjectPool<LocalBytesRes>.Instance.Allocate();
if (res != null)
{
res.AssetName = name;
res.SetUrl(name.Substring(11));
}
return res;
}
public void SetDownloadProgress(int totalSize, int download)
{
}
public string LocalResPath
{
get { return string.Format("{0}{1}", AssetBundlePathHelper.PersistentDataPath4Photo, mHashCode); }
}
public virtual object RawAsset
{
get { return mRawAsset; }
}
public bool NeedDownload
{
get { return RefCount > 0; }
}
public string Url
{
get { return mFullPath; }
}
public int FileSize
{
get { return 1; }
}
public void SetUrl(string url)
{
if (string.IsNullOrEmpty(url))
{
return;
}
mFullPath = url;
mHashCode = string.Format("Photo_{0}", mFullPath.GetHashCode());
}
public override bool UnloadImage(bool flag)
{
return false;
}
public override bool LoadSync()
{
return false;
}
public override void LoadAsync()
{
if (!CheckLoadAble())
{
return;
}
if (string.IsNullOrEmpty(mAssetName))
{
return;
}
DoLoadWork();
}
private void DoLoadWork()
{
State = ResState.Loading;
OnDownLoadResult(true);
//检测本地文件是否存在
/*
if (!File.Exists(LocalResPath))
{
ResDownloader.S.AddDownloadTask(this);
}
else
{
OnDownLoadResult(true);
}
*/
}
protected override void OnReleaseRes()
{
if (mAsset != null)
{
GameObject.Destroy(mAsset);
mAsset = null;
}
mRawAsset = null;
}
public override void Recycle2Cache()
{
SafeObjectPool<LocalBytesRes>.Instance.Recycle(this);
}
public override void OnRecycled()
{
}
public void DeleteOldResFile()
{
//throw new NotImplementedException();
}
public void OnDownLoadResult(bool result)
{
if (!result)
{
OnResLoadFaild();
return;
}
if (RefCount <= 0)
{
State = ResState.Waiting;
return;
}
ResMgr.Instance.PushIEnumeratorTask(this);
}
public override IEnumerator DoLoadAsync(System.Action finishCallback)
{
using (UnityWebRequest request = UnityWebRequest.Get(mFullPath))
{
request.downloadHandler = new DownloadHandlerBuffer();
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError(string.Format("Res:{0}, WWW Errors:{1}", mFullPath, request.error));
OnResLoadFaild();
finishCallback();
yield break;
}
else
{
// Convert the downloaded data to an AudioClip
bytes = request.downloadHandler.data;
}
if (RefCount <= 0)
{
OnResLoadFaild();
finishCallback();
yield break;
}
}
State = ResState.Ready;
finishCallback();
}
protected override float CalculateProgress()
{
if (request == null)
{
return 0;
}
return request.downloadProgress;
}
/*
public IEnumerator StartIEnumeratorTask2(Action finishCallback)
{
if (refCount <= 0)
{
OnResLoadFaild();
finishCallback();
yield break;
}
WWW www = new WWW("file://" + LocalResPath);
yield return www;
if (www.error != null)
{
Log.E("WWW Error:" + www.error);
OnResLoadFaild();
finishCallback();
yield break;
}
if (!www.isDone)
{
Log.E("NetImageRes WWW Not Done! Url:" + m_Url);
OnResLoadFaild();
finishCallback();
www.Dispose();
www = null;
yield break;
}
if (refCount <= 0)
{
OnResLoadFaild();
finishCallback();
www.Dispose();
www = null;
yield break;
}
TimeDebugger dt = new TimeDebugger("Tex");
dt.Begin("LoadingTask");
Texture2D tex = www.texture;
tex.Compress(true);
dt.End();
dt.Dump(-1);
m_Asset = tex;
www.Dispose();
www = null;
resState = eResState.kReady;
finishCallback();
}
*/
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 531af03c0530e404ebafb861aa56738c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,7 +1,6 @@
using QFramework.Example; using QFramework.Example;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine; using UnityEngine;
namespace QFramework namespace QFramework

View File

@ -1,6 +1,5 @@
using HighlightPlus; using HighlightPlus;
using System; using System;
using Unity.VisualScripting;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine; using UnityEngine;
namespace QFramework namespace QFramework

View File

@ -5,7 +5,6 @@ using QFramework;
using System; using System;
using QFramework.Example; using QFramework.Example;
using System.Linq; using System.Linq;
using Unity.VisualScripting;
public class TextQuestionAction : IAction public class TextQuestionAction : IAction
{ {
public ulong ActionID { get; set; } public ulong ActionID { get; set; }

View File

@ -5,7 +5,6 @@ using QFramework;
using System; using System;
using QFramework.Example; using QFramework.Example;
using System.Linq; using System.Linq;
using Unity.VisualScripting;
public class TextTipAction : IAction public class TextTipAction : IAction
{ {
public ulong ActionID { get; set; } public ulong ActionID { get; set; }

View File

@ -2,7 +2,6 @@ using QFramework;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine; using UnityEngine;
using XMLTool; using XMLTool;

View File

@ -19,6 +19,8 @@ public class Global : Singleton<Global>
public static string imagePath = dataPath + "/Image/"; public static string imagePath = dataPath + "/Image/";
public static string videoPath = dataPath + "/Video/"; public static string videoPath = dataPath + "/Video/";
public static string xmlPath = dataPath + "/Xml/"; public static string xmlPath = dataPath + "/Xml/";
public static string reportPath = dataPath + "/Report/";
public static string reportDemoPath = reportPath + "Demo.docx";
public static APPSetting appSetting { get; } = new APPSetting(); public static APPSetting appSetting { get; } = new APPSetting();
public enum AppType public enum AppType

View File

@ -2,7 +2,6 @@ using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
using QFramework; using QFramework;
using System.Collections.Generic; using System.Collections.Generic;
using Unity.VisualScripting;
namespace QFramework.Example namespace QFramework.Example
{ {

View File

@ -17,7 +17,6 @@ namespace QFramework.Example
setBtn.onClick.AddListener(() => setBtn.onClick.AddListener(() =>
{ {
UIKit.OpenPanelAsync<UIScore>(canvasLevel: UILevel.PopUI).ToAction().StartGlobal();
UIKit.OpenPanelAsync<UISetting>(canvasLevel: UILevel.PopUI).ToAction().StartGlobal(); UIKit.OpenPanelAsync<UISetting>(canvasLevel: UILevel.PopUI).ToAction().StartGlobal();
}); });
closeBtn.onClick.AddListener(() => closeBtn.onClick.AddListener(() =>
@ -52,7 +51,11 @@ namespace QFramework.Example
UIKit.OpenPanelAsync<UIInstruction>(canvasLevel: UILevel.PopUI).ToAction().StartGlobal(); UIKit.OpenPanelAsync<UIInstruction>(canvasLevel: UILevel.PopUI).ToAction().StartGlobal();
}); });
scoreBtn.onClick.AddListener(() => UIKit.OpenPanelAsync<UIScore>().ToAction().Start(this)); scoreBtn.onClick.AddListener(() =>
{
Debug.LogError("111");
UIKit.OpenPanelAsync<UIScore>().ToAction().StartGlobal();
});
} }
protected override void OnOpen(IUIData uiData = null) protected override void OnOpen(IUIData uiData = null)

View File

@ -1,11 +1,6 @@
using UnityEngine; using Newtonsoft.Json;
using UnityEngine.UI;
using QFramework;
using Unity.VisualScripting;
using System;
using System.Collections.Generic;
using XMLTool;
using TMPro; using TMPro;
using UnityEngine;
namespace QFramework.Example namespace QFramework.Example
{ {
@ -17,7 +12,6 @@ namespace QFramework.Example
protected override void OnInit(IUIData uiData = null) protected override void OnInit(IUIData uiData = null)
{ {
mData = uiData as UIScoreData ?? new UIScoreData(); mData = uiData as UIScoreData ?? new UIScoreData();
DownLoad.onClick.AddListener(() => DownLoad.onClick.AddListener(() =>
{ {
if (string.IsNullOrEmpty(InputName.text) || string.IsNullOrEmpty(InputId.text)) if (string.IsNullOrEmpty(InputName.text) || string.IsNullOrEmpty(InputId.text))
@ -25,6 +19,25 @@ namespace QFramework.Example
Debug.LogError("ÐÕÃû»òÕßѧºÅΪ¿Õ"); Debug.LogError("ÐÕÃû»òÕßѧºÅΪ¿Õ");
return; return;
} }
ResLoader loader = ResLoader.Allocate();
loader.Add2Load(Global.reportDemoPath.ToLocalBytesResName(), (success, res) =>
{
if (success)
{
byte[] bytes = res.As<LocalBytesRes>().bytes;
var data = new LabReprotData();
data.realname = InputName.text;
data.biaobencaiji_1_buzhou_1 = "[1111]";
string json = JsonConvert.SerializeObject(data);
#if UNITY_WEBGL
WebGLDownLoadFile.Instance.DownloadDocx(bytes, json);
#endif
}
});
loader.LoadAsync();
}); });
Confirm.onClick.AddListener(Hide); Confirm.onClick.AddListener(Hide);
} }

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dd662ae6ae3aaa64f8fab20605d738ef
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1b7643cfda78b234985b0d046709991a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,188 @@
/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.3.2
* 2016-06-16 18:25:19
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs || (function(view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var
doc = view.document
// only get URL when necessary in case Blob.js hasn't overridden it yet
, get_URL = function() {
return view.URL || view.webkitURL || view;
}
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
}
, is_safari = /constructor/i.test(view.HTMLElement) || view.safari
, is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
, throw_outside = function(ex) {
(view.setImmediate || view.setTimeout)(function() {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
, arbitrary_revoke_timeout = 1000 * 40 // in ms
, revoke = function(file) {
var revoker = function() {
if (typeof file === "string") { // file is an object URL
get_URL().revokeObjectURL(file);
} else { // file is a File
file.remove();
}
};
setTimeout(revoker, arbitrary_revoke_timeout);
}
, dispatch = function(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, auto_bom = function(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
}
return blob;
}
, FileSaver = function(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, force = type === force_saveable_type
, object_url
, dispatch_all = function() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function() {
if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function() {
var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
var popup = view.open(url, '_blank');
if(!popup) view.location.href = url;
url=undefined; // release reference before dispatching
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (!object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (force) {
view.location.href = object_url;
} else {
var opened = view.open(object_url, "_blank");
if (!opened) {
// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
}
;
filesaver.readyState = filesaver.INIT;
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
setTimeout(function() {
save_link.href = object_url;
save_link.download = name;
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
fs_error();
}
, FS_proto = FileSaver.prototype
, saveAs = function(blob, name, no_auto_bom) {
return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
}
;
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function(blob, name, no_auto_bom) {
name = name || blob.name || "download";
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name);
};
}
FS_proto.abort = function(){};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
return saveAs;
}(
typeof self !== "undefined" && self
|| typeof window !== "undefined" && window
|| this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
define("FileSaver.js", function() {
return saveAs;
});
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b553b668487059e46b20598af2094335
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 52a88145e15d97043b41a0ea7221595f
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 095271581e49eaf449f5ebb880baea13
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,112 @@
"use strict";
const DocUtils = require("./docUtils");
const extensionRegex = /[^.]+\.([^.]+)/;
const rels = {
getPrefix(fileType) {
return fileType === "docx" ? "word" : "ppt";
},
getFileTypeName(fileType) {
return fileType === "docx" ? "document" : "presentation";
},
getRelsFileName(fileName) {
return fileName.replace(/^.*?([a-zA-Z0-9]+)\.xml$/, "$1") + ".xml.rels";
},
getRelsFilePath(fileName, fileType) {
const relsFileName = rels.getRelsFileName(fileName);
const prefix = fileType === "pptx" ? "ppt/slides" : "word";
return `${prefix}/_rels/${relsFileName}`;
},
};
module.exports = class ImgManager {
constructor(zip, fileName, xmlDocuments, fileType) {
this.fileName = fileName;
this.prefix = rels.getPrefix(fileType);
this.zip = zip;
this.xmlDocuments = xmlDocuments;
this.fileTypeName = rels.getFileTypeName(fileType);
this.mediaPrefix = fileType === "pptx" ? "../media" : "media";
const relsFilePath = rels.getRelsFilePath(fileName, fileType);
this.relsDoc = xmlDocuments[relsFilePath] || this.createEmptyRelsDoc(xmlDocuments, relsFilePath);
}
createEmptyRelsDoc(xmlDocuments, relsFileName) {
const mainRels = this.prefix + "/_rels/" + (this.fileTypeName) + ".xml.rels";
const doc = xmlDocuments[mainRels];
if (!doc) {
const err = new Error("Could not copy from empty relsdoc");
err.properties = {
mainRels,
relsFileName,
files: Object.keys(this.zip.files),
};
throw err;
}
const relsDoc = DocUtils.str2xml(DocUtils.xml2str(doc));
const relationships = relsDoc.getElementsByTagName("Relationships")[0];
const relationshipChilds = relationships.getElementsByTagName("Relationship");
for (let i = 0, l = relationshipChilds.length; i < l; i++) {
relationships.removeChild(relationshipChilds[i]);
}
xmlDocuments[relsFileName] = relsDoc;
return relsDoc;
}
loadImageRels() {
const iterable = this.relsDoc.getElementsByTagName("Relationship");
return Array.prototype.reduce.call(iterable, function (max, relationship) {
const id = relationship.getAttribute("Id");
if (/^rId[0-9]+$/.test(id)) {
return Math.max(max, parseInt(id.substr(3), 10));
}
return max;
}, 0);
}
// Add an extension type in the [Content_Types.xml], is used if for example you want word to be able to read png files (for every extension you add you need a contentType)
addExtensionRels(contentType, extension) {
const contentTypeDoc = this.xmlDocuments["[Content_Types].xml"];
const defaultTags = contentTypeDoc.getElementsByTagName("Default");
const extensionRegistered = Array.prototype.some.call(defaultTags, function (tag) {
return tag.getAttribute("Extension") === extension;
});
if (extensionRegistered) {
return;
}
const types = contentTypeDoc.getElementsByTagName("Types")[0];
const newTag = contentTypeDoc.createElement("Default");
newTag.namespaceURI = null;
newTag.setAttribute("ContentType", contentType);
newTag.setAttribute("Extension", extension);
types.appendChild(newTag);
}
// Add an image and returns it's Rid
addImageRels(imageName, imageData, i) {
if (i == null) {
i = 0;
}
const realImageName = i === 0 ? imageName : imageName + `(${i})`;
const imagePath = `${this.prefix}/media/${realImageName}`;
if (this.zip.files[imagePath] != null) {
return this.addImageRels(imageName, imageData, i + 1);
}
const image = {
name: imagePath,
data: imageData,
options: {
binary: true,
},
};
this.zip.file(image.name, image.data, image.options);
const extension = realImageName.replace(extensionRegex, "$1");
this.addExtensionRels(`image/${extension}`, extension);
const relationships = this.relsDoc.getElementsByTagName("Relationships")[0];
const newTag = this.relsDoc.createElement("Relationship");
newTag.namespaceURI = null;
const maxRid = this.loadImageRels() + 1;
newTag.setAttribute("Id", `rId${maxRid}`);
newTag.setAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
newTag.setAttribute("Target", `${this.mediaPrefix}/${realImageName}`);
relationships.appendChild(newTag);
return maxRid;
}
};

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: db6aef5b5146b144e98c13ca162e5e5e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,176 @@
"use strict";
const templates = require("./templates");
const DocUtils = require("docxtemplater").DocUtils;
const DOMParser = require("xmldom").DOMParser;
function isNaN(number) {
return !(number === number);
}
const ImgManager = require("./imgManager");
const moduleName = "open-xml-templating/docxtemplater-image-module";
function getInnerDocx({part}) {
return part;
}
function getInnerPptx({part, left, right, postparsed}) {
const xmlString = postparsed.slice(left + 1, right).reduce(function (concat, item) {
return concat + item.value;
}, "");
const xmlDoc = new DOMParser().parseFromString("<xml>" + xmlString + "</xml>");
part.offset = {x: 0, y: 0};
part.ext = {cx: 0, cy: 0};
const offset = xmlDoc.getElementsByTagName("a:off");
const ext = xmlDoc.getElementsByTagName("a:ext");
if (ext.length > 0) {
part.ext.cx = parseInt(ext[ext.length - 1].getAttribute("cx"), 10);
part.ext.cy = parseInt(ext[ext.length - 1].getAttribute("cy"), 10);
}
if (offset.length > 0) {
part.offset.x = parseInt(offset[offset.length - 1].getAttribute("x"), 10);
part.offset.y = parseInt(offset[offset.length - 1].getAttribute("y"), 10);
}
return part;
}
class ImageModule {
constructor(options) {
this.name = "ImageModule";
this.options = options || {};
this.imgManagers = {};
if (this.options.centered == null) { this.options.centered = false; }
if (this.options.getImage == null) { throw new Error("You should pass getImage"); }
if (this.options.getSize == null) { throw new Error("You should pass getSize"); }
this.imageNumber = 1;
}
optionsTransformer(options, docxtemplater) {
const relsFiles = docxtemplater.zip.file(/\.xml\.rels/)
.concat(docxtemplater.zip.file(/\[Content_Types\].xml/))
.map((file) => file.name);
this.fileTypeConfig = docxtemplater.fileTypeConfig;
this.fileType = docxtemplater.fileType;
this.zip = docxtemplater.zip;
options.xmlFileNames = options.xmlFileNames.concat(relsFiles);
return options;
}
set(options) {
if (options.zip) {
this.zip = options.zip;
}
if (options.xmlDocuments) {
this.xmlDocuments = options.xmlDocuments;
}
}
parse(placeHolderContent) {
const module = moduleName;
const type = "placeholder";
if (this.options.setParser) {
return this.options.setParser(placeHolderContent);
}
if (placeHolderContent.substring(0, 2) === "%%") {
return {type, value: placeHolderContent.substr(2), module, centered: true};
}
if (placeHolderContent.substring(0, 1) === "%") {
return {type, value: placeHolderContent.substr(1), module, centered: false};
}
return null;
}
postparse(parsed) {
let expandTo;
let getInner;
if (this.fileType === "pptx") {
expandTo = "p:sp";
getInner = getInnerPptx;
}
else {
expandTo = this.options.centered ? "w:p" : "w:t";
getInner = getInnerDocx;
}
return DocUtils.traits.expandToOne(parsed, {moduleName, getInner, expandTo});
}
render(part, options) {
if (!part.type === "placeholder" || part.module !== moduleName) {
return null;
}
const tagValue = options.scopeManager.getValue(part.value, {
part: part,
});
if (!tagValue) {
return {value: this.fileTypeConfig.tagTextXml};
}
else if (typeof tagValue === "object") {
return this.getRenderedPart(part, tagValue.rId, tagValue.sizePixel);
}
const imgManager = new ImgManager(this.zip, options.filePath, this.xmlDocuments, this.fileType);
const imgBuffer = this.options.getImage(tagValue, part.value);
const rId = imgManager.addImageRels(this.getNextImageName(), imgBuffer);
const sizePixel = this.options.getSize(imgBuffer, tagValue, part.value);
return this.getRenderedPart(part, rId, sizePixel);
}
resolve(part, options) {
const imgManager = new ImgManager(this.zip, options.filePath, this.xmlDocuments, this.fileType);
if (!part.type === "placeholder" || part.module !== moduleName) {
return null;
}
const value = options.scopeManager.getValue(part.value, {
part: part,
});
if (!value) {
return {value: this.fileTypeConfig.tagTextXml};
}
return new Promise((resolve) => {
const imgBuffer = this.options.getImage(value, part.value);
resolve(imgBuffer);
}).then((imgBuffer) => {
const rId = imgManager.addImageRels(this.getNextImageName(), imgBuffer);
return new Promise((resolve) => {
const sizePixel = this.options.getSize(imgBuffer, value, part.value);
resolve(sizePixel);
}).then((sizePixel) => {
return {
rId: rId,
sizePixel: sizePixel,
};
});
});
}
getRenderedPart(part, rId, sizePixel) {
if (isNaN(rId)) {
throw new Error("rId is NaN, aborting");
}
const size = [DocUtils.convertPixelsToEmus(sizePixel[0]), DocUtils.convertPixelsToEmus(sizePixel[1])];
const centered = (this.options.centered || part.centered);
let newText;
if (this.fileType === "pptx") {
newText = this.getRenderedPartPptx(part, rId, size, centered);
}
else {
newText = this.getRenderedPartDocx(rId, size, centered);
}
return {value: newText};
}
getRenderedPartPptx(part, rId, size, centered) {
const offset = {x: parseInt(part.offset.x, 10), y: parseInt(part.offset.y, 10)};
const cellCX = parseInt(part.ext.cx, 10) || 1;
const cellCY = parseInt(part.ext.cy, 10) || 1;
const imgW = parseInt(size[0], 10) || 1;
const imgH = parseInt(size[1], 10) || 1;
if (centered) {
offset.x = Math.round(offset.x + (cellCX / 2) - (imgW / 2));
offset.y = Math.round(offset.y + (cellCY / 2) - (imgH / 2));
}
return templates.getPptxImageXml(rId, [imgW, imgH], offset);
}
getRenderedPartDocx(rId, size, centered) {
return centered ? templates.getImageXmlCentered(rId, size) : templates.getImageXml(rId, size);
}
getNextImageName() {
const name = `image_generated_${this.imageNumber}.png`;
this.imageNumber++;
return name;
}
}
module.exports = ImageModule;

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4adcc011b5c00c546bb56bb78c51b048
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4082be133e63a564fa250e363c74a70a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,42 @@
{
"name": "docxtemplater-image-module-free",
"version": "1.1.1",
"description": "Open Source Image Module for docxtemplater",
"main": "js/index.js",
"scripts": {
"test:coverage": "istanbul cover _mocha -- es6/test.js",
"compile": "rimraf js && mkdirp js && babel es6 --out-dir js",
"preversion": "npm test && npm run browserify && npm run uglify",
"test:compiled": "mocha js/test.js",
"test:es6": "mocha es6/test.js",
"lint": "eslint .",
"test": "npm run compile && npm run test:compiled",
"browserify": "rimraf build && mkdirp build && browserify --insert-global-vars __filename,__dirname -r ./js/index.js -s ImageModule > build/imagemodule.js",
"uglify": "uglifyjs build/imagemodule.js > build/imagemodule.min.js"
},
"devDependencies": {
"babel-cli": "^6.11.4",
"babel-eslint": "^7.1.1",
"babel-preset-es2015": "^6.3.13",
"browserify": "^14.0.0",
"chai": "^3.4.1",
"docxtemplater": "^3.0.0",
"eslint": "^3.15.0",
"image-size": "^0.5.1",
"istanbul": "^0.4.5",
"jszip": "^2.6.1",
"mkdirp": "^0.5.1",
"mocha": "^3.2.0",
"rimraf": "^2.5.4",
"uglifyjs": "^2.4.10"
},
"repository": {
"type": "git",
"url": "https://github.com/evilc0des/docxtemplater-image-module-free"
},
"author": "Dk Saha",
"license": "MIT",
"dependencies": {
"xmldom": "^0.1.27"
}
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c58b4a08eec032540a18c3556b4062c5
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,112 @@
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./es6/index_IE.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "../node_modules/webpack/buildin/global.js":
/*!*************************************************!*\
!*** ../node_modules/webpack/buildin/global.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n\n\n//# sourceURL=webpack:///../node_modules/webpack/buildin/global.js?");
/***/ }),
/***/ "./es6/index_IE.js":
/*!*************************!*\
!*** ./es6/index_IE.js ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/* WEBPACK VAR INJECTION */(function(global) {/* global IEBinaryToArray_ByteStr, IEBinaryToArray_ByteStr_Last */\n // Adapted from http://stackoverflow.com/questions/1095102/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest\n\nvar IEBinaryToArray_ByteStr_Script = \"<!-- IEBinaryToArray_ByteStr -->\\r\\n\" + \"<script type='text/vbscript'>\\r\\n\" + \"Function IEBinaryToArray_ByteStr(Binary)\\r\\n\" + \" IEBinaryToArray_ByteStr = CStr(Binary)\\r\\n\" + \"End Function\\r\\n\" + \"Function IEBinaryToArray_ByteStr_Last(Binary)\\r\\n\" + \" Dim lastIndex\\r\\n\" + \" lastIndex = LenB(Binary)\\r\\n\" + \" if lastIndex mod 2 Then\\r\\n\" + \" IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\\r\\n\" + \" Else\\r\\n\" + \" IEBinaryToArray_ByteStr_Last = \" + '\"\"' + \"\\r\\n\" + \" End If\\r\\n\" + \"End Function\\r\\n\" + \"</script>\\r\\n\"; // inject VBScript\n\ndocument.write(IEBinaryToArray_ByteStr_Script);\n\nglobal.PizZipUtils._getBinaryFromXHR = function (xhr) {\n var binary = xhr.responseBody;\n var byteMapping = {};\n\n for (var i = 0; i < 256; i++) {\n for (var j = 0; j < 256; j++) {\n byteMapping[String.fromCharCode(i + (j << 8))] = String.fromCharCode(i) + String.fromCharCode(j);\n }\n }\n\n var rawBytes = IEBinaryToArray_ByteStr(binary);\n var lastChr = IEBinaryToArray_ByteStr_Last(binary);\n return rawBytes.replace(/[\\s\\S]/g, function (match) {\n return byteMapping[match];\n }) + lastChr;\n};\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ \"../node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./es6/index_IE.js?");
/***/ })
/******/ });

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 68284ab593af17c4d975a9a59770c57c
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,102 @@
window["PizZipUtils"] =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./es6/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./es6/index.js":
/*!**********************!*\
!*** ./es6/index.js ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar PizZipUtils = {}; // just use the responseText with xhr1, response with xhr2.\n// The transformation doesn't throw away high-order byte (with responseText)\n// because PizZip handles that case. If not used with PizZip, you may need to\n// do it, see https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data\n\nPizZipUtils._getBinaryFromXHR = function (xhr) {\n // for xhr.responseText, the 0xFF mask is applied by PizZip\n return xhr.response || xhr.responseText;\n}; // taken from jQuery\n\n\nfunction createStandardXHR() {\n try {\n return new window.XMLHttpRequest();\n } catch (e) {}\n}\n\nfunction createActiveXHR() {\n try {\n return new window.ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {}\n} // Create the request object\n\n\nvar createXHR = window.ActiveXObject ?\n/* Microsoft failed to properly\n * implement the XMLHttpRequest in IE7 (can't request local files),\n * so we use the ActiveXObject when it is available\n * Additionally XMLHttpRequest can be disabled in IE7/IE8 so\n * we need a fallback.\n */\nfunction () {\n return createStandardXHR() || createActiveXHR();\n} : // For all other browsers, use the standard XMLHttpRequest object\ncreateStandardXHR;\n\nPizZipUtils.getBinaryContent = function (path, callback) {\n /*\n * Here is the tricky part : getting the data.\n * In firefox/chrome/opera/... setting the mimeType to 'text/plain; charset=x-user-defined'\n * is enough, the result is in the standard xhr.responseText.\n * cf https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Receiving_binary_data_in_older_browsers\n * In IE <= 9, we must use (the IE only) attribute responseBody\n * (for binary data, its content is different from responseText).\n * In IE 10, the 'charset=x-user-defined' trick doesn't work, only the\n * responseType will work :\n * http://msdn.microsoft.com/en-us/library/ie/hh673569%28v=vs.85%29.aspx#Binary_Object_upload_and_download\n *\n * I'd like to use jQuery to avoid this XHR madness, but it doesn't support\n * the responseType attribute : http://bugs.jquery.com/ticket/11461\n */\n try {\n var xhr = createXHR();\n xhr.open(\"GET\", path, true); // recent browsers\n\n if (\"responseType\" in xhr) {\n xhr.responseType = \"arraybuffer\";\n } // older browser\n\n\n if (xhr.overrideMimeType) {\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\n }\n\n xhr.onreadystatechange = function (evt) {\n var file, err; // use `xhr` and not `this`... thanks IE\n\n if (xhr.readyState === 4) {\n if (xhr.status === 200 || xhr.status === 0) {\n file = null;\n err = null;\n\n try {\n file = PizZipUtils._getBinaryFromXHR(xhr);\n } catch (e) {\n err = new Error(e);\n }\n\n callback(err, file);\n } else {\n callback(new Error(\"Ajax error for \" + path + \" : \" + this.status + \" \" + this.statusText), null);\n }\n }\n };\n\n xhr.send();\n } catch (e) {\n callback(new Error(e), null);\n }\n};\n\nmodule.exports = PizZipUtils;\n\n//# sourceURL=webpack://PizZipUtils/./es6/index.js?");
/***/ })
/******/ });

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: d364e43be597f06488ecbd133c325c5a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 319996a31f07b28489f8ccda03d02992
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dccac8cab0f011148a986b08df7ad611
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c30ea19771718df4082a72c69a62a2da
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@ -0,0 +1,15 @@
mergeInto(LibraryManager.library, {
WebGLDownloadWord : function(array,size,reportjson)
{
var reportdata= UTF8ToString(reportjson);
var bytes = new Uint8Array(size);
for (var i = 0; i < size; i++)
{
bytes[i] = HEAPU8[array + i];
}
HtmlDownloadWord(bytes,reportdata);
}
});

View File

@ -0,0 +1,32 @@
fileFormatVersion: 2
guid: 3c5db0930befe7d419f28aed73f4dcd9
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
WebGL: WebGL
second:
enabled: 1
settings: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3f8ba2d94d39cde4497a65c1ececf209
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,17 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bca17604ecf2ff74a8c8bc9974e71bb3, type: 3}
m_Name: "\u4E0B\u8F7DWord\u914D\u7F6E\u6587\u4EF6"
m_EditorClassIdentifier:
Author: Chao
PackPathName: KunChong
TemplatePath: Assets/StreamingAssets/Template/

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c37e63a24fee820468a5815cbf92ec10
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1e590c4ae3cc2b3428e1aee0548579e6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 63ad792ad5744fb4e86f31716e3e26fe
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fce78ddffb926bf4cba621fc565358ba
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 95cfb9a8de2c1274fb9b3219d5518aec
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,37 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScreenShot : MonoBehaviour
{
public Texture2D screenImage;
public void Shot(Action<string> callBack)
{
//if (MVC.GetModel<KunChongModel>().IsKaoHe)
//{
// StartCoroutine(ScrrenCapture(callBack));
//}
}
IEnumerator ScrrenCapture(Action<string> callBack)
{
yield return new WaitForEndOfFrame();
// 创建一个新的Texture2D对象尺寸为屏幕当前分辨率
screenImage = new Texture2D(Screen.width, Screen.height);
// 读取屏幕上当前帧的像素
screenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
screenImage.Apply();
//生成Base64
string base64 = "data:image/png;base64," + Texture2DToBase64(screenImage);
// 清理
callBack?.Invoke(base64);
}
public string Texture2DToBase64(Texture2D texture)
{
byte[] data = texture.EncodeToPNG();
return Convert.ToBase64String(data);
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9f66816bedeb18345a5f4f55bef8f9b0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: df4bb7b1427ea994c935597c8276fd22
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,259 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
/// <summary>
/// 实验报告基础参数
/// </summary>
[Serializable]
public class LabReprotData
{
public string realname;
#region
public string xuanzeti_1;
public string xuanzeti_2;
public string xuanzeti_3;
public string xuanzeti_4;
public string xuanzeti_5;
public string xuanzeti_6;
public string xuanzeti_7;
public string xuanzeti_8;
public string xuanzeti_9;
public string xuanzeti_10;
public string xuanzeti_11;
public string xuanzeti_12;
public string xuanzeti_13;
public string xuanzeti_14;
public string xuanzeti_15;
#endregion
#region 1
public string biaobencaiji_1_name;
public string biaobencaiji_1_shijian;
public string biaobencaiji_1_buzhou_1;
public string biaobencaiji_1_jilu_1;
public string biaobencaiji_1_image_1;
public string biaobencaiji_1_daan_1;
public string biaobencaiji_1_buzhou_2;
public string biaobencaiji_1_jilu_2;
public string biaobencaiji_1_image_2;
public string biaobencaiji_1_daan_2;
public string biaobencaiji_1_buzhou_3;
public string biaobencaiji_1_jilu_3;
public string biaobencaiji_1_image_3;
public string biaobencaiji_1_daan_3;
public string biaobencaiji_1_buzhou_4;
public string biaobencaiji_1_jilu_4;
public string biaobencaiji_1_image_4;
public string biaobencaiji_1_daan_4;
public string biaobencaiji_1_buzhou_5;
public string biaobencaiji_1_jilu_5;
public string biaobencaiji_1_image_5;
public string biaobencaiji_1_daan_5;
#endregion
#region 2
public string biaobencaiji_2_name;
public string biaobencaiji_2_shijian;
public string biaobencaiji_2_buzhou_1;
public string biaobencaiji_2_jilu_1;
public string biaobencaiji_2_image_1;
public string biaobencaiji_2_daan_1;
public string biaobencaiji_2_buzhou_2;
public string biaobencaiji_2_jilu_2;
public string biaobencaiji_2_image_2;
public string biaobencaiji_2_daan_2;
public string biaobencaiji_2_buzhou_3;
public string biaobencaiji_2_jilu_3;
public string biaobencaiji_2_image_3;
public string biaobencaiji_2_daan_3;
public string biaobencaiji_2_buzhou_4;
public string biaobencaiji_2_jilu_4;
public string biaobencaiji_2_image_4;
public string biaobencaiji_2_daan_4;
#endregion
#region 3
public string biaobencaiji_3_name;
public string biaobencaiji_3_shijian;
public string biaobencaiji_3_buzhou_1;
public string biaobencaiji_3_jilu_1;
public string biaobencaiji_3_image_1;
public string biaobencaiji_3_daan_1;
public string biaobencaiji_3_buzhou_2;
public string biaobencaiji_3_jilu_2;
public string biaobencaiji_3_image_2;
public string biaobencaiji_3_daan_2;
public string biaobencaiji_3_buzhou_3;
public string biaobencaiji_3_jilu_3;
public string biaobencaiji_3_image_3;
public string biaobencaiji_3_daan_3;
public string biaobencaiji_3_buzhou_4;
public string biaobencaiji_3_jilu_4;
public string biaobencaiji_3_image_4;
public string biaobencaiji_3_daan_4;
#endregion
#region 4
public string biaobencaiji_4_name;
public string biaobencaiji_4_shijian;
public string biaobencaiji_4_buzhou_1;
public string biaobencaiji_4_jilu_1;
public string biaobencaiji_4_image_1;
public string biaobencaiji_4_daan_1;
public string biaobencaiji_4_buzhou_2;
public string biaobencaiji_4_jilu_2;
public string biaobencaiji_4_image_2;
public string biaobencaiji_4_daan_2;
public string biaobencaiji_4_buzhou_3;
public string biaobencaiji_4_jilu_3;
public string biaobencaiji_4_image_3;
public string biaobencaiji_4_daan_3;
public string biaobencaiji_4_buzhou_4;
public string biaobencaiji_4_jilu_4;
public string biaobencaiji_4_image_4;
public string biaobencaiji_4_daan_4;
#endregion
#region 5
public string biaobencaiji_5_name;
public string biaobencaiji_5_shijian;
public string biaobencaiji_5_buzhou_1;
public string biaobencaiji_5_jilu_1;
public string biaobencaiji_5_image_1;
public string biaobencaiji_5_daan_1;
public string biaobencaiji_5_buzhou_2;
public string biaobencaiji_5_jilu_2;
public string biaobencaiji_5_image_2;
public string biaobencaiji_5_daan_2;
public string biaobencaiji_5_buzhou_3;
public string biaobencaiji_5_jilu_3;
public string biaobencaiji_5_image_3;
public string biaobencaiji_5_daan_3;
public string biaobencaiji_5_buzhou_4;
public string biaobencaiji_5_jilu_4;
public string biaobencaiji_5_image_4;
public string biaobencaiji_5_daan_4;
#endregion
#region 6
public string biaobencaiji_6_name;
public string biaobencaiji_6_shijian;
public string biaobencaiji_6_buzhou_1;
public string biaobencaiji_6_jilu_1;
public string biaobencaiji_6_image_1;
public string biaobencaiji_6_daan_1;
public string biaobencaiji_6_buzhou_2;
public string biaobencaiji_6_jilu_2;
public string biaobencaiji_6_image_2;
public string biaobencaiji_6_daan_2;
public string biaobencaiji_6_buzhou_3;
public string biaobencaiji_6_jilu_3;
public string biaobencaiji_6_image_3;
public string biaobencaiji_6_daan_3;
public string biaobencaiji_6_buzhou_4;
public string biaobencaiji_6_jilu_4;
public string biaobencaiji_6_image_4;
public string biaobencaiji_6_daan_4;
#endregion
#region 1
public string biaobenzhizuo_1_name;
public string biaobenzhizuo_1_jilu_1;
public string biaobenzhizuo_1_image_1;
public string biaobenzhizuo_1_daan_1;
public string biaobenzhizuo_1_jilu_2;
public string biaobenzhizuo_1_image_2;
public string biaobenzhizuo_1_daan_2;
public string biaobenzhizuo_1_jilu_3;
public string biaobenzhizuo_1_image_3;
public string biaobenzhizuo_1_daan_3;
public string biaobenzhizuo_1_jilu_4;
public string biaobenzhizuo_1_image_4;
public string biaobenzhizuo_1_daan_4;
public string biaobenzhizuo_1_jilu_5;
public string biaobenzhizuo_1_image_5;
public string biaobenzhizuo_1_daan_5;
#endregion
#region 2
public string biaobenzhizuo_2_name;
public string biaobenzhizuo_2_jilu_1;
public string biaobenzhizuo_2_image_1;
public string biaobenzhizuo_2_daan_1;
public string biaobenzhizuo_2_jilu_2;
public string biaobenzhizuo_2_image_2;
public string biaobenzhizuo_2_daan_2;
public string biaobenzhizuo_2_jilu_3;
public string biaobenzhizuo_2_image_3;
public string biaobenzhizuo_2_daan_3;
#endregion
#region 3
public string biaobenzhizuo_3_name;
public string biaobenzhizuo_3_jilu_1;
public string biaobenzhizuo_3_image_1;
public string biaobenzhizuo_3_daan_1;
public string biaobenzhizuo_3_jilu_2;
public string biaobenzhizuo_3_image_2;
public string biaobenzhizuo_3_daan_2;
public string biaobenzhizuo_3_jilu_3;
public string biaobenzhizuo_3_image_3;
public string biaobenzhizuo_3_daan_3;
#endregion
#region 4
public string biaobenzhizuo_4_name;
public string biaobenzhizuo_4_jilu_1;
public string biaobenzhizuo_4_image_1;
public string biaobenzhizuo_4_daan_1;
public string biaobenzhizuo_4_jilu_2;
public string biaobenzhizuo_4_image_2;
public string biaobenzhizuo_4_daan_2;
public string biaobenzhizuo_4_jilu_3;
public string biaobenzhizuo_4_image_3;
public string biaobenzhizuo_4_daan_3;
public string biaobenzhizuo_4_jilu_4;
public string biaobenzhizuo_4_image_4;
public string biaobenzhizuo_4_daan_4;
public string biaobenzhizuo_4_jilu_5;
public string biaobenzhizuo_4_image_5;
public string biaobenzhizuo_4_daan_5;
public string biaobenzhizuo_4_jilu_6;
public string biaobenzhizuo_4_image_6;
public string biaobenzhizuo_4_daan_6;
public string biaobenzhizuo_4_jilu_7;
public string biaobenzhizuo_4_image_7;
public string biaobenzhizuo_4_daan_7;
public string biaobenzhizuo_4_jilu_8;
public string biaobenzhizuo_4_image_8;
public string biaobenzhizuo_4_daan_8;
public string biaobenzhizuo_4_jilu_9;
public string biaobenzhizuo_4_image_9;
public string biaobenzhizuo_4_daan_9;
public string biaobenzhizuo_4_jilu_10;
public string biaobenzhizuo_4_image_10;
public string biaobenzhizuo_4_daan_10;
public string biaobenzhizuo_4_jilu_11;
public string biaobenzhizuo_4_image_11;
public string biaobenzhizuo_4_daan_11;
public string biaobenzhizuo_4_jilu_12;
public string biaobenzhizuo_4_image_12;
public string biaobenzhizuo_4_daan_12;
public string biaobenzhizuo_4_jilu_13;
public string biaobenzhizuo_4_image_13;
public string biaobenzhizuo_4_daan_13;
#endregion
#region 5
public string biaobenzhizuo_diechihua_image;
#endregion
#region 1
public string kunchongjiepou_1_name;
public string kunchongjiepou_1_buzhou_1;
public string kunchongjiepou_1_jilu_1;
public string kunchongjiepou_1_image_1;
public string kunchongjiepou_1_daan_1;
public string kunchongjiepou_1_buzhou_2;
public string kunchongjiepou_1_jilu_2;
public string kunchongjiepou_1_image_2;
public string kunchongjiepou_1_daan_2;
public string kunchongjiepou_1_buzhou_3;
public string kunchongjiepou_1_jilu_3;
public string kunchongjiepou_1_image_3;
public string kunchongjiepou_1_daan_3;
#endregion
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 88f29195f280e2b4aaff177780c5bcd0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5bd960b5c0324a542b043cc588092b8a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b448d06c5c5ff52468263f9ad64fad22
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,66 @@
using QFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// 下载Word脚本
/// </summary>
public class WebGLDownLoadFile : MonoSingleton<WebGLDownLoadFile>
{
[DllImport("__Internal")]
private static extern void WebGLDownloadWord(byte[] array, int size, string reportjson);
/// <summary>
/// 下载Word 方法
/// </summary>
public void Download(string json)
{
#region
//LabReprotData reprotData = new LabReprotData();
//// 转json
//string json = JsonUtility.ToJson(reprotData, true);
#endregion
// 调用携程下载数据
StartCoroutine(WebGLDownloadWord(json));
}
/// <summary>
/// 下载Word
/// </summary>
/// <param name="json">实验报告json</param>
/// <returns></returns>
IEnumerator WebGLDownloadWord(string json)
{
UnityWebRequest request = UnityWebRequest.Get(Global.reportDemoPath);
yield return request.SendWebRequest();
if (request.isHttpError || request.isNetworkError)
{
Debug.Log("错误路径:" + request.error);
}
else
{
// 下载word
DownloadDocx(request.downloadHandler.data, json);
}
}
/// <summary>
/// 调用下载Word
/// </summary>
/// <param name="bytes">支持多种文件格式下载doc docx xml xlsx txt等</param>
/// <param name="reportjson">json数据</param>
public void DownloadDocx(byte[] bytes, string reportjson)
{
WebGLDownloadWord(bytes, bytes.Length, reportjson);
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 40ec725cf2804f149acc5f79096b0f59
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 98a6b80550e33de4c8d7a6880d9d6eb7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,70 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.ProjectWindowCallback;
using UnityEngine;
public class CreateHtml
{
[MenuItem("Assets/Create/创建WordAssets文件/Webgl Index Html", false, 60)]
public static void CreateIndex()
{
//参数为传递给CreateEventCSScriptAsset类action方法的参数
var endNameEditAction = ScriptableObject.CreateInstance<CreateEventCSScriptAsset>();
var icon = EditorGUIUtility.FindTexture("html Script Icon");
var resourceFile = "Assets/StreamingAssets/Template/" + "Index.html.txt";
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, endNameEditAction, "index.html", icon, resourceFile);
}
}
public class CreateEventCSScriptAsset : EndNameEditAction
{
public override void Action(int instanceId, string pathName, string resourceFile)
{
//创建资源
UnityEngine.Object obj = CreateScriptAssetFromTemplate(pathName, resourceFile);
ProjectWindowUtil.ShowCreatedAsset(obj);//高亮显示资源
}
private static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile)
{
//获取要创建资源的绝对路径
string fullPath = Path.GetFullPath(pathName);
//读取本地的模板文件
StreamReader streamReader = new StreamReader(resourceFile);
string text = streamReader.ReadToEnd();
streamReader.Close();
//获取文件名,不含扩展名
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
text = Regex.Replace(text, "#ScriptName#", fileNameWithoutExtension);
text = Regex.Replace(text, "#Author#", WordConfig.Instance.Author);
text = Regex.Replace(text, "#ProgramName#", PlayerSettings.productName);
text = Regex.Replace(text, "#NowTime#", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
text = Regex.Replace(text, "#ReleasePathName#", WordConfig.Instance.PackPathName);
//写入配置文件
bool encoderShouldEmitUTF8Identifier = true; //参数指定是否提供 Unicode 字节顺序标记
bool throwOnInvalidBytes = false;//是否在检测到无效的编码时引发异常
bool append = false;
UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
streamWriter.Write(text);
streamWriter.Close();
//刷新资源管理器
AssetDatabase.ImportAsset(pathName);
AssetDatabase.Refresh();
return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object));
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4b73c4f0759d3ca4e96d8a83388d6e8f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,50 @@
using System.IO;
using UnityEditor;
using UnityEngine;
[CreateAssetMenu(fileName = "下载Word配置文件", menuName = "创建WordAssets文件/配置文件")]
public class WordConfig : ScriptableObject
{
/// <summary>
/// 作者
/// </summary>
[Header("作者")]
public string Author = "ChenXiang";
/// <summary>
/// 项目发布目录名称
/// </summary>
[Header("项目发布目录名称")]
public string PackPathName = "目录名称";
/// <summary>
/// 模板路径
/// </summary>
[Header("模板路径")]
public string TemplatePath = "Assets/StreamingAssets/Template/";
private static WordConfig instance;
public static WordConfig Instance
{
get
{
if (instance != null)
{
return instance;
}
instance = Resources.Load<WordConfig>("下载Word配置文件");
if (instance == null)
{
Debug.Log("Resources资源为空请创建文件");
instance = CreateInstance<WordConfig>();
AssetDatabase.CreateAsset(instance, Application.dataPath + "/Resources");
}
return instance;
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: befc8bc5bf204f047a84c5781e59ffc4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,55 @@
using System.IO;
using UnityEditor;
using UnityEngine;
/// <summary>
/// 脚本配置窗口
/// </summary>
public class WordConfigWindow : EditorWindow
{
/// <summary>
/// 脚本配置菜单
/// </summary>
// 添加一个新的菜单项 CTRL-SHIFT-A
[MenuItem("WordConfig/WordConfigWindow &f")]
static void ScriptsConfig()
{
WordConfigWindow configWindow = new WordConfigWindow();
configWindow.minSize = new Vector2(600, 300);
configWindow.maxSize = new Vector2(600, 300);
configWindow.Show();
}
/// <summary>
///
/// </summary>
private void OnGUI()
{
GUILayout.BeginVertical();
GUILayout.Space(30);
GUI.skin.label.fontSize = 15;
GUI.skin.label.alignment = TextAnchor.UpperLeft;
this.titleContent = new GUIContent("脚本生成配置");
WordConfig.Instance.Author = EditorGUILayout.TextField("作者:", WordConfig.Instance.Author);
GUILayout.Space(10);
WordConfig.Instance.PackPathName = EditorGUILayout.TextField("项目发布路径名称:", WordConfig.Instance.PackPathName);
GUILayout.Space(10);
WordConfig.Instance.TemplatePath = EditorGUILayout.TextField("模板路径:", WordConfig.Instance.TemplatePath);
GUILayout.Space(10);
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUILayout.Space(20);
GUI.color = Color.red;
if (GUILayout.Button("完成"))
{
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
this.Close();
}
GUILayout.EndVertical();
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 40feb81115ab2284e8d2f91c2b43fb93
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 63c7c33a4de7c1140a01accacaa7207e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ede503a0aff83fa498b0c5c84393bfeb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 91ccf9d64a1bf0a4ca1b0ac2cbf65334
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2da7d930a5ab01b458ca7df71f866fac
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 B

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f2665bcab28e22345a2bf37bbe0f2795
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 B

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 81e033af8edb73145bb263061bebe3d8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 B

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 49d2c72c83498db418cc7b7999989df3
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 B

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 56cb493fa5a4d8f4cb482da5c2ad961e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 B

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9e1b936f6306a1e4aa6f71ffe665f38a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,16 @@
body { padding: 0; margin: 0 }
#unity-container { position: absolute }
#unity-container.unity-desktop { left: 50%; top: 50%; transform: translate(-50%, -50%) }
#unity-container.unity-mobile { width: 100%; height: 100% }
#unity-canvas { background: #231F20 }
.unity-mobile #unity-canvas { width: 100%; height: 100% }
#unity-loading-bar { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); display: none }
#unity-logo { width: 154px; height: 130px; background: url('unity-logo-dark.png') no-repeat center }
#unity-progress-bar-empty { width: 141px; height: 18px; margin-top: 10px; margin-left: 6.5px; background: url('progress-bar-empty-dark.png') no-repeat center }
#unity-progress-bar-full { width: 0%; height: 18px; margin-top: 10px; background: url('progress-bar-full-dark.png') no-repeat center }
#unity-footer { position: relative }
.unity-mobile #unity-footer { display: none }
#unity-webgl-logo { float:left; width: 204px; height: 38px; background: url('webgl-logo.png') no-repeat center }
#unity-build-title { float: right; margin-right: 10px; line-height: 38px; font-family: arial; font-size: 18px }
#unity-fullscreen-button { float: right; width: 38px; height: 38px; background: url('fullscreen-button.png') no-repeat center }
#unity-warning { position: absolute; left: 50%; top: 5%; transform: translate(-50%); background: white; padding: 10px; display: none }

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: acee3b9096daa234f91ebb3aa546a2ba
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2a5ef3c252e921a459ed647cde8c6310
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e64b57b6cb9372a49a9abff0f55f7521
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8eb20925618d17b42867a4a2063d98a7
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,362 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>虚拟实验 | {{{ PRODUCT_NAME }}}</title>
<link rel="shortcut icon" href="TemplateData/favicon.ico">
<link rel="stylesheet" href="TemplateData/style.css">
<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>
</head>
<body>
<div id="unity-container" class="unity-desktop">
<canvas id="unity-canvas" width=1280 height=720></canvas>
<div id="unity-loading-bar">
<div id="unity-progress-bar-empty">
<div id="unity-progress-bar-full"></div>
</div>
</div>
<div id="unity-warning"> </div>
<div id="unity-footer">
<div id="unity-fullscreen-button"></div>
<div id="unity-build-title">{{{ PRODUCT_NAME }}}</div>
</div>
</div>
<script>
var container = document.querySelector("#unity-container");
var canvas = document.querySelector("#unity-canvas");
var loadingBar = document.querySelector("#unity-loading-bar");
var progressBarFull = document.querySelector("#unity-progress-bar-full");
var fullscreenButton = document.querySelector("#unity-fullscreen-button");
var warningBanner = document.querySelector("#unity-warning");
// Shows a temporary message banner/ribbon for a few seconds, or
// a permanent error message on top of the canvas if type=='error'.
// If type=='warning', a yellow highlight color is used.
// Modify or remove this function to customize the visually presented
// way that non-critical warnings and error messages are presented to the
// user.
function unityShowBanner(msg, type) {
function updateBannerVisibility() {
warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
}
var div = document.createElement('div');
div.innerHTML = msg;
warningBanner.appendChild(div);
if (type == 'error') div.style = 'background: red; padding: 10px;';
else {
if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
setTimeout(function() {
warningBanner.removeChild(div);
updateBannerVisibility();
}, 5000);
}
updateBannerVisibility();
}
var buildUrl = "Build";
var loaderUrl = buildUrl + "/{{{ LOADER_FILENAME }}}";
var config = {
dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}",
frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}",
codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",
streamingAssetsUrl: "StreamingAssets",
companyName: {{{ JSON.stringify(COMPANY_NAME) }}},
productName: {{{ JSON.stringify(PRODUCT_NAME) }}},
productVersion: {{{ JSON.stringify(PRODUCT_VERSION) }}},
showBanner: unityShowBanner,
};
// By default Unity keeps WebGL canvas render target size matched with
// the DOM size of the canvas element (scaled by window.devicePixelRatio)
// Set this to false if you want to decouple this synchronization from
// happening inside the engine, and you would instead like to size up
// the canvas DOM size and WebGL render target sizes yourself.
// config.matchWebGLToCanvasSize = false;
if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
// Mobile device style: fill the whole browser client area with the game canvas:
var meta = document.createElement('meta');
meta.name = 'viewport';
meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
document.getElementsByTagName('head')[0].appendChild(meta);
container.className = "unity-mobile";
canvas.className = "unity-mobile";
// To lower canvas resolution on mobile devices to gain some
// performance, uncomment the following line:
// config.devicePixelRatio = 1;
unityShowBanner('WebGL builds are not supported on mobile devices.');
} else {
// Desktop style: Render the game canvas in a window that can be maximized to fullscreen:
canvas.style.width = "1280px";
canvas.style.height = "720px";
}
loadingBar.style.display = "block";
var script = document.createElement("script");
script.src = loaderUrl;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
}).catch((message) => {
alert(message);
});
};
var inputObj;
function Test() {
console.log("1");
if (inputObj != null) document.body.removeChild(inputObj);
inputObj = document.createElement('input');
inputObj.setAttribute('id', '_ef');
inputObj.setAttribute('type', 'file');
inputObj.setAttribute("style", 'visibility:hidden');
document.body.appendChild(inputObj);
document.addEventListener('input', imgChange);
var file = document.getElementById("_ef");
file.click();
file.value;
console.log("2");
}
function imgChange(obj) {
console.log("3");
var file = document.getElementById("_ef");
var imgUrl = window.URL.createObjectURL(file.files[0]);
if (instance != null) {
instance.SendMessage("Web", "CallBack", imgUrl);
}
};
//添加功能---------
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 [384, 216];
},
};
function generate(url, reportdata) {
loadFile(
url,
function (error, content) {
if (error) {
throw error;
}
//先处理unity传入的数据得到base64
reportdata = (reportdata.replace(/<(.|\n)*?>/g, '') || ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/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(reportdata);
var out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
compression: "DEFLATE",
});
saveAs(out, "实验报告.docx");
});
}
document.body.appendChild(script);
</script>
</body>
</html>

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1c5560ae5754d7e4ea960b323d4cf91a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,9 @@
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".unityweb" mimeType="application/binary" />
<mimeMap fileExtension=".unity3d" mimeType="application/octet-stream"/>
</staticContent>
<urlCompression doDynamicCompression="false"/>
</system.webServer>
</configuration>

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4d2edd7711614ec49acc9aceb4093b2d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f538532946435d345843369bb394100b
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

BIN
Data/Report/demo.docx Normal file

Binary file not shown.

View File

@ -2,18 +2,17 @@
"dependencies": { "dependencies": {
"com.unity.2d.sprite": "1.0.0", "com.unity.2d.sprite": "1.0.0",
"com.unity.2d.tilemap": "1.0.0", "com.unity.2d.tilemap": "1.0.0",
"com.unity.ai.navigation": "1.1.5",
"com.unity.collab-proxy": "2.2.0", "com.unity.collab-proxy": "2.2.0",
"com.unity.feature.development": "1.0.1", "com.unity.feature.development": "1.0.1",
"com.unity.ide.rider": "3.0.27", "com.unity.ide.rider": "3.0.27",
"com.unity.ide.visualstudio": "2.0.22", "com.unity.ide.visualstudio": "2.0.22",
"com.unity.ide.vscode": "1.2.5", "com.unity.ide.vscode": "1.2.5",
"com.unity.nuget.newtonsoft-json": "3.2.1",
"com.unity.render-pipelines.universal": "14.0.9", "com.unity.render-pipelines.universal": "14.0.9",
"com.unity.test-framework": "1.1.33", "com.unity.test-framework": "1.1.33",
"com.unity.textmeshpro": "3.0.6", "com.unity.textmeshpro": "3.0.6",
"com.unity.timeline": "1.7.6", "com.unity.timeline": "1.7.6",
"com.unity.ugui": "1.0.0", "com.unity.ugui": "1.0.0",
"com.unity.visualscripting": "1.9.1",
"com.unity.xr.legacyinputhelpers": "2.1.10", "com.unity.xr.legacyinputhelpers": "2.1.10",
"com.unity.modules.ai": "1.0.0", "com.unity.modules.ai": "1.0.0",
"com.unity.modules.androidjni": "1.0.0", "com.unity.modules.androidjni": "1.0.0",

View File

@ -15,15 +15,6 @@
"com.unity.modules.uielements": "1.0.0" "com.unity.modules.uielements": "1.0.0"
} }
}, },
"com.unity.ai.navigation": {
"version": "1.1.5",
"depth": 0,
"source": "registry",
"dependencies": {
"com.unity.modules.ai": "1.0.0"
},
"url": "https://packages.unity.cn"
},
"com.unity.burst": { "com.unity.burst": {
"version": "1.8.11", "version": "1.8.11",
"depth": 1, "depth": 1,
@ -100,6 +91,13 @@
"dependencies": {}, "dependencies": {},
"url": "https://packages.unity.cn" "url": "https://packages.unity.cn"
}, },
"com.unity.nuget.newtonsoft-json": {
"version": "3.2.1",
"depth": 0,
"source": "registry",
"dependencies": {},
"url": "https://packages.unity.cn"
},
"com.unity.performance.profile-analyzer": { "com.unity.performance.profile-analyzer": {
"version": "1.2.2", "version": "1.2.2",
"depth": 1, "depth": 1,
@ -212,16 +210,6 @@
"com.unity.modules.imgui": "1.0.0" "com.unity.modules.imgui": "1.0.0"
} }
}, },
"com.unity.visualscripting": {
"version": "1.9.1",
"depth": 0,
"source": "registry",
"dependencies": {
"com.unity.ugui": "1.0.0",
"com.unity.modules.jsonserialize": "1.0.0"
},
"url": "https://packages.unity.cn"
},
"com.unity.xr.legacyinputhelpers": { "com.unity.xr.legacyinputhelpers": {
"version": "2.1.10", "version": "2.1.10",
"depth": 0, "depth": 0,

View File

@ -44,8 +44,8 @@ PlayerSettings:
m_HolographicTrackingLossScreen: {fileID: 0} m_HolographicTrackingLossScreen: {fileID: 0}
defaultScreenWidth: 1920 defaultScreenWidth: 1920
defaultScreenHeight: 1080 defaultScreenHeight: 1080
defaultScreenWidthWeb: 960 defaultScreenWidthWeb: 1280
defaultScreenHeightWeb: 600 defaultScreenHeightWeb: 720
m_StereoRenderingPath: 0 m_StereoRenderingPath: 0
m_ActiveColorSpace: 1 m_ActiveColorSpace: 1
unsupportedMSAAFallback: 0 unsupportedMSAAFallback: 0
@ -819,7 +819,7 @@ PlayerSettings:
webGLDebugSymbols: 0 webGLDebugSymbols: 0
webGLEmscriptenArgs: webGLEmscriptenArgs:
webGLModulesDirectory: webGLModulesDirectory:
webGLTemplate: APPLICATION:Default webGLTemplate: PROJECT:MyIndex
webGLAnalyzeBuildSize: 0 webGLAnalyzeBuildSize: 0
webGLUseEmbeddedResources: 0 webGLUseEmbeddedResources: 0
webGLCompressionFormat: 1 webGLCompressionFormat: 1