当前位置: 首页 > web >正文

unity使用iTextSharp生成PDF文件

iTextSharp 可以在VS中工具下面得NuGet包管理器中下载 ,具体操作可以搜一下 很多 ,
我直接把我得生成pdf代码附上 我这个是生成我一个csv文件内容和图片

using System.IO;
using UnityEngine;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Text;
using Font = iTextSharp.text.Font;
using Image = iTextSharp.text.Image;
using UnityEngine.Networking;
using System.Collections;
public class PDFGenerator : MonoBehaviour
{public string reportTitle = "Unity 报告";public Text printSuccessText;private BaseFont chineseBaseFont;// 在Awake或Start中预加载字体private IEnumerator Start(){yield return StartCoroutine(LoadChineseFont());}private IEnumerator LoadChineseFont(){// 关键:注册编码提供程序Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);// 1. 优先尝试使用内置字体try{chineseBaseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);Debug.Log("成功加载内置字体 STSong-Light");yield break;}catch (System.Exception e){Debug.LogWarning($"内置字体加载失败: {e.Message}");}// 2. 尝试从StreamingAssets加载字体string fontPath = Path.Combine(Application.streamingAssetsPath, "SIMFANG.TTF");Debug.Log("尝试加载字体路径: " + fontPath);// 处理不同平台的路径
#if UNITY_STANDALONE_WIN || UNITY_EDITOR// Windows平台特殊处理if (File.Exists(fontPath)){try{// 添加额外的编码参数chineseBaseFont = BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H,BaseFont.EMBEDDED,true, // 强制缓存null, // 字体数据null, // 字体度量true, // 强制读取true); // 缓存到文件Debug.Log("成功从文件系统加载字体: " + fontPath);yield break;}catch (System.Exception e){Debug.LogError($"Windows平台字体加载失败: {e.Message}\n{e.StackTrace}");}}else{Debug.LogWarning($"字体文件不存在: {fontPath}");}
#elif UNITY_ANDROID && !UNITY_EDITOR// Android平台特殊处理string url = "jar:file://" + Application.dataPath + "!/assets/SIMFANG.TTF";using (UnityWebRequest www = UnityWebRequest.Get(url)){yield return www.SendWebRequest();if (www.result == UnityWebRequest.Result.Success){byte[] fontData = www.downloadHandler.data;try{chineseBaseFont = BaseFont.CreateFont("SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, false, fontData, null);Debug.Log("成功从Android资源加载字体");yield break;}catch (System.Exception e){Debug.LogError($"Android字体加载失败: {e.Message}\n{e.StackTrace}");}}else{Debug.LogError($"无法加载Android字体文件: {www.error}");}}
#elif UNITY_IOS && !UNITY_EDITOR// iOS平台特殊处理if (File.Exists(fontPath)){try{chineseBaseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);Debug.Log("成功从iOS资源加载字体");yield break;}catch (System.Exception e){Debug.LogError($"iOS字体加载失败: {e.Message}\n{e.StackTrace}");}}
#endif// 3. 最后尝试使用系统字体try{chineseBaseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);Debug.LogWarning("使用默认系统字体(可能不支持中文)");}catch (System.Exception e){Debug.LogError($"系统字体加载失败: {e.Message}");chineseBaseFont = null;}}public void GeneratePDF(string pdfName, string csvFilePath, string imageFolderPath, string outputFolderPath){if (chineseBaseFont == null){Debug.LogError("字体未加载完成,无法生成PDF");return;}Document document = new Document();if (!Directory.Exists(outputFolderPath)){Directory.CreateDirectory(outputFolderPath);}string pdfPath = Path.Combine(outputFolderPath, pdfName + ".pdf");try{PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));document.Open();// 使用预加载的字体iTextSharp.text.Font chineseFont = new iTextSharp.text.Font(chineseBaseFont, 12);// 添加标题document.Add(new Paragraph(reportTitle, chineseFont) { Alignment = Element.ALIGN_CENTER });document.Add(new Paragraph(" ", chineseFont));// 添加表格内容PdfPTable table = CreatePdfTable(csvFilePath, chineseFont);document.Add(table);document.Add(new Paragraph(" ", chineseFont));// 添加图片AddImagesToPdf(document, imageFolderPath);document.Close();if (printSuccessText != null){printSuccessText.text = $"PDF生成成功: {pdfPath}";printSuccessText.gameObject.SetActive(true);}}catch (System.Exception e){Debug.LogError($"PDF生成失败: {e.Message}\n{e.StackTrace}");if (printSuccessText != null){printSuccessText.text = $"PDF生成失败: {e.Message}";printSuccessText.gameObject.SetActive(true);}}}private PdfPTable CreatePdfTable(string csvFilePath, Font font){List<string[]> csvData = ReadCSVFile(csvFilePath);if (csvData.Count == 0) return new PdfPTable(1);PdfPTable table = new PdfPTable(csvData[0].Length);table.WidthPercentage = 100;foreach (var row in csvData){foreach (string cellValue in row){table.AddCell(new PdfPCell(new Phrase(cellValue, font)));}}return table;}private void AddImagesToPdf(Document document, string imageFolderPath){if (!Directory.Exists(imageFolderPath)) return;foreach (string imageFile in Directory.GetFiles(imageFolderPath, "*.png")){try{Image image = Image.GetInstance(imageFile);image.ScaleToFit(document.PageSize.Width - 40, document.PageSize.Height - 40);image.Alignment = Element.ALIGN_CENTER;document.Add(image);document.Add(new Paragraph(" "));}catch (System.Exception e){Debug.LogError($"添加图片 {imageFile} 到 PDF 失败: {e.Message}");}}}private List<string[]> ReadCSVFile(string filePath){List<string[]> data = new List<string[]>();try{using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8)){while (!reader.EndOfStream)data.Add(reader.ReadLine().Split(','));}}catch (System.Exception e){Debug.LogError($"读取CSV文件失败: {e.Message}");}return data;}
}

