意思是标记第一行数据是table的header,然后循环每一页的时候就会自动加上header。不然它不知道哪一行是header。
net生成pdf表头项目需要在线生成PDF文件,我首先考虑采用itextsharp控件来实现。具体方法参考 https://sourceforge.net/projects/itextsharp/
1.首先利用nuget 引入该控件包。![在这里插入图片描述](https://img-blog.csdnimg.cn/img_convert/2626f9837f6e050e0abfa4fe62dc720c.png#pic_center)
2、然后直接创建就可以了。
using iTextSharp.text
using iTextSharp.text.pdf
using System
using System.Collections.Generic
using System.Data
using System.IO
using System.Linq
using System.Text
using System.Web
public class CreatePDF
{
private static CreatePDF instance
public static CreatePDF GetInstance()
{
if (instance == null)
{
instance = new CreatePDF()
}
return instance
}
private static Document doc
//string fontdb = AppDomain.CurrentDomain.BaseDirectory + "Template\\msyh.ttc"
//private static BaseFont bf = BaseFont.CreateFont(@"C://Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
static string fontdb = (AppDomain.CurrentDomain.BaseDirectory + "Template\\msyh.ttf").Replace("\\", "/")
private static BaseFont bf = BaseFont.CreateFont(fontdb + "", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
//四种字体
private static Font fontBig = new Font(bf, 14, Font.BOLD)
private static Font fontSmall = new Font(bf, (float)10.5, Font.BOLD)
private static Font fontSmallNoBold = new Font(bf, (float)10.5)
private static float IndentationLeft = 50//距左边距
//如果要传参数进来,可自定义
public string GeneratePDF(string name)
{
doc = new Document(PageSize.A4)
string filePath = string.Empty
try
{
//MemoryStream ms2 = new MemoryStream()
string fileName = string.Format("{0}.pdf", DateTime.Now.ToString("yyyyMMddHHmmss"))
filePath = AppDomain.CurrentDomain.BaseDirectory + "Template\\" + fileName
FileStream fs = new FileStream(filePath, FileMode.Create)//创建临时文件,到时生成好后删除
PdfWriter writer = PdfWriter.GetInstance(doc, fs)
writer.CloseStream = false//把doc内容写入流中
doc.Open()
//核心 *** 作
CreateLine(name)//生成一条下横线
#region 添加水印
string waterMarkName = "机密"
#endregion
doc.Close()
MemoryStream ms = new MemoryStream()
if (fs != null)
{
byte[] bytes = new byte[fs.Length]//定义一个长度为fs长度的字节数组
fs.Read(bytes, 0, (int)fs.Length)//把fs的内容读到字节数组中
ms.Write(bytes, 0, bytes.Length)//把字节内容读到流中
fs.Flush()
fs.Close()
}
MemoryStream waterMS = SetWaterMark(ms, filePath, waterMarkName)//先生成水印,再删除临时文件
//if (File.Exists(filePath))//判断临时文件是否存在,如果存在则删除
//{
//File.Delete(filePath)
//GC.Collect()//回收垃圾
//}
//SendFile(fileName, waterMS)//把PDF文件发送回浏览器
}
catch (DocumentException ex)
{
throw new Exception(ex.Message)
}
return filePath
}
#region 生成一条横线
private static void CreateLine(string name)
{
PdfPTable table = new PdfPTable(1)//一个单元格的
PdfPCell cell = new PdfPCell()
Image gif = Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "Template\\logo.png")
gif.ScaleAbsoluteWidth(100)
cell.AddElement(gif)
cell.BorderWidth = 0f
cell.BorderWidthBottom = 0.2f
table.AddCell(cell)
doc.Add(table)
}
#endregion
#region 生成页码
private static void AddPageNumberContent()
{
var content = new Paragraph("共 页 第 页", fontSmall)
content.IndentationRight = IndentationLeft + 20
content.Alignment = 2 //居左
doc.Add(content)
}
#endregion
#region 生成单元格
private static PdfPCell GetPdfCell(string content, Font font, int horizontalAlignment)
{
Paragraph paragraph = new Paragraph(content, font)
paragraph.FirstLineIndent = 2
paragraph.SetLeading(10, 20)
paragraph.SpacingAfter = 10
PdfPCell cell = new PdfPCell(paragraph)
cell.HorizontalAlignment = horizontalAlignment//水平位置
cell.VerticalAlignment = Element.ALIGN_CENTER//垂直居中
cell.MinimumHeight = 20//单元格的最小高度
cell.Border = 0
return cell
}
#endregion
#region 生成水印
private static MemoryStream SetWaterMark(MemoryStream ms, string filePath, string waterMarkName, string waterMarkAddr = null)
{
MemoryStream msWater = new MemoryStream()
PdfReader pdfReader = null
PdfStamper pdfStamper = null
try
{
pdfReader = new PdfReader(filePath)
pdfStamper = new PdfStamper(pdfReader, msWater)
int total = pdfReader.NumberOfPages + 1//获取PDF的总页数
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1)//获取第一页
float width = psize.Width//PDF页面的宽度,用于计算水印倾斜
float height = psize.Height
PdfContentByte waterContent
BaseFont basefont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED)
PdfGState gs = new PdfGState()
for (int i = 1i <totali++)
{
waterContent = pdfStamper.GetOverContent(i)//在内容上方加水印
//透明度
waterContent.SetGState(gs)
//开始写入文本
waterContent.BeginText()
waterContent.SetColorFill(BaseColor.RED)
waterContent.SetFontAndSize(basefont, 18)
waterContent.SetTextMatrix(0, 0)
if (waterMarkAddr == null || waterMarkAddr == "")
{
waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2, 55)
}
else
{
waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2 + 100, 55)
waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkAddr, width / 2, height / 2 - 100, 55)
}
waterContent.EndText()
}
}
catch (Exception)
{
return ms
}
finally
{
if (pdfStamper != null)
pdfStamper.Close()
if (pdfReader != null)
pdfReader.Close()
}
return msWater
}
#endregion
//-----------------------发送PDF文件回浏览器端----------------------
public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null)
{
fileName = (fileName + "").Replace(" ", "")
encoding = encoding ?? Encoding.UTF8
if (ms != null &&!string.IsNullOrEmpty(fileName))
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response
response.Clear()
response.Charset = encoding.BodyName// "utf-8"
if (!HttpContext.Current.Request.UserAgent.Contains("Firefox") &&!HttpContext.Current.Request.UserAgent.Contains("Chrome"))
{
fileName = HttpUtility.UrlEncode(fileName, encoding)
}
response.AddHeader("Content-Disposition", "attachmentfilename=" + fileName)
//为了解决打开,导出NPOI生成的xlsx文件时,提示发现不可读取内容。
if (!(fileName + "").ToLower().EndsWith(".xlsx"))
{
response.AddHeader("Content-Type", "application/octet-stream")
response.BinaryWrite(ms.GetBuffer())
}
else
{
response.BinaryWrite(ms.ToArray())
}
ms.Close()
ms = null
response.Flush()
response.End()
}
}
}
登录后复制
特别需要注意一点的是,如果对字体有特殊要求,可以将字库文件放在项目目录下,但字库的文件类型不同,引用时略有差别。
pdftable就是表格,把你的表格加到段落里或者这样子循环表格
for (int i = 0i <pt.Rows.Counti++)
{
PdfPCell[] cells = pt.Rows[i].GetCells()
for (int l = 0l <cells.Count()l++)
{
PdfPCell item = cells[l]
if (item != null &&item.CompositeElements != null)
{
foreach (var el in item.CompositeElements)
{
foreach (var ck in el.Chunks)
{
ck.Font = new Font(baseFont)
ck.Font.Size = 10} } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)