Unity本舆图片文件上传服务器(或者数据库),并从服务器(或者数据库)下载+ ...

打印 上一主题 下一主题

主题 511|帖子 511|积分 1533

@TOC
一、媒介

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


  • iTextSharp.dll
  • LitJson.dll
  • sqlite3.dll
  • system.data.dll
  • pdfrenderAPI
  • BestHttp
  • RestClient
相干插件


三、创建PDF,打印PDF

1.导入iTextSharp插件后,在项目中新建一个场景,创建一个按钮和一个脚本TestReport.cs(任意挂在一个物体上即可);并给按钮绑定创建pdf变乱,下方是全部代码。
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. public class TestReport : MonoBehaviour
  6. {
  7.     public Button button;
  8.     private AndroidJavaClass unityPlayerClass;
  9.     private AndroidJavaObject unityActivity;
  10.     private AndroidJavaObject alert;
  11.     string path = Application.streamingAssetsPath + "/test.pdf";
  12.     void Start()
  13.     {
  14.         button.onClick.AddListener(() => { StartCoroutine(CreatPDF()); });
  15.     }
  16.     #region 创建pdf
  17.     /// <summary>
  18.     /// 创建PDF
  19.     /// </summary>
  20.     /// <returns></returns>
  21.     public IEnumerator CreatPDF()
  22.     {
  23.         using (PDFReport pdf = new PDFReport())
  24.         {
  25.             yield return pdf.Init(path);
  26.             pdf.AddTitle("我是测试报告标题",1);//这是标题
  27.             pdf.AddNullLine();//添加空白行
  28.             pdf.AddContent("姓名:测试者           证件号:000000000000000000");
  29.             pdf.AddNullLine();
  30.             pdf.AddContent("测试项目:项目一        测试时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm"));
  31.             pdf.AddNullLine();
  32.             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot1.jpg");
  33.             pdf.AddNullLine();
  34.             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot2.jpg");
  35.             pdf.AddNullLine();
  36.             pdf.AddImage(Application.streamingAssetsPath + @"/Screenshot3.jpg");
  37.         }
  38.         Debug.Log("创建成功打开文件:" + path);
  39.         Application.OpenURL(path);
  40.       
  41.     }
  42.     #endregion
  43.    
  44. }
复制代码
项目场景如图所示:

运行场景如下,可直接毗连打印机打印pdf:

