C#生成PDF文件流

时间:2021-09-10 02:53:59

1。设置字体

 static BaseFont FontBase = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
static iTextSharp.text.Font bodyFont = new iTextSharp.text.Font(FontBase, );
static iTextSharp.text.Font titleFont = new iTextSharp.text.Font(FontBase, );
static iTextSharp.text.Font paragraphFont = new iTextSharp.text.Font(FontBase, );
static iTextSharp.text.Font linkFont = new iTextSharp.text.Font(FontBase, , Font.UNDERLINE, BaseColor.BLUE);

2.生成PDF文件流返回byte数组

 public byte[] DocCreate(System.Drawing.Image image, List<TreeNodes> list)
{
MemoryStream file = new MemoryStream(); string fileName = string.Empty;
Rectangle page = PageSize.A4;
float y = page.Height;
Document document = new Document(page, , , , );
float docWidth = page.Width - * ;
float docHeight = page.Height - document.BottomMargin - document.TopMargin;
PdfWriter writer = PdfWriter.GetInstance(document, file);
writer.CloseStream = false;
writer.Open();
PdfContentByte cb = writer.DirectContent;
document.Open();
//标题
Paragraph title = new Paragraph(new Chunk("标题", titleFont));
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
//图片
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(image, ImageFormat.Png);
float widthSzie = (page.Width - ) / img.Width;
if (widthSzie < )
{
img.ScalePercent(widthSzie * );
}
document.Add(img);
//文献出处
Paragraph p2 = new Paragraph(new Chunk("出处", paragraphFont));
p2.IndentationLeft = indentationLeft;
document.Add(p2);
InitData(list);//初始化业务数据
CreateSteps(list, document, list.FirstOrDefault(it => it.PID == ));//添加业务数据
////添加印章
//iTextSharp.text.Image whyz = iTextSharp.text.Image.GetInstance(whyzPath);
//whyz.ScalePercent(50);
//whyz.PaddingTop = 100;
//whyz.Alignment = Element.ALIGN_RIGHT;
//document.Add(whyz);
//添加日期
Paragraph createtime = new Paragraph(new Chunk(DateTime.Now.ToLongDateString().ToString(), bodyFont));
createtime.Alignment = Element.ALIGN_RIGHT;
//createtime.SpacingBefore = -80;
createtime.PaddingTop = ; document.Add(createtime); document.Close();
file.Position = ;
MemoryStream newfile = SetWaterMark(file, "水印内容", docWidth, docHeight);//添加水印,见另外一篇博客
newfile.Position = ;//重置流指针位置
byte[] bytes = new byte[newfile.Length];
newfile.Read(bytes, , bytes.Length);
return bytes;
}