自学内容网 自学内容网

Unity使用iTextSharp导出PDF-02基础结构及设置中文字体

基础结构

1.创建一个Document对象
2.使用PdfWriter创建PDF文档
3.打开文档
4.添加内容,调用文档Add方法添加内容时,内容写入到输出流中
5.关闭文档

using UnityEngine;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
using System;
//项目文件夹中生成一份pdf
public class PDFStructSample : MonoBehaviour
{
    void Start()
    {
        PDFStruct($"Pdf{DateTime.Now.ToString("yyyyMMddHHmmss")}.pdf");
    }

    void PDFStruct(string fileName)
    {
        //基础结构
        using (Document doc = new Document())//自动调用doc.Close()方法
        {
            try
            {
                //创建pdf文档
                PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create));       
                //打开pdf文档
                doc.Open();
                //pdf中显示一行文字:Hello PDF!
                doc.Add(new Paragraph("Hello PDF!"));
            }
            catch (IOException e)
            {
                Debug.Log("IO异常" + e.Message);
            }
            catch (DocumentException e)
            {
                Debug.Log("文档异常" + e.Message);
            }
        }
    }
}

设置pdf页面属性

页面大小,背景颜色,页边距。
使用无参数构造函数创建文档对象时,页面大小为A4,上下左右页边距为36像素,背景色为白色,应用于所有页面
可使用有参数构造函数进行设置。
例如:Document doc = new Document(PageSize.A4, 40f, 40f, 36f, 36f);
参数1是内置的页面,类型为Rectangle,根据需要可创建对象,自定义页面。
Rectangle可设置页面大小,背景颜色。
页面尺寸单位是像素,页面默认dpi是72,1英寸=72像素,1英寸=2.54厘米

设置中文字体

iTextSharp默认使用的是英文字体,没有中文字体。
开源字体:思源黑体体ttf格式,可在Github上查找
Pal3love/Source-Han-TrueType

  1. 加载字体,创建BaseFont
  2. 创建Font对象
  3. 创建文本对象的时候可设置字体
  4. Font对象可设置字体颜色,风格,大小等属性。

StreamingAssetsPath文件夹存放了思源字体Bold
依据文件路径,创建BaseFont对象,创建Font对象
BaseFont.CreateFont(boldFontFilePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
参数1:字体路径
参数2:字体编码,IDENTITY_H表示横向文字,使用Unicode编码。
参数3:字体嵌入PDF中,避免电脑不存在该字体。

    string FontDirectory => UnityEngine.Application.streamingAssetsPath + "/Fonts/";
    string boldFontFilePath => FontDirectory + "SourceHanSansCN-Bold.ttf";

    BaseFont boldBaseFont;
    BaseFont BoldBaseFont
    {
        get
        {
            if (boldBaseFont == null)
                boldBaseFont = BaseFont.CreateFont(boldFontFilePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            return boldBaseFont;
        }
    }

    Font boldFont;
    Font BoldFont
    {
        get
        {
            if (boldFont == null)               
                boldFont = new Font(BoldBaseFont, 10.5f);             
            return boldFont;
        }
    }

原文地址:https://blog.csdn.net/weixin_43796392/article/details/145566447

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!