注解:重要脚本PDFReport.cs脚本里包罗了生成pdf的基础设置:字体、样式、标题、添加表格、空行、文本内容、图片等。
  1. using iTextSharp.text;
  2. using iTextSharp.text.pdf;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.IO;
  8. using UnityEngine;
  9. using UnityEngine.Networking;
  10. using Font = iTextSharp.text.Font;
  11. using Image = iTextSharp.text.Image;
  12. public class PDFReport : IDisposable
  13. {
  14.     /// <summary>
  15.     /// 基础字体
  16.     /// </summary>
  17.     BaseFont heiBaseFont;
  18.     /// <summary>
  19.     /// 报告字体样式
  20.     /// </summary>
  21.     public Font titleFont;
  22.     /// <summary>
  23.     /// 大标题字体样式
  24.     /// </summary>
  25.     public Font firstTitleFont;
  26.     /// <summary>
  27.     /// 小标题字体样式
  28.     /// </summary>
  29.     public Font secondTitleFont;
  30.     /// <summary>
  31.     /// 内容字体样式
  32.     /// </summary>
  33.     public Font contentFont;
  34.     /// <summary>
  35.     /// 文档
  36.     /// </summary>
  37.     public Document document;
  38.     /// <summary>
  39.     /// 字体在安卓中的路径
  40.     /// </summary>
  41.     string newFontPath;
  42.     /// <summary>
  43.     /// 拷贝资源到读写路径
  44.     /// </summary>
  45.     /// <param name="Oldpath"></param>
  46.     /// <param name="newPath"></param>
  47.     /// <returns></returns>
  48.     public static IEnumerator CopyOldPathToNewPath(string Oldpath, string newPath)
  49.     {
  50.         if (File.Exists(newPath))
  51.         {
  52.             yield break;
  53.         }
  54.         Uri uri = new Uri(Oldpath);
  55.         using (UnityWebRequest request = UnityWebRequest.Get(uri))
  56.         {
  57.             yield return request.SendWebRequest();
  58.             if (string.IsNullOrEmpty(request.error))
  59.             {
  60.                 yield return File.WriteAllBytesAsync(newPath, request.downloadHandler.data);
  61.             }
  62.             else
  63.             {
  64.                 Debug.LogError(request.error);
  65.             }
  66.         }
  67.     }
  68.     /// <summary>
  69.     /// 初始化
  70.     /// </summary>
  71.     /// <param name="filePath"></param>
  72.     /// <returns></returns>
  73.     public IEnumerator Init(string filePath)
  74.     {
  75.         document = new Document(PageSize.A4);
  76.         string dirPath = Path.GetDirectoryName(filePath);
  77.         Directory.CreateDirectory(dirPath);
  78.         FileStream os = new FileStream(filePath, FileMode.Create);
  79.         PdfWriter.GetInstance(document, os);
  80.         document.Open();
  81.         
  82.         Debug.LogError(document.PageNumber);
  83.         
  84.         string oldPath = Application.streamingAssetsPath + "/SourceHanSansSC-Medium.otf";
  85.         newFontPath = Application.persistentDataPath + "/SourceHanSansSC-Medium.otf";
  86.         yield return CopyOldPathToNewPath(oldPath, newFontPath);
  87.         //创建字体
  88.         heiBaseFont = BaseFont.CreateFont(newFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  89.         titleFont = new Font(heiBaseFont, 26, 1);
  90.         firstTitleFont = new Font(heiBaseFont, 20, 1);
  91.         secondTitleFont = new Font(heiBaseFont, 13, 1);
  92.         contentFont = new Font(heiBaseFont, 11, Font.NORMAL);
  93.     }
  94.     /// <summary>
  95.     /// 添加pdf表格
  96.     /// </summary>
  97.     /// <param name="dt"></param>
  98.     public void AddDataTable(DataTable dt)
  99.     {
  100.         List<float> columns = new List<float>();
  101.         for (int i = 0; i < dt.Columns.Count; i++)
  102.         {
  103.             columns.Add(1);
  104.         }
  105.         AddDataTable(dt, columns.ToArray());
  106.     }
  107.     /// <summary>
  108.     /// 添加pdf表格
  109.     /// </summary>
  110.     /// <param name="dt"></param>
  111.     /// <param name="columnW">列</param>
  112.     public void AddDataTable(DataTable dt, float[] columnW)
  113.     {
  114.         List<string> list = new List<string>();
  115.         for (int i = 0; i < dt.Columns.Count; i++)
  116.         {
  117.             string s = dt.Columns[i].ColumnName;
  118.             list.Add(s);
  119.         }
  120.         //数据 行
  121.         foreach (DataRow row in dt.Rows)
  122.         {
  123.             for (int i = 0; i < dt.Columns.Count; i++)
  124.             {
  125.                 string s = row[i].ToString();
  126.                 list.Add(s);
  127.             }
  128.         }
  129.         AddTable(columnW, list.ToArray());
  130.     }
  131.     /// <summary>
  132.     /// 增加表格
  133.     /// </summary>
  134.     /// <param name="column">列数宽度比例</param>
  135.     /// <param name="content">内容</param>
  136.     public void AddTable(float[] columns, string[] content)
  137.     {
  138.         PdfPTable table = new PdfPTable(columns);
  139.         table.WidthPercentage = 100;
  140.         //table.SetTotalWidth(new float[] {10,10,10,10,10,10,10,20 });
  141.         for (int i = 0; i < content.Length; i++)
  142.         {
  143.             PdfPCell cell = new PdfPCell(new Phrase(content[i], contentFont));
  144.             cell.HorizontalAlignment = Element.ALIGN_CENTER;
  145.             cell.VerticalAlignment = Element.ALIGN_MIDDLE;
  146.             table.AddCell(cell);
  147.         }
  148.         document.Add(table);
  149.     }
  150.     /// <summary>
  151.     /// 空格
  152.     /// 加入空行,用以区分上下行
  153.     /// </summary>
  154.     public void AddNullLine()
  155.     {
  156.         Paragraph nullLine = new Paragraph(" ", secondTitleFont);
  157.         nullLine.Leading = 5;
  158.         document.Add(nullLine);
  159.     }
  160.     /// <summary>
  161.     /// 加入标题
  162.     /// </summary>
  163.     /// <param name="titleStr">标题内容</param>
  164.     /// <param name="font">标题字体,分为一级标题和二级标题</param>
  165.     /// <param name="alignmentType">对齐格式,0为左对齐,1为居中</param>
  166.     public void AddTitle(string titleStr, int alignmentType = 0)
  167.     {
  168.         Paragraph contentP = new Paragraph(new Chunk(titleStr, titleFont));
  169.         contentP.Alignment = alignmentType;
  170.         document.Add(contentP);
  171.     }
  172.     /// <summary>
  173.     /// 插入文字内容
  174.     /// </summary>
  175.     /// <param name="content">内容</param>
  176.     /// <param name="alignmentType">对齐格式,0为左对齐,1为居中</param>
  177.     public void AddContent(string content, int alignmentType = 0)
  178.     {
  179.         Paragraph contentP = new Paragraph(new Chunk(content, contentFont));
  180.         contentP.Alignment = alignmentType;
  181.         document.Add(contentP);
  182.     }
  183.    
  184.     /// <summary>
  185.     /// 插入图片
  186.     /// </summary>
  187.     /// <param name="imagePath"></param>
  188.     /// <param name="scale"></param>
  189.     public void AddImage(string imagePath)
  190.     {
  191.         if (!File.Exists(imagePath))
  192.         {
  193.             Debug.LogWarning("该路径下不存在指定图片,请检测路径是否正确!");
  194.             return;
  195.         }
  196.         iTextSharp.text.Document Doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
  197.         Rectangle defaultPageSize = iTextSharp.text.PageSize.A4;
  198.         // float pageWidth = defaultPageSize.Width - Doc.RightMargin - Doc.LeftMargin;//留白
  199.         // float pageHeight = defaultPageSize.Height - Doc.TopMargin - Doc.BottomMargin;
  200.         
  201.         Image image = Image.GetInstance(imagePath);
  202.         image.ScaleToFit(defaultPageSize.Width,defaultPageSize.Height);
  203.         image.Alignment = Element.ALIGN_JUSTIFIED;
  204.         document.Add(image);
  205.     }
  206.     /// <summary>
  207.     /// 关闭文档
  208.     /// </summary>
  209.     public void Dispose()
  210.     {
  211.         document.Close();
  212.     }
  213. }
复制代码
四、创建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里包罗了数据库的增删改查

代码部分:
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using Mono.Data.Sqlite;
  5. namespace Imdork.SQLite
  6. {
  7.     /// <summary>
  8.     /// SQLite数据库操作类
  9.     /// </summary>
  10.     public class DbAccess : IDisposable
  11.     {
  12.         private SqliteConnection conn; // SQLite连接
  13.         private SqliteCommand cmd; // SQLite命令
  14.         private SqliteDataReader reader;
  15.         /// <summary>
  16.         /// 打开数据库
  17.         /// </summary>
  18.         /// <param name="connectionString"></param>
  19.         public DbAccess(string connectionString)
  20.         {
  21.             OpenDB(connectionString);
  22.         }
  23.         public DbAccess()
  24.         {
  25.         }
  26.         /// <summary>
  27.         /// 打开数据库
  28.         /// </summary>
  29.         /// <param name="connectionString"></param>
  30.         public void OpenDB(string connectionString)
  31.         {
  32.             Debug.Log(connectionString);
  33.             try
  34.             {
  35.                 conn = new SqliteConnection(connectionString);
  36.                 conn.Open();
  37.                 Debug.Log("Connected to db,连接数据库成功!");
  38.             }
  39.             catch (Exception e)
  40.             {
  41.                 string temp1 = e.ToString();
  42.                 Debug.Log("接连库据数败失:" + temp1);
  43.             }
  44.         }
  45.         /// <summary>
  46.         /// 关闭数据库连接
  47.         /// </summary>
  48.         public void CloseSqlConnection()
  49.         {
  50.             if (cmd != null)
  51.             {
  52.                 cmd.Dispose();
  53.                 cmd = null;
  54.             }
  55.             if (reader != null)
  56.             {
  57.                 reader.Dispose();
  58.                 reader = null;
  59.             }
  60.             if (conn != null)
  61.             {
  62.                 conn.Close();
  63.                 conn = null;
  64.             }
  65.             Debug.Log("Disconnected from db.关闭数据库!");
  66.         }
  67.         /// <summary>
  68.         /// 回收资源
  69.         /// </summary>
  70.         public void Dispose()
  71.         {
  72.             CloseSqlConnection();
  73.         }
  74.         /// <summary>
  75.         /// 执行SQL语句 用于Update/Insert/Delete
  76.         /// </summary>
  77.         /// <param name="sqlQuery"></param>
  78.         /// <returns></returns>
  79.         public int ExecuteNonQuery(string sqlQuery)
  80.         {
  81.             Debug.Log("ExecuteNonQuery:: " + sqlQuery);
  82.             cmd = conn.CreateCommand();
  83.             cmd.CommandText = sqlQuery;
  84.             int rows = cmd.ExecuteNonQuery();
  85.             return rows;
  86.         }
  87.         #region 更新数据
  88.         /// <summary>
  89.         /// 更新数据 param tableName=表名  cols=更新字段 colsvalues=更新内容
  90.         /// </summary>
  91.         /// <param name="tableName"></param>
  92.         /// <param name="selectKeys"></param>
  93.         /// <param name="selectValues"></param>
  94.         /// <param name="cols"></param>
  95.         /// <param name="colsValues"></param>
  96.         /// <returns></returns>
  97.         public int UpdateIntoSpecific(string tableName, string[] cols, string[] colsValues)
  98.         {
  99.             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";
  100.             for (int i = 1; i < colsValues.Length; ++i)
  101.             {
  102.                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";
  103.             }
  104.             return ExecuteNonQuery(query);
  105.         }
  106.         /// <summary>
  107.         /// 更新数据 param tableName=表名  selectkey=查找字段(主键) selectvalue=查找内容 cols=更新字段 colsvalues=更新内容
  108.         /// </summary>
  109.         /// <param name="tableName"></param>
  110.         /// <param name="selectKeys"></param>
  111.         /// <param name="selectValues"></param>
  112.         /// <param name="cols"></param>
  113.         /// <param name="colsValues"></param>
  114.         /// <returns></returns>
  115.         public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] selectValues, string[] cols,
  116.             string[] colsValues)
  117.         {
  118.             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";
  119.             for (int i = 1; i < colsValues.Length; ++i)
  120.             {
  121.                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";
  122.             }
  123.             query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";
  124.             for (int i = 1; i < selectKeys.Length; ++i)
  125.             {
  126.                 query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";
  127.             }
  128.             return ExecuteNonQuery(query);
  129.         }
  130.         /// <summary>
  131.         /// 更新数据 param tableName=表名  selectkey=查找字段(主键) operation=判断的符号 selectvalue=查找内容 cols=更新字段 colsvalues=更新内容
  132.         /// </summary>
  133.         /// <param name="tableName"></param>
  134.         /// <param name="selectKeys"></param>
  135.         /// <param name="operation"></param>
  136.         /// <param name="selectValues"></param>
  137.         /// <param name="cols"></param>
  138.         /// <param name="colsValues"></param>
  139.         /// <returns></returns>
  140.         public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] operation, string[] selectValues,
  141.             string[] cols, string[] colsValues)
  142.         {
  143.             string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";
  144.             for (int i = 1; i < colsValues.Length; ++i)
  145.             {
  146.                 query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";
  147.             }
  148.             query += " WHERE " + selectKeys[0] + " " + operation[0] + " " + "'" + selectValues[0] + "' ";
  149.             for (int i = 1; i < selectKeys.Length; ++i)
  150.             {
  151.                 query += " AND " + selectKeys[i] + " " + operation[i] + " " + "'" + selectValues[i] + "' ";
  152.             }
  153.             return ExecuteNonQuery(query);
  154.         }
  155.         #endregion
  156.         #region 插入数据
  157.         #region 插入部分数据
  158.         /// <summary>
  159.         /// 插入部分数据
  160.         /// </summary>
  161.         /// <param name="tableName">表名</param>
  162.         /// <param name="cols">字段名</param>
  163.         /// <param name="values">具体数值</param>
  164.         /// <returns></returns>
  165.         public int InsertIntoSpecific(string tableName, string[] cols, string[] values)
  166.         {
  167.             if (cols.Length != values.Length)
  168.             {
  169.                 throw new Exception("columns.Length != colType.Length");
  170.             }
  171.             string query = "INSERT INTO " + tableName + " (" + cols[0];
  172.             for (int i = 1; i < cols.Length; ++i)
  173.             {
  174.                 query += ", " + cols[i];
  175.             }
  176.             query += ") VALUES (" + "'" + values[0] + "'";
  177.             for (int i = 1; i < values.Length; ++i)
  178.             {
  179.                 query += ", " + "'" + values[i] + "'";
  180.             }
  181.             query += ")";
  182.             return ExecuteNonQuery(query);
  183.         }
  184.         #endregion
  185.         #region 插入一行数据
  186.         /// <summary>
  187.         /// 插入一行数据 param tableName=表名 values=插入数据内容
  188.         /// </summary>
  189.         public int InsertInto(string tableName, string[] values)
  190.         {
  191.             string query = "INSERT INTO " + tableName + " VALUES (" + string.Format("'{0}'", values[0]);
  192.             for (int i = 1; i < values.Length; ++i)
  193.             {
  194.                 query += ", " + string.Format("'{0}'", values[i]);
  195.             }
  196.             query += ")";
  197.             return ExecuteNonQuery(query);
  198.         }
  199.         #endregion
  200.         #endregion
  201.         #region 删除表
  202.         #region 根据条件删除表
  203.         /// <summary>
  204.         /// 删除
  205.         /// </summary>
  206.         /// <param name="tableName">表名</param>
  207.         /// <param name="cols">字段</param>
  208.         /// <param name="colsValues">字段值</param>
  209.         /// <returns></returns>
  210.         public int Delete(string tableName, string[] cols, string[] colsValues)
  211.         {
  212.             string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + "'" + colsValues[0] + "'";
  213.             for (int i = 1; i < colsValues.Length; ++i)
  214.             {
  215.                 query += " and " + cols[i] + " = " + "'" + colsValues[i] + "'";
  216.             }
  217.             return ExecuteNonQuery(query);
  218.         }
  219.         /// <summary>
  220.         /// 删除表
  221.         /// </summary>
  222.         /// <param name="tableName"></param>
  223.         /// <param name="cols"></param>
  224.         /// <param name="operation"></param>
  225.         /// <param name="colsValues"></param>
  226.         /// <returns></returns>
  227.         public int Delete(string tableName, string[] cols, string[] operation, string[] colsValues)
  228.         {
  229.             string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " " + operation[0] + " " + "'" +
  230.                            colsValues[0] + "'";
  231.             for (int i = 1; i < colsValues.Length; ++i)
  232.             {
  233.                 query += " and " + cols[i] + " " + operation[i] + " " + "'" + colsValues[i] + "'";
  234.             }
  235.             return ExecuteNonQuery(query);
  236.         }
  237.         #endregion
  238.         /// <summary>
  239.         /// 删除表中全部数据
  240.         /// </summary>
  241.         public int DeleteContents(string tableName)
  242.         {
  243.             string query = "DELETE FROM " + tableName;
  244.             return ExecuteNonQuery(query);
  245.         }
  246.         #endregion
  247.         #region 创建表
  248.         /// <summary>
  249.         /// 创建表 param name=表名 col=字段名 colType=字段类型
  250.         /// </summary>
  251.         public int CreateTable(string name, string[] col, string[] colType)
  252.         {
  253.             if (col.Length != colType.Length)
  254.             {
  255.                 throw new SqliteException("columns.Length != colType.Length");
  256.             }
  257.             string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
  258.             for (int i = 1; i < col.Length; ++i)
  259.             {
  260.                 query += ", " + col[i] + " " + colType[i];
  261.             }
  262.             query += ")";
  263.             return ExecuteNonQuery(query);
  264.         }
  265.         #endregion
  266.         #region 查询表
  267.         #region 按条件查询全部数据
  268.         /// <summary>
  269.         /// 按条件查询全部数据 param tableName=表名  col=查找字段 operation=运算符 values=内容
  270.         /// </summary>
  271.         public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] operation, string[] values)
  272.         {
  273.             if (col.Length != operation.Length || operation.Length != values.Length)
  274.             {
  275.                 throw new SqliteException("col.Length != operation.Length != values.Length");
  276.             }
  277.             string query = "SELECT *";
  278.             query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
  279.             for (int i = 1; i < col.Length; ++i)
  280.             {
  281.                 query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";
  282.             }
  283.             return ExecuteQuery(query);
  284.         }
  285.         /// <summary>
  286.         /// 按条件查询全部数据 param tableName=表名 col=查找字段  values=内容
  287.         /// </summary>
  288.         public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] values)
  289.         {
  290.             if (col.Length != values.Length)
  291.             {
  292.                 throw new SqliteException("col.Length != values.Length");
  293.             }
  294.             string query = "SELECT *";
  295.             query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";
  296.             for (int i = 1; i < col.Length; ++i)
  297.             {
  298.                 query += " AND " + col[i] + "=" + "'" + values[i] + "' ";
  299.             }
  300.             return ExecuteQuery(query);
  301.         }
  302.         #endregion
  303.         #region 按条件查询数据
  304.         /// <summary>
  305.         /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容
  306.         /// </summary>
  307.         public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] operation,
  308.             string[] values)
  309.         {
  310.             if (col.Length != operation.Length || operation.Length != values.Length)
  311.             {
  312.                 throw new SqliteException("col.Length != operation.Length != values.Length");
  313.             }
  314.             string query = "SELECT " + items[0];
  315.             for (int i = 1; i < items.Length; ++i)
  316.             {
  317.                 query += ", " + items[i];
  318.             }
  319.             query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
  320.             for (int i = 1; i < col.Length; ++i)
  321.             {
  322.                 query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";
  323.             }
  324.             return ExecuteQuery(query);
  325.         }
  326.         /// <summary>
  327.         /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段  values=内容
  328.         /// </summary>
  329.         public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] values)
  330.         {
  331.             if (col.Length != values.Length)
  332.             {
  333.                 throw new SqliteException("col.Length != values.Length");
  334.             }
  335.             string query = "SELECT " + items[0];
  336.             for (int i = 1; i < items.Length; ++i)
  337.             {
  338.                 query += ", " + items[i];
  339.             }
  340.             query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";
  341.             for (int i = 1; i < col.Length; ++i)
  342.             {
  343.                 query += " AND " + col[i] + "=" + "'" + values[i] + "' ";
  344.             }
  345.             return ExecuteQuery(query);
  346.         }
  347.         #endregion
  348.         #region 按条件查询 单个字段数据
  349.         /// <summary>
  350.         ///  查询表
  351.         /// </summary>
  352.         /// <param name="tableName">表名</param>
  353.         /// <param name="col">查找字段</param>
  354.         /// <param name="operation">运算符</param>
  355.         /// <param name="values">内容</param>
  356.         /// <returns></returns>
  357.         public SqliteDataReader Select(string tableName, string col, string operation, string values)
  358.         {
  359.             string query = "SELECT * FROM " + tableName + " WHERE " + col + " " + operation + " " +
  360.                            string.Format("'{0}'", values);
  361.             return ExecuteQuery(query);
  362.         }
  363.         /// <summary>
  364.         /// 查询表
  365.         /// </summary>
  366.         /// <param name="tableName">表名</param>
  367.         /// <param name="col">查找字段</param>
  368.         /// <param name="values">内容</param>
  369.         /// <returns></returns>
  370.         public SqliteDataReader Select(string tableName, string col, string values)
  371.         {
  372.             string query = "SELECT * FROM " + tableName + " WHERE " + col + " = " + string.Format("'{0}'", values);
  373.             return ExecuteQuery(query);
  374.         }
  375.         #endregion
  376.         #region 升序查询/降序查询/查询表行数/查询表全部数据
  377.         /// <summary>
  378.         /// 升序查询
  379.         /// </summary>
  380.         public SqliteDataReader SelectOrderASC(string tableName, string col)
  381.         {
  382.             string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " ASC";
  383.             return ExecuteQuery(query);
  384.         }
  385.         /// <summary>
  386.         /// 降序查询
  387.         /// </summary>
  388.         public SqliteDataReader SelectOrderDESC(string tableName, string col)
  389.         {
  390.             string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " DESC";
  391.             return ExecuteQuery(query);
  392.         }
  393.         /// <summary>
  394.         /// 查询表行数
  395.         /// </summary>
  396.         public SqliteDataReader SelectCount(string tableName)
  397.         {
  398.             string query = "SELECT COUNT(*) FROM " + tableName;
  399.             return ExecuteQuery(query);
  400.         }
  401.         /// <summary>
  402.         /// 查询表中全部数据 param tableName=表名
  403.         /// </summary>
  404.         public SqliteDataReader ReadFullTable(string tableName)
  405.         {
  406.             string query = "SELECT * FROM " + tableName;
  407.             return ExecuteQuery(query);
  408.         }
  409.         #endregion
  410.         /// <summary>
  411.         /// 执行SQL语句 用于SelectWhere查询语句
  412.         /// </summary>
  413.         /// <param name="sqlQuery"></param>
  414.         /// <returns></returns>
  415.         public SqliteDataReader ExecuteQuery(string sqlQuery)
  416.         {
  417.             Debug.Log("ExecuteQuery:: " + sqlQuery);
  418.             cmd = conn.CreateCommand();
  419.             cmd.CommandText = sqlQuery;
  420.             try
  421.             {
  422.                 reader = cmd.ExecuteReader();
  423.             }
  424.             catch (Exception e)
  425.             {
  426.                 Debug.LogError(e);
  427.                 return null;
  428.             }
  429.             return reader;
  430.         }
  431.         #endregion
  432.     }
  433. }
