NET|C#生成PDF文件
项目需要在线生成PDF文件,我首先考虑采用itextsharp控件来实现。具体方法参考 https://sourceforge.net/projects/itextsharp/
1.首先利用nuget 引入该控件包。
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