这个时候在编辑器运行是没错 但是打包出来就会出问题PDF中不显示中文
还需要 找到Unity编辑器的安装路径
例如:2019.4.34f1c1\Editor\Data\MonoBleedingEdge\lib\mono\unityjit找到以下dll
I18N.CJK.dll 、I18N.dll、I18N.MidEast.dll
I18N.Other.dll、I18N.Rare.dll、I18N.West.dll
这些文件 我是放在了打包出来exe同级文件夹里面成功得, 也有人是放在XXXX_Data\Managed
请大家自行测试

http://www.xdnf.cn/news/1523.html

相关文章:

  • AI时代的能力重构与终身进化
  • 1.1 java开发的准备工作(入门)
  • day4 pandas学习
  • Java面试场景篇:MCP使用场景与实现详解
  • 【⼆分查找】⼆分查找(easy)
  • RBAC权限-笔记
  • mybatis高级查询:一对多配置,一次性查出主表和子表中的数据
  • 《楞严经》中“魔”与魔王波旬的关联性分析
  • 《系统分析师-第三阶段—总结(五)》
  • 【Java学习】Windows安装Noj4库及java集成详细步骤
  • 夏季跑步注意
  • IP地址与子网掩码
  • 问题:raw.githubusercontent无法访问
  • 【Redis】哈希类型Hash 常用命令详解
  • 【白雪讲堂】GEO优化第6篇 内容中台的搭建:GEO优化的中控神经系统
  • 【Java学习日记25】:带返回值的方法
  • Vue生命周期详细解析
  • 第1节:Backtrader到底是个啥?能干嘛?
  • python安装toad
  • Vue3 模板语法
  • 第三章:File Storage Backend
  • JavaScript 改变this指向
  • 在 JavaScript 中,`call`、`bind` 和 `apply`区别
  • QT容器类控件及其属性
  • Python高级爬虫之JS逆向+安卓逆向1.6节: 函数基础
  • 如何使用LangChain调用Ollama部署的模型?
  • 厚铜PCB制造中的散热结构工艺控制要点
  • python:mido 提取 midi文件中某一音轨的音乐数据
  • Java 加密与解密:从算法到应用的全面解析
  • Vue3速通笔记