复制代码
2.屏幕截图,获取图片的base64字节流

3.将pdf文件转成base64字节流插入数据库

4.完备代码如下:
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Threading.Tasks;
  6. using Cysharp.Threading.Tasks;
  7. using Imdork.SQLite;
  8. using Manager;
  9. using Tool;
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12. public class SQLiteManager : MonoSingleton<SQLiteManager>
  13. {
  14.     #region 数据基本设置
  15.     /// <summary>
  16.     /// 数据库名称
  17.     /// </summary>
  18.     [Header("数据库名称")] public string UseTableName = "UseTable";
  19.     /// <summary>
  20.     /// 数据库路径
  21.     /// </summary>
  22.     private string UseTablePath;
  23.     [HideInInspector] public List<DataBase> dataList;
  24.     /// <summary>
  25.     /// 打印层相机
  26.     /// </summary>
  27.     public Camera printCamera;
  28.     /// <summary>
  29.     /// 所有图片更新GO
  30.     /// </summary>
  31.     public List<GameObject> AllTables;
  32.     /// <summary>
  33.     /// 截图路径
  34.     /// </summary>
  35.     string _path = Application.streamingAssetsPath + "/PrintImage/Screenshot";
  36.     string pathPDF = Application.streamingAssetsPath + @"\test.pdf"; //要打印的目标图片
  37.     private List<string> allImagePath;
  38.     private Coroutine _CreatPDF;
  39.     private GameObject curGO;
  40.     Rect rect;
  41.     RenderTexture rt;
  42.     void Awake()
  43.     {
  44.         rect = new Rect(0, 0, 1920, 1080);
  45.         rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
  46.         UseTablePath = "Data Source = " + Application.streamingAssetsPath + "/" + UseTableName;
  47.     }
  48.     public void Start()
  49.     {
  50.         for (int i = 0; i < AllTables.Count; i++)
  51.         {
  52.             AllTables[i].SetActive(false);
  53.         }
  54.         ToInsertData();
  55.     }
  56.     void ToInsertData()
  57.     {
  58.         DataBase curDataBase = new DataBase();
  59.         curDataBase.ProjectName = "我是测试项目";
  60.         curDataBase.UserName = "测试";
  61.         curDataBase.UserID = "000000000000000000";
  62.         curDataBase.Time = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm");
  63.         PrintImage(curDataBase);
  64.     }
  65.     /// <summary>
  66.     /// 读取配置文件  账号登录
  67.     /// </summary>
  68.     /// <param name="path"></param>
  69.     /// <param name="callBack"></param>
  70.     /// <returns></returns>
  71.     private bool ReadData(string path, Action<string> callBack)
  72.     {
  73.         if (!File.Exists(path))
  74.         {
  75.             return false;
  76.         }
  77.         var str = File.ReadAllText(path);
  78.         callBack?.Invoke(str);
  79.         return true;
  80.     }
  81.     #endregion
  82.     #region 用户信息表格
  83.     /// <summary>
  84.     /// 获取当前用户的所有信息
  85.     /// </summary>
  86.     public void GetAllUseData()
  87.     {
  88.         GetDB(db =>
  89.         {
  90.             var reader = db.ReadFullTable("UserData");
  91.             List<DataBase> _userDatas = SQLiteUtility.GetDataValues(reader);
  92.             dataList.Clear();
  93.             if (_userDatas != null)
  94.             {
  95.                 for (int i = 0; i < _userDatas.Count; i++)
  96.                 {
  97.                     if (_userDatas[i].UserID == "000000000000000000")
  98.                     {
  99.                         dataList.Add(_userDatas[i]);
  100.                     }
  101.                 }
  102.             }
  103.         });
  104.     }
  105.     /// <summary>
  106.     /// 插入当前患者数据
  107.     /// </summary>
  108.     /// <param name="curUserData"></param>
  109.     public void InsertUserData(DataBase curUserData)
  110.     {
  111.         GetDB(db =>
  112.         {
  113.             db.InsertInto("UserData", GetSingleUserData(curUserData));
  114.             if (_CreatPDF != null) StopCoroutine(_CreatPDF);
  115.         });
  116.     }
  117.     /// <summary>
  118.     /// 将单个userdata数据拼接成字符串  按照数据库表顺序
  119.     /// </summary>
  120.     /// <param name="curUserData"></param>
  121.     /// <returns></returns>
  122.     String[] GetSingleUserData(DataBase curUserData)
  123.     {
  124.         List<string> strList = new List<string>();
  125.         strList.Add(curUserData.UserName);
  126.         strList.Add(curUserData.UserID);
  127.         strList.Add(curUserData.ProjectName);
  128.         strList.Add(curUserData.Time);
  129.         strList.Add(curUserData.PrintImage);
  130.         return strList.ToArray();
  131.     }
  132.     #endregion
  133.     /// <summary>
  134.     /// 调用数据库
  135.     /// </summary>
  136.     /// <param name="action"></param>
  137.     public void GetDB(Action<DbAccess> action)
  138.     {
  139.         //Path数据库文件,一定是StreamingAssets文件夹下 填写的路径文件不需要填写.db后缀
  140.         //创建数据库读取类
  141.         SQLiteHelper helper = new SQLiteHelper(UseTablePath);
  142.         //打开数据库 存储数据库操作类
  143.         using (var db = helper.Open())
  144.         {
  145.             //调用数据库委托
  146.             action(db);
  147.         }
  148.         /*
  149.          因为每次使用数据 添/删/改/查 都需要使用完后Close掉
  150.          重复代码,写无数次太麻烦 因为数据库操作类 继承了IDisposable接口 所以,
  151.          using会自动关闭数据库连接,我们无需手动关闭数据库
  152.          */
  153.     }
  154.     private void OnDestroy()
  155.     {
  156.         GetDB(db => db.Dispose());
  157.     }
  158.     #region 截图  打印
  159.     /// <summary>
  160.     /// 截图
  161.     /// </summary>
  162.     public async void PrintImage(DataBase _dataBase)
  163.     {
  164.         Debug.LogError(_dataBase.ProjectName);
  165.         for (int i = 0; i < AllTables.Count; i++)
  166.         {
  167.             Debug.LogError(AllTables[i].name);
  168.             if (_dataBase.ProjectName.Contains(AllTables[i].name))
  169.             {
  170.                 AllTables[i].SetActive(true);
  171.                 curGO = AllTables[i];
  172.             }
  173.             else
  174.             {
  175.                 AllTables[i].SetActive(false);
  176.             }
  177.         }
  178.         allImagePath = new List<string>();
  179.         Debug.LogError(curGO.transform.childCount);
  180.         for (int i = 0; i < curGO.transform.childCount; i++)
  181.         {
  182.             allImagePath.Add(_path + i + ".png");
  183.             ScreenTool(_path + i + ".png");
  184.             await Task.Delay(500);
  185.             curGO.transform.GetChild(i).gameObject.SetActive(false);
  186.         }
  187.         _CreatPDF = StartCoroutine(CreatPDF(_dataBase));
  188.     }
  189.     /// <summary>
  190.     /// 截图
  191.     /// </summary>
  192.     /// <param name="path"></param>
  193.     async void ScreenTool(string path)
  194.     {
  195.         printCamera.targetTexture = rt;
  196.         printCamera.Render();
  197.         RenderTexture.active = rt;
  198.         Texture2D _screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGBA32, false);
  199.         _screenShot.ReadPixels(rect, 0, 0);
  200.         _screenShot.Apply();
  201.         await UniTask.Yield(PlayerLoopTiming.LastPostLateUpdate);
  202.         printCamera.targetTexture = null;
  203.         RenderTexture.active = null;
  204.         var bytes = _screenShot.EncodeToPNG();
  205.         await File.WriteAllBytesAsync(path, bytes);
  206.         Debug.LogError($"截屏了一张照片: {path}");
  207.     }
  208.     /// <summary>
  209.     /// 创建pdf
  210.     /// </summary>
  211.     /// <param name="_dataBase"></param>
  212.     /// <returns></returns>
  213.     public IEnumerator CreatPDF(DataBase _dataBase)
  214.     {
  215.         using (PDFReport pdf = new PDFReport())
  216.         {
  217.             yield return pdf.Init(pathPDF);
  218.             for (int i = 0; i < allImagePath.Count; i++)
  219.             {
  220.                 pdf.AddImage(allImagePath[i]);
  221.             }
  222.         }
  223.         yield return new WaitForSeconds(0.2f);
  224.         string strBase = System.Convert.ToBase64String(File.ReadAllBytes(pathPDF));
  225.         _dataBase.PrintImage = strBase;
  226.         InsertUserData(_dataBase);
  227.         Debug.Log("创建成功打开文件:" + pathPDF);
  228.     }
  229.     #endregion
  230. }
