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
请大家自行测试