Unity中创建PDF的方法

25 篇文章 10 订阅
2 篇文章 0 订阅

前言

最近项目有需求要实现unity内生成学习记录的pdf,遇到不少问题,后面换了种简单的手段实现

1.ITextSharp实现

关于ITextSharp我就不多介绍了,使用起来很方便,但是在unity里面会出现编辑器内没问题,导包出来加载字体失败不能用的情况,一开始是国际化的原因,后面解决了还有,很是困扰,这里介绍一下用法,dll下载在这里链接:https://pan.baidu.com/s/1PBItHlwNI-t4aIWwb9JH7w ,提取码:y79a
,下载完了之后拖入unity Asserts文件夹。
两个国际化的文件也可以在你的unity安装包里找到,如下路径
在这里插入图片描述
存储路径
直接上使用代码,记得引入ItextSharp命名空间

 Document document = new Document();
 string currenttime = DateTime.Now.Year.ToString() + "年" + DateTime.Now.Month.ToString() + "月" + DateTime.Now.Day.ToString() + "日" + DateTime.Now.Hour.ToString() + "点" + DateTime.Now.Minute.ToString() + "分" + DateTime.Now.Second.ToString() + "秒";
 PdfWriter.GetInstance(document, new FileStream(GetStudyPath()  +"/"+currenttime+ "学习记录.pdf", FileMode.Create));
document.Open();
//这里的字体选择一个路径就可以,我这里是直接把字体放进unity streamingAssets文件夹然后加载
string titlefontpath = Application.streamingAssetsPath + "/arlishugbmd_test.ttf";
BaseFont bf1 = BaseFont.CreateFont(titlefontpath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font fonttitle = new iTextSharp.text.Font(bf1, 20);
Paragraph chinesePa2 = new Paragraph("hello123你好", fonttitle);
document.Add(chinesePa2);
document.Close();

生成效果,其他使用方法可以找到很多相关资料:
在这里插入图片描述

2.PdfSharp实现

PdfSharp也是一个可以生成PDF的组件,它一般是通过绘制的形式来实现,有点像python里面的画图
一样下载dll:
链接:https://pan.baidu.com/s/1OnDxwIP3WglOwlpvzlpK9Q
提取码:knkv
直接上代码

    private void PdfConvert()
    {
        try
        {
            PdfDocument document = new PdfDocument();
            PdfPage page = document.AddPage();
            XGraphics gfx = XGraphics.FromPdfPage(page);
            //XFont font = new XFont("黑体", 20, XFontStyle.Bold);
            XFont font = new XFont("黑体", 20, XFontStyle.Bold);
            gfx.DrawString("个人信息表", font, XBrushes.Black, new XRect(0, 50, (float)page.Width, (float)page.Height), XStringFormats.TopCenter);
            var tbw = (page.Width - 100) / 5;
            XPen pen1 = new XPen(XColor.FromKnownColor(XKnownColor.Black), 0.1);
            gfx.DrawLine(pen1, 50, 100, page.Width - 50, 100);

            string titlefontpath = Application.streamingAssetsPath + "学习记录.pdf";


            document.Save(titlefontpath);

        }
        catch (Exception ex)
        {

            print(ex.Message);
        }
    }

在unity里实现时,老是会报一个错,应该是我版本问题,解决了的老兄可以跟我说一下
在这里插入图片描述

3.NPOI和Aspose.Words组合使用

NPOI是用于处理和读取excel、Word等格式的一种类库,用起来很方便,Aspose.Words是用来处理word文档的类库,注意:Aspose要收费使用,不收费会有水印。
我的思路是,先用NPOI创建一个doc文档,然后使用Aspose转成pdf,导包之后确认中文是可以显示的
嗯…没错,转pdf,这样考虑的原因有两点
1.我的数据量不多,就一两页
2.很多时候在unity编辑器模式下没问题,但在导包之后问题一大堆,特别是中文不显示,干脆这样做算了
有了这种思路之后,一样的拖入dll,链接里面Aspose为学习版
链接:https://pan.baidu.com/s/1T9tYOtbDQ_Al958FB73y_A
提取码:v8dd
直接上代码:


using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using NPOI.XWPF.UserModel;
using System.IO;
using Aspose.Cells;
using Aspose.Words.Saving;
using NPOI.OpenXmlFormats.Wordprocessing;
public class TestData : MonoBehaviour
{
    public Text messText;
    /// <summary>
    /// 文件路径
    /// </summary>
    private  string filePath = Application.streamingAssetsPath;

    /// <summary>
    /// 文件名称
    /// </summary>
    private string fileName = "david.docx";

    private string path;

    /// <summary>
    /// word文档
    /// </summary>
    private XWPFDocument doc = new XWPFDocument();

    private void Start()
    {
        //缝合路径
        path = Path.Combine(filePath, fileName);
        CreateParagraph(ParagraphAlignment.CENTER, 20, "red", "你好");
        Word2PDF(path, Application.streamingAssetsPath+"/123.pdf");
    }



    // Update is called once per frame
    void Update()
    {
        
    }

    /// <summary>
    /// 创建段落
    /// </summary>
    /// <param name="_alignment">对齐方式</param>
    /// <param name="_fontSize">字体大小</param>
    /// <param name="_color">字体颜色(16进制)</param>
    /// <param name="_content">内容</param>
    private void CreateParagraph(ParagraphAlignment _alignment, int _fontSize,
        string _color, string _content)
    {
        XWPFParagraph paragraph = doc.CreateParagraph();
        paragraph.Alignment = _alignment;
        XWPFRun run = paragraph.CreateRun();
        run.FontSize = _fontSize;
        run.SetColor(_color);
        run.FontFamily = "宋体";
        run.SetText(_content);
        var table = doc.CreateTable(15, 6);
        table.Width =10000 ;

        var para = new CT_P();
        var pCell = new XWPFParagraph(para, table.Body);
        pCell.Alignment = ParagraphAlignment.CENTER; //字体居中
        pCell.VerticalAlignment = NPOI.XWPF.UserModel.TextAlignment.CENTER; //字体居中

        var r1c1 = pCell.CreateRun();
        r1c1.SetText("你好");
        r1c1.FontSize = 11;
        r1c1.SetFontFamily("宋体", FontCharRange.None); //设置雅黑字体
        pCell.SpacingAfterLines = 40;
        pCell.SpacingBeforeLines = 40;
        //放入单元格
        table.GetRow(4).GetCell(1).SetParagraph(pCell);

        FileStream fs = new FileStream(path, FileMode.Create);
        doc.Write(fs);
        fs.Close();
        fs.Dispose();
        File.SetAttributes(path, FileAttributes.ReadOnly);
        Debug.Log("写入成功");
    }
    public void Word2PDF(string srcDocPath, string dstPdfPath)
    {
        // Load the document from disk.
    Aspose.Words.Document srcDoc = new Aspose.Words.Document(srcDocPath);
        // Save the document in PDF format.
        srcDoc.Save(dstPdfPath,Aspose.Words.SaveFormat.Pdf);

    }
}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ToDoNothing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值