复制代码
五、将本舆图片文件上传至服务器,服务器返回一个图片文件下载地点,通过下载地点下载对应的图片文件

注解:在这里必要一个配景服务器用来储存文件地点并返回下载地点,所以在此直接做成一个工具类,调用接口直接传服务器请求URL和本地文件路径:
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using UnityEngine;
  6. public static class HttpTool
  7. {
  8.     /// <summary>
  9.     /// Http上传文件
  10.     /// </summary>
  11.     /// <param name="url">服务器地址</param>
  12.     /// <param name="path">文件路径</param>
  13.     /// <returns>服务器返回的文件下载地址</returns>
  14.     public static string HttpUploadFile(string url, string path)
  15.     {
  16.         HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  17.         CookieContainer cookieContainer = new CookieContainer();
  18.         request.CookieContainer = cookieContainer;
  19.         request.AllowAutoRedirect = true;
  20.         request.Method = "POST";
  21.         string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
  22.         request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
  23.         byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
  24.         byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
  25.         int pos = path.LastIndexOf("\");
  26.         string fileName = path.Substring(pos + 1);
  27.         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));
  28.         byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
  29.         FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
  30.         byte[] bArr = new byte[fs.Length];
  31.         fs.Read(bArr, 0, bArr.Length);
  32.         fs.Close();
  33.         Stream postStream = request.GetRequestStream();
  34.         postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
  35.         postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  36.         postStream.Write(bArr, 0, bArr.Length);
  37.         postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  38.         postStream.Close();
  39.         HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  40.         Stream instream = response.GetResponseStream();
  41.         StreamReader sr = new StreamReader(instream, Encoding.UTF8);
  42.         string content = sr.ReadToEnd();
  43.         DataShellStr _data = JsonUtility.FromJson<DataShellStr>(content);//这里需要序列化,获取后台返回的文件下载地址
  44.         Debug.Log(content);
  45.         return _data.data;
  46.     }
  47.    
  48. }
复制代码
PS:附带一个博主网络请求常用的方法:RestClient插件,请求失败2秒后继续请求

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

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

风雨同行

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表