Unity本地图片文件上传服务器(或者数据库),并从服务器(或者数据库)下载+图片生成PDF并保存到数据库+SQLite数据库增删改查
创始人
2025-01-19 23:03:23
0

@TOC

一、前言

最近博主用以前的小功能总是搬来扒去,感觉。。。
正好汇总一下,以后再用直接扒博客,下面是博主整理的一些功能点:sqlite数据库(包含增删改查),本地图片上传下载(数据库或者服务器),图片生成pdf(插入表格、标题等等),pdf上传数据库并下载等。。。。。。最后附上项目源码,希望对广大网友有所帮助。

二、插件附上(源码中获得即可)

  1. iTextSharp.dll
  2. LitJson.dll
  3. sqlite3.dll
  4. system.data.dll
  5. pdfrenderAPI
  6. BestHttp
  7. RestClient

相关插件

相关插件

三、创建PDF,打印PDF

1.导入iTextSharp插件后,在项目中新建一个场景,创建一个按钮和一个脚本TestReport.cs(随便挂在一个物体上即可);并给按钮绑定创建pdf事件,下方是全部代码。

using System; using System.Collections; using UnityEngine; using UnityEngine.UI;  public class TestReport : MonoBehaviour {     public Button button;     private AndroidJavaClass unityPlayerClass;     private AndroidJavaObject unityActivity;     private AndroidJavaObject alert;     string path = Application.streamingAssetsPath + "/test.pdf";      void Start()     {         button.onClick.AddListener(() => { StartCoroutine(CreatPDF()); });     }      #region 创建pdf      ///      /// 创建PDF     ///      ///      public IEnumerator CreatPDF()     {         using (PDFReport pdf = new PDFReport())         {             yield return pdf.Init(path);             pdf.AddTitle("我是测试报告标题",1);//这是标题             pdf.AddNullLine();//添加空白行             pdf.AddContent("姓名:测试者           证件号:000000000000000000");             pdf.AddNullLine();             pdf.AddContent("测试项目:项目一        测试时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm"));             pdf.AddNullLine();             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot1.jpg");             pdf.AddNullLine();             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot2.jpg");             pdf.AddNullLine();             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot3.jpg");         }          Debug.Log("创建成功打开文件:" + path);         Application.OpenURL(path);             }      #endregion     } 

项目场景如图所示:
创建按钮,添加脚本
运行场景如下,可直接连接打印机打印pdf:
生成的pdf文件
注解:主要脚本PDFReport.cs脚本里包含了生成pdf的基础设置:字体、样式、标题、添加表格、空行、文本内容、图片等。

using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using UnityEngine; using UnityEngine.Networking; using Font = iTextSharp.text.Font; using Image = iTextSharp.text.Image;  public class PDFReport : IDisposable {     ///      /// 基础字体     ///      BaseFont heiBaseFont;      ///      /// 报告字体样式     ///      public Font titleFont;      ///      /// 大标题字体样式     ///      public Font firstTitleFont;      ///      /// 小标题字体样式     ///      public Font secondTitleFont;      ///      /// 内容字体样式     ///      public Font contentFont;      ///      /// 文档     ///      public Document document;      ///      /// 字体在安卓中的路径     ///      string newFontPath;      ///      /// 拷贝资源到读写路径     ///      ///      ///      ///      public static IEnumerator CopyOldPathToNewPath(string Oldpath, string newPath)     {         if (File.Exists(newPath))         {             yield break;         }          Uri uri = new Uri(Oldpath);         using (UnityWebRequest request = UnityWebRequest.Get(uri))         {             yield return request.SendWebRequest();             if (string.IsNullOrEmpty(request.error))             {                 yield return File.WriteAllBytesAsync(newPath, request.downloadHandler.data);             }             else             {                 Debug.LogError(request.error);             }         }     }      ///      /// 初始化     ///      ///      ///      public IEnumerator Init(string filePath)     {         document = new Document(PageSize.A4);         string dirPath = Path.GetDirectoryName(filePath);         Directory.CreateDirectory(dirPath);         FileStream os = new FileStream(filePath, FileMode.Create);         PdfWriter.GetInstance(document, os);         document.Open();                  Debug.LogError(document.PageNumber);                  string oldPath = Application.streamingAssetsPath + "/SourceHanSansSC-Medium.otf";         newFontPath = Application.persistentDataPath + "/SourceHanSansSC-Medium.otf";         yield return CopyOldPathToNewPath(oldPath, newFontPath);         //创建字体         heiBaseFont = BaseFont.CreateFont(newFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);         titleFont = new Font(heiBaseFont, 26, 1);         firstTitleFont = new Font(heiBaseFont, 20, 1);         secondTitleFont = new Font(heiBaseFont, 13, 1);         contentFont = new Font(heiBaseFont, 11, Font.NORMAL);     }      ///      /// 添加pdf表格     ///      ///      public void AddDataTable(DataTable dt)     {         List columns = new List();         for (int i = 0; i < dt.Columns.Count; i++)         {             columns.Add(1);         }          AddDataTable(dt, columns.ToArray());     }      ///      /// 添加pdf表格     ///      ///      /// 列     public void AddDataTable(DataTable dt, float[] columnW)     {         List list = new List();         for (int i = 0; i < dt.Columns.Count; i++)         {             string s = dt.Columns[i].ColumnName;             list.Add(s);         }          //数据 行         foreach (DataRow row in dt.Rows)         {             for (int i = 0; i < dt.Columns.Count; i++)             {                 string s = row[i].ToString();                 list.Add(s);             }         }          AddTable(columnW, list.ToArray());     }      ///      /// 增加表格     ///      /// 列数宽度比例     /// 内容     public void AddTable(float[] columns, string[] content)     {         PdfPTable table = new PdfPTable(columns);         table.WidthPercentage = 100;         //table.SetTotalWidth(new float[] {10,10,10,10,10,10,10,20 });         for (int i = 0; i < content.Length; i++)         {             PdfPCell cell = new PdfPCell(new Phrase(content[i], contentFont));             cell.HorizontalAlignment = Element.ALIGN_CENTER;             cell.VerticalAlignment = Element.ALIGN_MIDDLE;              table.AddCell(cell);         }          document.Add(table);     }       ///      /// 空格     /// 加入空行,用以区分上下行     ///      public void AddNullLine()     {         Paragraph nullLine = new Paragraph(" ", secondTitleFont);         nullLine.Leading = 5;         document.Add(nullLine);     }      ///      /// 加入标题     ///      /// 标题内容     /// 标题字体,分为一级标题和二级标题     /// 对齐格式,0为左对齐,1为居中     public void AddTitle(string titleStr, int alignmentType = 0)     {         Paragraph contentP = new Paragraph(new Chunk(titleStr, titleFont));         contentP.Alignment = alignmentType;         document.Add(contentP);     }      ///      /// 插入文字内容     ///      /// 内容     /// 对齐格式,0为左对齐,1为居中     public void AddContent(string content, int alignmentType = 0)     {         Paragraph contentP = new Paragraph(new Chunk(content, contentFont));         contentP.Alignment = alignmentType;         document.Add(contentP);     }           ///      /// 插入图片     ///      ///      ///      public void AddImage(string imagePath)     {         if (!File.Exists(imagePath))         {             Debug.LogWarning("该路径下不存在指定图片,请检测路径是否正确!");             return;         }         iTextSharp.text.Document Doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);         Rectangle defaultPageSize = iTextSharp.text.PageSize.A4;         // float pageWidth = defaultPageSize.Width - Doc.RightMargin - Doc.LeftMargin;//留白         // float pageHeight = defaultPageSize.Height - Doc.TopMargin - Doc.BottomMargin;                  Image image = Image.GetInstance(imagePath);         image.ScaleToFit(defaultPageSize.Width,defaultPageSize.Height);         image.Alignment = Element.ALIGN_JUSTIFIED;         document.Add(image);     }      ///      /// 关闭文档     ///      public void Dispose()     {         document.Close();     } } 

四、创建sqlite数据库,截取屏幕图片生成PDF,并将PDF并保存至数据库

1.新建一个场景,创建脚本SQLiteManager.cs,挂在一个空物体上
2.在StreamingAssets文件夹里创建UseTable.db数据库
3.SQLiteStudio下载安装步骤:这位博主写的很详细,请参考安装即可
[https://blog.csdn.net/m0_37149062/article/details/135138080]
4.部分原理:
1.在UseTable.db中创建表行和列,如下图所示,脚本DbAccess.cs里包含了数据库的增删改查
在这里插入图片描述
代码部分:

using UnityEngine; using System; using System.Collections; using Mono.Data.Sqlite;  namespace Imdork.SQLite {     ///      /// SQLite数据库操作类     ///      public class DbAccess : IDisposable     {         private SqliteConnection conn; // SQLite连接         private SqliteCommand cmd; // SQLite命令         private SqliteDataReader reader;          ///          /// 打开数据库         ///          ///          public DbAccess(string connectionString)         {             OpenDB(connectionString);         }          public DbAccess()         {         }          ///          /// 打开数据库         ///          ///          public void OpenDB(string connectionString)         {             Debug.Log(connectionString);             try             {                 conn = new SqliteConnection(connectionString);                 conn.Open();                 Debug.Log("Connected to db,连接数据库成功!");             }             catch (Exception e)             {                 string temp1 = e.ToString();                 Debug.Log("接连库据数败失:" + temp1);             }         }          ///          /// 关闭数据库连接         ///          public void CloseSqlConnection()         {             if (cmd != null)             {                 cmd.Dispose();                 cmd = null;             }              if (reader != null)             {                 reader.Dispose();                 reader = null;             }              if (conn != null)             {                 conn.Close();                 conn = null;             }              Debug.Log("Disconnected from db.关闭数据库!");         }          ///          /// 回收资源         ///          public void Dispose()         {             CloseSqlConnection();         }          ///          /// 执行SQL语句 用于Update/Insert/Delete         ///          ///          ///          public int ExecuteNonQuery(string sqlQuery)         {             Debug.Log("ExecuteNonQuery:: " + sqlQuery);             cmd = conn.CreateCommand();             cmd.CommandText = sqlQuery;             int rows = cmd.ExecuteNonQuery();             return rows;         }           #region 更新数据          ///          /// 更新数据 param tableName=表名  cols=更新字段 colsvalues=更新内容         ///          ///          ///          ///          ///          ///          ///          public int UpdateIntoSpecific(string tableName, string[] cols, string[] colsValues)         {             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";             }              return ExecuteNonQuery(query);         }          ///          /// 更新数据 param tableName=表名  selectkey=查找字段(主键) selectvalue=查找内容 cols=更新字段 colsvalues=更新内容         ///          ///          ///          ///          ///          ///          ///          public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] selectValues, string[] cols,             string[] colsValues)         {             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";             }              query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";             for (int i = 1; i < selectKeys.Length; ++i)             {                 query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";             }              return ExecuteNonQuery(query);         }          ///          /// 更新数据 param tableName=表名  selectkey=查找字段(主键) operation=判断的符号 selectvalue=查找内容 cols=更新字段 colsvalues=更新内容         ///          ///          ///          ///          ///          ///          ///          ///          public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] operation, string[] selectValues,             string[] cols, string[] colsValues)         {             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";             }              query += " WHERE " + selectKeys[0] + " " + operation[0] + " " + "'" + selectValues[0] + "' ";             for (int i = 1; i < selectKeys.Length; ++i)             {                 query += " AND " + selectKeys[i] + " " + operation[i] + " " + "'" + selectValues[i] + "' ";             }              return ExecuteNonQuery(query);         }          #endregion          #region 插入数据          #region 插入部分数据          ///          /// 插入部分数据         ///          /// 表名         /// 字段名         /// 具体数值         ///          public int InsertIntoSpecific(string tableName, string[] cols, string[] values)         {             if (cols.Length != values.Length)             {                 throw new Exception("columns.Length != colType.Length");             }              string query = "INSERT INTO " + tableName + " (" + cols[0];             for (int i = 1; i < cols.Length; ++i)             {                 query += ", " + cols[i];             }              query += ") VALUES (" + "'" + values[0] + "'";             for (int i = 1; i < values.Length; ++i)             {                 query += ", " + "'" + values[i] + "'";             }              query += ")";             return ExecuteNonQuery(query);         }          #endregion          #region 插入一行数据          ///          /// 插入一行数据 param tableName=表名 values=插入数据内容         ///          public int InsertInto(string tableName, string[] values)         {             string query = "INSERT INTO " + tableName + " VALUES (" + string.Format("'{0}'", values[0]);             for (int i = 1; i < values.Length; ++i)             {                 query += ", " + string.Format("'{0}'", values[i]);             }              query += ")";             return ExecuteNonQuery(query);         }          #endregion          #endregion          #region 删除表          #region 根据条件删除表          ///          /// 删除         ///          /// 表名         /// 字段         /// 字段值         ///          public int Delete(string tableName, string[] cols, string[] colsValues)         {             string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + "'" + colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += " and " + cols[i] + " = " + "'" + colsValues[i] + "'";             }              return ExecuteNonQuery(query);         }          ///          /// 删除表         ///          ///          ///          ///          ///          ///          public int Delete(string tableName, string[] cols, string[] operation, string[] colsValues)         {             string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " " + operation[0] + " " + "'" +                            colsValues[0] + "'";              for (int i = 1; i < colsValues.Length; ++i)             {                 query += " and " + cols[i] + " " + operation[i] + " " + "'" + colsValues[i] + "'";             }              return ExecuteNonQuery(query);         }          #endregion          ///           /// 删除表中全部数据         ///          public int DeleteContents(string tableName)         {             string query = "DELETE FROM " + tableName;             return ExecuteNonQuery(query);         }          #endregion          #region 创建表          ///          /// 创建表 param name=表名 col=字段名 colType=字段类型         ///          public int CreateTable(string name, string[] col, string[] colType)         {             if (col.Length != colType.Length)             {                 throw new SqliteException("columns.Length != colType.Length");             }              string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];             for (int i = 1; i < col.Length; ++i)             {                 query += ", " + col[i] + " " + colType[i];             }              query += ")";             return ExecuteNonQuery(query);         }          #endregion          #region 查询表          #region 按条件查询全部数据          ///          /// 按条件查询全部数据 param tableName=表名  col=查找字段 operation=运算符 values=内容         ///          public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] operation, string[] values)         {             if (col.Length != operation.Length || operation.Length != values.Length)             {                 throw new SqliteException("col.Length != operation.Length != values.Length");             }              string query = "SELECT *";              query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          ///          /// 按条件查询全部数据 param tableName=表名 col=查找字段  values=内容         ///          public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] values)         {             if (col.Length != values.Length)             {                 throw new SqliteException("col.Length != values.Length");             }              string query = "SELECT *";             query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + "=" + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          #endregion          #region 按条件查询数据          ///          /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容         ///          public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] operation,             string[] values)         {             if (col.Length != operation.Length || operation.Length != values.Length)             {                 throw new SqliteException("col.Length != operation.Length != values.Length");             }              string query = "SELECT " + items[0];             for (int i = 1; i < items.Length; ++i)             {                 query += ", " + items[i];             }              query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          ///          /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段  values=内容         ///          public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] values)         {             if (col.Length != values.Length)             {                 throw new SqliteException("col.Length != values.Length");             }              string query = "SELECT " + items[0];             for (int i = 1; i < items.Length; ++i)             {                 query += ", " + items[i];             }              query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";             for (int i = 1; i < col.Length; ++i)             {                 query += " AND " + col[i] + "=" + "'" + values[i] + "' ";             }              return ExecuteQuery(query);         }          #endregion          #region 按条件查询 单个字段数据          ///          ///  查询表         ///          /// 表名         /// 查找字段         /// 运算符         /// 内容         ///          public SqliteDataReader Select(string tableName, string col, string operation, string values)         {             string query = "SELECT * FROM " + tableName + " WHERE " + col + " " + operation + " " +                            string.Format("'{0}'", values);             return ExecuteQuery(query);         }          ///          /// 查询表         ///          /// 表名         /// 查找字段         /// 内容         ///          public SqliteDataReader Select(string tableName, string col, string values)         {             string query = "SELECT * FROM " + tableName + " WHERE " + col + " = " + string.Format("'{0}'", values);             return ExecuteQuery(query);         }          #endregion          #region 升序查询/降序查询/查询表行数/查询表全部数据          ///          /// 升序查询         ///          public SqliteDataReader SelectOrderASC(string tableName, string col)         {             string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " ASC";             return ExecuteQuery(query);         }          ///          /// 降序查询         ///          public SqliteDataReader SelectOrderDESC(string tableName, string col)         {             string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " DESC";             return ExecuteQuery(query);         }          ///          /// 查询表行数         ///          public SqliteDataReader SelectCount(string tableName)         {             string query = "SELECT COUNT(*) FROM " + tableName;             return ExecuteQuery(query);         }          ///          /// 查询表中全部数据 param tableName=表名          ///          public SqliteDataReader ReadFullTable(string tableName)         {             string query = "SELECT * FROM " + tableName;             return ExecuteQuery(query);         }          #endregion          ///          /// 执行SQL语句 用于SelectWhere查询语句         ///          ///          ///          public SqliteDataReader ExecuteQuery(string sqlQuery)         {             Debug.Log("ExecuteQuery:: " + sqlQuery);             cmd = conn.CreateCommand();             cmd.CommandText = sqlQuery;             try             {                 reader = cmd.ExecuteReader();             }             catch (Exception e)             {                  Debug.LogError(e);                 return null;             }              return reader;         }          #endregion     } }  

2.屏幕截图,获取图片的base64字节流
在这里插入图片描述
3.将pdf文件转成base64字节流插入数据库
在这里插入图片描述
4.完整代码如下:

using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using Imdork.SQLite; using Manager; using Tool; using UnityEngine; using UnityEngine.UI;  public class SQLiteManager : MonoSingleton {     #region 数据基本设置      ///      /// 数据库名称     ///      [Header("数据库名称")] public string UseTableName = "UseTable";      ///      /// 数据库路径     ///      private string UseTablePath;      [HideInInspector] public List dataList;      ///      /// 打印层相机     ///      public Camera printCamera;      ///      /// 所有图片更新GO     ///      public List AllTables;      ///      /// 截图路径     ///      string _path = Application.streamingAssetsPath + "/PrintImage/Screenshot";      string pathPDF = Application.streamingAssetsPath + @"\test.pdf"; //要打印的目标图片      private List allImagePath;      private Coroutine _CreatPDF;     private GameObject curGO;     Rect rect;     RenderTexture rt;      void Awake()     {         rect = new Rect(0, 0, 1920, 1080);         rt = new RenderTexture((int)rect.width, (int)rect.height, 0);         UseTablePath = "Data Source = " + Application.streamingAssetsPath + "/" + UseTableName;     }      public void Start()     {         for (int i = 0; i < AllTables.Count; i++)         {             AllTables[i].SetActive(false);         }          ToInsertData();     }      void ToInsertData()     {         DataBase curDataBase = new DataBase();         curDataBase.ProjectName = "我是测试项目";         curDataBase.UserName = "测试";         curDataBase.UserID = "000000000000000000";         curDataBase.Time = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm");         PrintImage(curDataBase);     }      ///      /// 读取配置文件  账号登录     ///      ///      ///      ///      private bool ReadData(string path, Action callBack)     {         if (!File.Exists(path))         {             return false;         }          var str = File.ReadAllText(path);         callBack?.Invoke(str);         return true;     }      #endregion      #region 用户信息表格      ///      /// 获取当前用户的所有信息     ///      public void GetAllUseData()     {         GetDB(db =>         {             var reader = db.ReadFullTable("UserData");              List _userDatas = SQLiteUtility.GetDataValues(reader);             dataList.Clear();             if (_userDatas != null)             {                 for (int i = 0; i < _userDatas.Count; i++)                 {                     if (_userDatas[i].UserID == "000000000000000000")                     {                         dataList.Add(_userDatas[i]);                     }                 }             }         });     }      ///      /// 插入当前患者数据     ///      ///      public void InsertUserData(DataBase curUserData)     {         GetDB(db =>         {             db.InsertInto("UserData", GetSingleUserData(curUserData));             if (_CreatPDF != null) StopCoroutine(_CreatPDF);         });     }      ///      /// 将单个userdata数据拼接成字符串  按照数据库表顺序     ///      ///      ///      String[] GetSingleUserData(DataBase curUserData)     {         List strList = new List();          strList.Add(curUserData.UserName);         strList.Add(curUserData.UserID);         strList.Add(curUserData.ProjectName);         strList.Add(curUserData.Time);         strList.Add(curUserData.PrintImage);          return strList.ToArray();     }      #endregion       ///      /// 调用数据库     ///      ///      public void GetDB(Action action)     {         //Path数据库文件,一定是StreamingAssets文件夹下 填写的路径文件不需要填写.db后缀         //创建数据库读取类         SQLiteHelper helper = new SQLiteHelper(UseTablePath);         //打开数据库 存储数据库操作类         using (var db = helper.Open())         {             //调用数据库委托             action(db);         }         /*          因为每次使用数据 添/删/改/查 都需要使用完后Close掉          重复代码,写无数次太麻烦 因为数据库操作类 继承了IDisposable接口 所以,          using会自动关闭数据库连接,我们无需手动关闭数据库          */     }       private void OnDestroy()     {         GetDB(db => db.Dispose());     }      #region 截图  打印      ///      /// 截图     ///      public async void PrintImage(DataBase _dataBase)     {         Debug.LogError(_dataBase.ProjectName);         for (int i = 0; i < AllTables.Count; i++)         {             Debug.LogError(AllTables[i].name);             if (_dataBase.ProjectName.Contains(AllTables[i].name))             {                 AllTables[i].SetActive(true);                 curGO = AllTables[i];             }             else             {                 AllTables[i].SetActive(false);             }         }          allImagePath = new List();         Debug.LogError(curGO.transform.childCount);         for (int i = 0; i < curGO.transform.childCount; i++)         {             allImagePath.Add(_path + i + ".png");             ScreenTool(_path + i + ".png");             await Task.Delay(500);             curGO.transform.GetChild(i).gameObject.SetActive(false);         }          _CreatPDF = StartCoroutine(CreatPDF(_dataBase));     }      ///      /// 截图     ///      ///      async void ScreenTool(string path)     {         printCamera.targetTexture = rt;         printCamera.Render();         RenderTexture.active = rt;         Texture2D _screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false);         _screenShot.ReadPixels(rect, 0, 0);         _screenShot.Apply();         await UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate);         printCamera.targetTexture = null;         RenderTexture.active = null;         var bytes = _screenShot.EncodeToPNG();         await File.WriteAllBytesAsync(path, bytes);         Debug.LogError($"截屏了一张照片: {path}");     }      ///      /// 创建pdf     ///      ///      ///      public IEnumerator CreatPDF(DataBase _dataBase)     {         using (PDFReport pdf = new PDFReport())         {             yield return pdf.Init(pathPDF);             for (int i = 0; i < allImagePath.Count; i++)             {                 pdf.AddImage(allImagePath[i]);             }         }          yield return new WaitForSeconds(0.2f);         string strBase = System.Convert.ToBase64String(File.ReadAllBytes(pathPDF));         _dataBase.PrintImage = strBase;         InsertUserData(_dataBase);         Debug.Log("创建成功打开文件:" + pathPDF);     }      #endregion } 

五、将本地图片文件上传至服务器,服务器返回一个图片文件下载地址,通过下载地址下载对应的图片文件

注解:在这里需要一个后台服务器用来储存文件地址并返回下载地址,所以在此直接做成一个工具类,调用接口直接传服务器请求URL和本地文件路径:

using System; using System.IO; using System.Net; using System.Text; using UnityEngine;  public static class HttpTool {     ///      /// Http上传文件     ///      /// 服务器地址     /// 文件路径     /// 服务器返回的文件下载地址     public static string HttpUploadFile(string url, string path)     {         HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;         CookieContainer cookieContainer = new CookieContainer();         request.CookieContainer = cookieContainer;         request.AllowAutoRedirect = true;         request.Method = "POST";         string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线         request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;         byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");         byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");         int pos = path.LastIndexOf("\\");         string fileName = path.Substring(pos + 1);          StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));         byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());          FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);         byte[] bArr = new byte[fs.Length];         fs.Read(bArr, 0, bArr.Length);         fs.Close();          Stream postStream = request.GetRequestStream();         postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);         postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);         postStream.Write(bArr, 0, bArr.Length);         postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);         postStream.Close();         HttpWebResponse response = request.GetResponse() as HttpWebResponse;         Stream instream = response.GetResponseStream();         StreamReader sr = new StreamReader(instream, Encoding.UTF8);         string content = sr.ReadToEnd();         DataShellStr _data = JsonUtility.FromJson(content);//这里需要序列化,获取后台返回的文件下载地址         Debug.Log(content);         return _data.data;     }      }  

PS:附带一个博主网络请求常用的方法:RestClient插件,请求失败2秒后继续请求
在这里插入图片描述

项目源码,包含相关插件和完整代码。希望能够帮到你,别忘记点赞+收藏哦,谢谢。。。

[百度网盘地址]
链接:https://pan.baidu.com/s/1-xcJEBgONxLhxenLnT95RQ
提取码:6666
–来自百度网盘超级会员V6的分享

相关内容

热门资讯

透视数据!德普之星辅助器怎么用... 透视数据!德普之星辅助器怎么用(透视)透视(有挂插件)1、进入到德普之星辅助器怎么用黑科技之后,能看...
透视肯定!aapoker怎么设... 透视肯定!aapoker怎么设置提高好牌几率(透视)aapoker辅助软件合法吗,透视教程(有挂细节...
透视插件“智星德州插件最新版本... 透视插件“智星德州插件最新版本更新内容详解”wepoker安装教程(透视)科技教程(果然是真的有挂)...
透视存在!德普之星私人局透视(... 透视存在!德普之星私人局透视(透视)辅助器app(有挂脚本);德普之星私人局透视软件透明挂微扑克wp...
透视透视挂!aapoker辅助... 透视透视挂!aapoker辅助工具安全吗(透视)aapoker ai插件,2025新版技巧(有挂介绍...
透视代打“哈糖大菠萝怎么挂”哈... 透视代打“哈糖大菠萝怎么挂”哈糖大菠萝有挂吗(透视)曝光教程(都是是真的有挂);1、金币登录送、破产...
透视总结!德普之星app安卓版... 透视总结!德普之星app安卓版破解版(透视)透视软件免费入口官网(有挂工具);1、进入到德普之星ap...
透视科技!aapoker辅助软... 透视科技!aapoker辅助软件合法吗(透视)aapoker辅助器是真的吗,微扑克教程(有挂脚本)一...
辅助透视“德州透视是真的吗”w... 辅助透视“德州透视是真的吗”werplan免费挂下载(透视)介绍教程(其实有挂);1、很好的工具软件...
透视科技!德普之星透视辅助软件... 透视科技!德普之星透视辅助软件下载(透视)透视免费(有挂插件)一、德普之星透视辅助软件下载软件透明挂...