The method of creating PDF in Unity

foreword

Recently, the project has a need to realize the pdf of learning records generated in unity, and encountered many problems. Later, I changed to a simple method to achieve it.

1. ITextSharp implementation

I won’t introduce much about ITextSharp, it’s very convenient to use, but in unity, there will be no problem in the editor, and the imported package fails to load the font and cannot be used. At first, it was the reason for internationalization, and it was solved later. , It is very troublesome, here is the usage, dll download link here: https://pan.baidu.com/s/1PBItHlwNI-t4aIWwb9JH7w, extraction code: y79a
, after downloading, drag it into the unity Asserts folder.
The two internationalized files can also be found in your unity installation package, the following path
Insert the picture description here
Storage path
Use the code directly, remember to import the ItextSharp namespace

 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();

Generate effects, other usage methods can find a lot of relevant information:
insert image description here

2. PdfSharp implementation

PdfSharp is also a component that can generate PDF. It is generally realized by drawing, a bit like drawing in python.
Download dll:
Link: https://pan.baidu.com/s/1OnDxwIP3WglOwlpvzlpK9Q
Extraction code: knkv
directly the code

    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);
        }
    }

When implementing it in unity, an error will always be reported. It should be my version problem. If you have solved it, you can tell me
insert image description here

3. Combination of NPOI and Aspose.Words

NPOI is a class library for processing and reading excel, Word and other formats. It is very convenient to use. Aspose.Words is a class library for processing word documents. Note: Aspose has to be used for a fee, and there will be a watermark if there is no charge.
My idea is to first create a doc document with NPOI, and then use Aspose to convert it to pdf. After importing the package, confirm that Chinese can be displayed.
Well... yes, convert to pdf. There are two reasons for this consideration
: 1. My data volume Not much, just one or two pages.
2. Many times, there is no problem in the unity editor mode, but there are a lot of problems after importing the package, especially the Chinese language is not displayed. Just do this.
After having this idea, the same Drag in the dll, Aspose in the link is the learning version
Link: https://pan.baidu.com/s/1T9tYOtbDQ_Al958FB73y_A
Extraction code: v8dd
Directly upload the code:


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);

    }
}

Guess you like

Origin blog.csdn.net/qq_14942529/article/details/124398376