unity利用ITextSharp实现导出pdf文件

本文档详细介绍了如何在Unity中利用iTextSharp库创建PDF文件,包括设置环境、导入dll、创建字体、添加表格、文本和图片。通过示例代码展示了从数据表生成PDF表格的实现过程,并提供了测试结果,适用于PC和Android平台,但不支持WebGL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unity创建pdf文件首先需要搭建ITextSharp环境,先要导入所需要的dll文件。选用vs创建一个控制台项目,然后点击工具-包管理器-管理解决方案的Nuget程序包选项,如图所示:

 打开包管理器后,搜索ITextSharp并安装此包。

 安装完毕后,点击生成-生成(项目名),即可生成dll文件,在项目路径下bin\Debug中找到itextsharp.dll,BouncyCastle.Crypto.dll导入到unity中。这时基本就能使用itextsharp了,但是只是编辑器运行正常,打包后还是会报错。这时还需要导入另外一个dll文件。

打开unity安装目录,我这里使用的版本是unity2022.1,找到Editor\Data\MonoBleedingEdge\lib\mono文件夹。再打开文件夹unityaot-win32或者unityjit-win32也行,找到I18N.West.dll,I18N.dll这两个个文件并导入到unity。除此之外要确保api兼容级别设置成.NET Framework而不是.NET Standard2.1。设置方法是点击菜单编辑-项目设置-玩家-api兼容级别。如图所示:这样就搭建好环境了。为了能够支持中文,我们需要自己导入一个字体文件在StreamingAssets中,为了支持安卓,需要把这个字体文件拷贝到可读写路径下面。我这里创建了一个PDFReport类来方便调用创建文件具体代码如下:

 

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 拷贝资源到读写路径(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 初始化(string filePath)
    {
        document = new Document(PageSize.A4);
        string dirPath = Path.GetDirectoryName(filePath);
        Directory.CreateDirectory(dirPath);
        //为该Document创建一个Writer实例:
        FileStream os = new FileStream(filePath, FileMode.Create);
        PdfWriter.GetInstance(document, os);
        //打开文档
        document.Open();
        string oldPath = Application.streamingAssetsPath + "/SourceHanSansSC-Medium.otf";
        newFontPath = Application.persistentDataPath  + "/SourceHanSansSC-Medium.otf";
        yield return 拷贝资源到读写路径(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);
    }

    public void 添加PDF表格(DataTable dt)
    {
        List<float> columns = new List<float>();
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            columns.Add(1);
        }
        添加PDF表格(dt, columns.ToArray());
    }
    public void  添加PDF表格(DataTable dt, float[] columnW)
    {

        List<string> list = new List<string>();
        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());
    }
    /// <summary>
    /// 增加表格
    /// </summary>
    /// <param name="column">列数宽度比例</param>
    /// <param name="content">内容</param>
    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);
    }


    /// <summary>
    /// 空格
    /// 加入空行,用以区分上下行
    /// </summary>
    public void AddNullLine()
    {
        Paragraph nullLine = new Paragraph(" ",secondTitleFont);
        nullLine.Leading = 5;
        document.Add(nullLine); 
    }

    /// <summary>
    /// 加入标题
    /// </summary>
    /// <param name="titleStr">标题内容</param>
    /// <param name="font">标题字体,分为一级标题和二级标题</param>
    /// <param name="alignmentType">对齐格式,0为左对齐,1为居中</param>
    public void AddTitle(string titleStr, int alignmentType = 0)
    {
        Paragraph contentP = new Paragraph(new Chunk(titleStr, titleFont));
        contentP.Alignment = alignmentType;
        document.Add(contentP);
    }

    /// <summary>
    /// 插入文字内容
    /// </summary>
    /// <param name="content">内容</param>
    /// <param name="alignmentType">对齐格式,0为左对齐,1为居中</param>
    public void AddContent(string content, int alignmentType = 0)
    {
        Paragraph contentP = new Paragraph(new Chunk(content, contentFont));
        contentP.Alignment = alignmentType;
        document.Add(contentP);
    }

    /// <summary>
    /// 插入图片
    /// </summary>
    /// <param name="imagePath"></param>
    /// <param name="scale"></param>
    public void AddImage(string imagePath,int width = 475,int height =325)
    {
        if (!File.Exists(imagePath))
        {
            Debug.LogWarning("该路径下不存在指定图片,请检测路径是否正确!");
            return;
        }
        Image image = Image.GetInstance(imagePath);
        image.ScaleToFit(width, height);
        image.Alignment = Element.ALIGN_JUSTIFIED;
        document.Add(image);
    }

    /// <summary>
    /// 关闭文档
    /// </summary>
    public void Dispose()
    {
        document.Close();
    }
}


以上代码可以添加pdf表格文本图片等功能。具体调用方法如下:

 void Start()
    {
        button.onClick.AddListener(() => { StartCoroutine(创建Pdf()); });
    }
   
    public IEnumerator 创建Pdf()
    {
        
        string[] Columns = new string[] { "编号", "名称", "产品", "系列2222222222222222222222222222222", "建筑面积", "用漆量", "数量", "详情" };
        DataTable dt = new DataTable();
        foreach (string item in Columns)
        {
            dt.Columns.Add(item);
        }
        for (int i = 0; i < 20; i++)
        {
            DataRow dr = dt.NewRow();
            object[] objs = { 999, "这是名称", "这是产品", "系列门窗",
                "建筑面积6666", "用漆量111", "数量33.3333", "详情啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊" };
            dr.ItemArray = objs;
            dt.Rows.Add(dr);
        }
        string path = Application.persistentDataPath + "/test.pdf";
        using (PDFReport pdf = new PDFReport())
        {
            yield return pdf.初始化(path);
            pdf.AddTitle("这是标题");
            pdf.AddContent("这是表格内容");
            pdf.添加PDF表格(dt);
        }
        Debug.Log("创建成功打开文件:" + path);
        Application.OpenURL(path);
    }

经过测试打包pc,安卓都能正常生成pdf文件。但是不支持webgl,不确定是否支持ios。实例项目下载地址:unity导出pdf文件-Unity3D文档类资源-CSDN下载

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值