应用场景 打印学生新生报到证:
上代码:
public void PrintBdz(string bmh, string xqjy_date, string xqjy_dz, string kxdl_date, string kxdl_dz)
{
try
{
string tplFileName = ""; //PDF模板文件
string tmpFolder = "";
tplFileName = @"D:\webapps\sol_file\Print\tpl\Bdz201809.pdf";
tmpFolder = @"D:\webapps\sol_file\Print\tmp\Bdz201809\";
#if DEBUG
tplFileName = @"P:\webapps\sol_file\Print\tpl\Bdz201809.pdf";
tmpFolder = @"P:\webapps\sol_file\Print\tmp\Bdz201809\";
#endif
if (!Directory.Exists(tmpFolder))
{
Directory.CreateDirectory(tmpFolder);
}
var item = GetStuDetailByBmh(bmh);
string fileNameNew = tmpFolder + item.bmh + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
iTextSharp.text.io.StreamUtil.AddToResourceSearch(Assembly.Load("iTextAsian"));
BaseFont baseFontCN = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
PdfReader reader = new PdfReader(tplFileName);
FileStream fs_pdf = new FileStream(fileNameNew, FileMode.Create);
PdfStamper pdfStamper = new PdfStamper(reader, fs_pdf);
pdfStamper.AcroFields.AddSubstitutionFont(baseFontCN);
AcroFields acroFields = pdfStamper.AcroFields;
//以下为填写表单部分
acroFields.SetField("pc_mc", item.pc_mc);
acroFields.SetField("bmh", item.bmh);
acroFields.SetField("xs_xm", item.xs_xm);
acroFields.SetField("xs_sfz", item.xs_sfz);
acroFields.SetField("xlcc_mc", item.xlcc_mc);
acroFields.SetField("zy_mc", item.zy_mc);
acroFields.SetField("yddh", item.yddh);
acroFields.SetField("room_title", item.room_title);
///开学典礼和学前教育
acroFields.SetField("xqjy_date", xqjy_date);
acroFields.SetField("xqjy_dz", xqjy_dz);
acroFields.SetField("kxdl_date", kxdl_date);
acroFields.SetField("kxdl_dz", kxdl_dz);
int numberOfPages = reader.NumberOfPages;
iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
PdfContentByte waterMarkContent;
string img_base_path= tplFileName = @"D:\webapps\sol_s2e\";
#if DEBUG
img_base_path = @"P:\webapps\sol_s2e\";
#endif
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(img_base_path + item.pic_url);
image.ScaleAbsoluteHeight(160);
image.ScaleAbsoluteWidth(120);
image.SetAbsolutePosition(361, 575);//定位
waterMarkContent = pdfStamper.GetUnderContent(1);
waterMarkContent.AddImage(image);
pdfStamper.Close();
reader.Close();
//以字符流的形式下载文件
FileStream fs = new FileStream(fileNameNew, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
DelTmpPdf(fileNameNew);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.AddHeader("Content-Disposition", "inline; filename=" + fileNameNew + ".pdf");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch (Exception e)
{
logger.Error(e.Message);
}
}
引用: