码迷,mamicode.com
首页 > 其他好文 > 详细

根据模板编辑PDF

时间:2018-08-27 10:24:38      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:tin   height   top   编辑   new   absolute   byte   mod   position   

public static string CreatePDF(string cName, string eName, string imageURL)
{
try
{
var pdfsrc = "~/File/PDF/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";

var pdfTemplateFile = "~/File/模板.pdf";

var fos = new FileStream(HttpContext.Current.Server.MapPath(pdfsrc), FileMode.Create);

var reader = new PdfReader(HttpContext.Current.Server.MapPath(pdfTemplateFile));

var stamper = new PdfStamper(reader, fos);

stamper.Writer.CloseStream = false;

AcroFields form = stamper.AcroFields;

//添加图片
if (File.Exists(imageURL))
{
//获取第三页
var pdfContentByte = stamper.GetOverContent(3);

var imageStream = new FileStream(HttpContext.Current.Server.MapPath(imageURL), FileMode.Open);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageStream);
image.SetAbsolutePosition(120, 315);//left top
image.ScaleAbsolute(60, 20);//width height
pdfContentByte.AddImage(image);
}

//中文字体
BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1",BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);

form.AddSubstitutionFont(baseFont);
form.SetField("cName", cName);

form.SetField("eName", eName);
form.SetField("cDate", DateTime.Now.ToString("yyyy-M-d"));

var random = new Random();
for (var i = 1; i < 6; i++)
{
var n = random.Next(1, 5);
for (var j = 1; j < 5; j++)
{
form.SetField("an" + i + j, j == n ? "\u0052" : "\u00A3");
}
}

stamper.FormFlattening = true;

reader.Close();
stamper.Close();
fos.Close();

return HttpContext.Current.Server.MapPath(pdfsrc);
}
catch (Exception ex)
{
return null;
}
}

根据模板编辑PDF

标签:tin   height   top   编辑   new   absolute   byte   mod   position   

原文地址:https://www.cnblogs.com/sanjiaolong/p/9540314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!