参考地址:https://www.cnblogs.com/ibeisha/p/itextsharp-pdf.html
一、先在程序中使用Nuget安装iTextSharp(我是创建的控制台程序)
二、建立静态常量类
public class ConstantInfo
{
/// <summary>
/// 证书下载目录
/// </summary>
public static string _Certificate { get { return "/DownloadResource/Certificate/"; } } /// <summary>
/// 证书模板目录
/// </summary>
public static string _CertificateTemplate { get { return "/Resources/"; } }
}
三、生成pdf主体代码
class Program
{
static void Main(string[] args)
{
//生成的pdf文件名称
string fileName = "Certificate_test.pdf";
//生成的pdf文件目录
string downloadFilePath = AppDomain.CurrentDomain.BaseDirectory + ConstantInfo._Certificate;
//生成的pdf文件完整路径
string downloadFileName = downloadFilePath + fileName;
//如没有,则创建
if (!Directory.Exists(downloadFilePath))
{
Directory.CreateDirectory(downloadFilePath);
}
//证书模板目录
string templateFilePath = AppDomain.CurrentDomain.BaseDirectory + ConstantInfo._CertificateTemplate + "TemplateCer.pdf";
//可直接写成固定目录
//string tempFilePath = "D:\\tmp.pdf";
//字体资源
string fontFilePath = AppDomain.CurrentDomain.BaseDirectory + ConstantInfo._CertificateTemplate + "msyhbd.ttf"; iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(templateFilePath);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(downloadFileName, FileMode.OpenOrCreate));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfStamper.FormFlattening = true; //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
BaseFont simheiBase = BaseFont.CreateFont(fontFilePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //添加图片
//Image image = Image.GetInstance("");
//pdfStamper.Writer.Add(image); pdfFormFields.AddSubstitutionFont(simheiBase);
//根据pdf中对应的表单域(一定要一致)赋对应的值
pdfStamper.AcroFields.SetField("Name", "小红");
pdfStamper.AcroFields.SetField("Score", "");
pdfStamper.AcroFields.SetField("CompanyName", "测试测试");
pdfStamper.AcroFields.SetField("Date", "2019-7-17");
//pdfStamper.AcroFields.SetField("chk", "yes", true);
pdfStamper.Close();
pdfReader.Close();
Console.Read();
//解析文本
//PdfReaderContentParser parser = new PdfReaderContentParser(pdfReader); //PdfWriter pdfWriter; //ITextExtractionStrategy strategy;
//strategy = parser.ProcessContent<SimpleTextExtractionStrategy>(1, new SimpleTextExtractionStrategy());
//string ss = strategy.GetResultantText(); //byte[] buffer = pdfReader.GetPageContent(1); //string strBody = System.Text.Encoding.Default.GetString(buffer);
}
}
四、文件路径如图:
其中ttf是用到的字体,看自己需要用到什么字体,可直接从网上下载对应的字体
生成的效果图
后记:最近遇到一个问题,在软件中已经用预览功能调整好字体的大小,但是在程序中,如果不用下载字体的话,值赋不上,如果用下载的字体(ttf)的话,和在软件中设置的还是有差别的。最后还是得再调整。有时间一定要看看这个问题。