基礎結構
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
- 加載字體,創建BaseFont
- 創建Font對象
- 創建文本對象的時候可設置字體
- 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;}}