C#.NET iTextSharp生成PDF文件源码大全(生成表格、透明水印,页脚页眉页码等)
作者:作者不详  发布日期:2020-12-16 14:43:52
  C#.NET iTextSharp生成PDF文件源码大全(生成表格、透明水印,页脚页眉页码等)



贴图图片-自动创建PDF


测试 iTextSharp 生成PDF文件:

C# Code:

string fileName = string.Format("{0}.pdf", DateTime.Now.ToString("yyyyMMddHHmmss"));
string filePath = AppDomain.CurrentDomain.BaseDirectory + "Template\\" + fileName;

string str = CSFrameworkPDF.GetInstance().GeneratePDF(filePath);

//来源:C/S框架网 | www.csframework.com | QQ:23404761





iTextSharp 生成PDF文件:


C# Code:


/// <summary>
/// 生成PDF文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string GeneratePDF(string filePath)
{
  
try
  {
    
//A4纸尺寸:595*420,单位:磅
    
//doc = new Document(PageSize.A4);//默认边距,36磅
    
_doc = new Document(PageSize.A5, 36, 36, 36, 36);
    
    
//doc.SetMargins(0, 0, 0, 0);//移除页边距
    

    FileStream fs
= new FileStream(filePath, FileMode.Create);
    PdfWriter writer
= PdfWriter.GetInstance(_doc, fs);
    writer.CloseStream
= false;//把doc内容写入流中
    

    _doc.Open();
    
    
//创建页眉+图片+下划线
    
CreatePageHeader();
    
    _doc.AddTitle(
"生成PDF文件");
    _doc.AddSubject(
"生成PDF文件");
    _doc.AddKeywords(
"生成PDF文件");
    _doc.AddCreator(
"www.csframework.com|C/S框架网");
    _doc.AddAuthor(
"www.csframework.com|C/S框架网");
    
    
//中间内容
    
_doc.Add(new Paragraph("Hello World"));
    _doc.Add(
new Paragraph("标题字体:我是中国人/I'm Chinease!", fontTitle));
    _doc.Add(
new Paragraph("内容字体:我是中国人/I'm Chinease!", fontContent));
    
    
//Phrase类用法,同一行,短语拼接
    
Phrase p1 = new Phrase("/我是", fontContentUnderline);
    Phrase p2
= new Phrase("/测试", fontContent);
    Phrase p3
= new Phrase("/工程师www.csframework.com|C/S框架网", fontContentRed);
    
    _doc.Add(p1);
    _doc.Add(p2);
    _doc.Add(p3);
    
    
//Chunk类用法,下划线中英文文本
    
Chunk chunk1 = new Chunk("单行下横线文本/www.csframework.com|C/S框架网", fontContentUnderline);
    _doc.Add(
new Paragraph(chunk1));
    
    _doc.Add(
new Paragraph(" "));//添加空行
    

    CreateTable(CreateDemoData());
    
    
    
//在固定位置显示文本
    
CreateText(writer, "在固定位置显示文本111111111", new Rectangle(100, 0, 333, 300), fontContentRed);
    CreateText(writer,
"在固定位置显示文本222222222", new Rectangle(100, 0, 333, 200), fontContent);
    CreateText(writer,
"www.csframework.com|C/S框架网", new Rectangle(100, 0, 333, 100), fontContent);
    
    AddPageNumberContent(writer,
1, 1); //添加页码
    

    _doc.Close();
//关闭文档
    
    
//保存PDF文件
    
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();
    }
    
    
//设置水印
    
SetWaterMark(filePath);
  }
  
catch (DocumentException ex)
  {
    
throw new Exception(ex.Message);
  }
  
return filePath;
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761








iTextSharp 设置自定义字体


C# Code:

//中文字体-宋体
private static string fontCHN = (AppDomain.CurrentDomain.BaseDirectory + "Template\\simsun.ttf").Replace("\\", "/");
private static BaseFont bfCHN = BaseFont.CreateFont(fontdb, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

//宋体标题-深灰色
private static Font fontTitle = new Font(bfCHN, (float)10, 1, BaseColor.DARK_GRAY);

//宋体正文内容
private static Font fontContent = new Font(BaseFont.CreateFont(fontCHN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), (float)10, 1, BaseColor.DARK_GRAY);

//宋体正文内容-下划线字体
private static Font fontContentUnderline = new Font(BaseFont.CreateFont(fontCHN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), (float)10, 1, BaseColor.DARK_GRAY);

//宋体正文内容-红色
private static Font fontContentRed = new Font(BaseFont.CreateFont(fontCHN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), (float)10, 1, BaseColor.RED);


//来源:C/S框架网 | www.csframework.com | QQ:23404761




iTextSharp 给PDF文件创建半透明图片水印:



C# Code:

/// <summary>
/// 设置水印
/// </summary>
/// <param name="pdfFilePath"></param>
private void SetWaterMark(string pdfFilePath)
{
  PdfReader reader
= null;
  PdfStamper stamper
= null;
  
string newPDFFileName = "";
  
  
try
  {
    reader
= new PdfReader(pdfFilePath);
    
    
string waterPDF = Path.GetDirectoryName(pdfFilePath);
    
string fileWater = Path.GetFileName(pdfFilePath).Replace(".pdf", "") + "-Stamper.pdf";
    
    newPDFFileName
= Path.Combine(waterPDF, fileWater);
    
    stamper
= new PdfStamper(reader, new FileStream(newPDFFileName, FileMode.OpenOrCreate));
    
    
string imgPath = AppDomain.CurrentDomain.BaseDirectory + "\\Template\\logo.png";
    
    iTextSharp.text.Image img
= iTextSharp.text.Image.GetInstance(imgPath);
    
    
float width = _doc.PageSize.Width;
    
float height = _doc.PageSize.Height;
    
    
float waterMarkWidth = 150;
    
    
//像素
    
float percent = waterMarkWidth / img.Width;
    img.ScaleAbsoluteWidth(waterMarkWidth);
//缩放图片指定宽度
    
img.ScaleAbsoluteHeight(img.Height * percent);//等比例缩放高度
    
img.SetAbsolutePosition((width - waterMarkWidth) / 2, (height - img.Height * percent) / 2);//设置水印位置
    
img.Rotation = 95;//旋转角度
    
    
//指定颜色透明,如:白色
    
img.Transparency = new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
    
    
//设置透明度
    
//create new graphics state and assign opacity
    
PdfGState graphicsState = new PdfGState();
    graphicsState.FillOpacity
= 0.2F; // (or whatever)
    
//set graphics state to pdfcontentbyte
    
PdfContentByte contentByte;
    
int j = 0;
    
int n = reader.NumberOfPages;
    
while (j < n)
    {
      j++;
      contentByte
= stamper.GetOverContent(j);
      contentByte.SetGState(graphicsState);
//设置透明度
      
contentByte.AddImage(img);
    }
  }
  
finally
  {
    
if (stamper != null) stamper.Close();
    
if (stamper != null) reader.Close();
    
    
//改名
    
if (File.Exists(newPDFFileName))
    {
      File.Delete(pdfFilePath);
      FileInfo fi
= new FileInfo(newPDFFileName);
      fi.MoveTo(pdfFilePath);
    }
  }
}



//来源:C/S框架网 | www.csframework.com | QQ:23404761



iTextSharp 创建带图片LOGO的页眉:


C# Code:

private static void CreatePageHeader()
{
  PdfPTable table
= new PdfPTable(1);//一个单元格的
  
table.TotalWidth = 350;//设置绝对宽度
  
table.LockedWidth = true;//使绝对宽度模式生效
  
table.PaddingTop = 0;
  
  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.1f;//底部画线
  
cell.BorderColorBottom = BaseColor.DARK_GRAY;
  
  table.AddCell(cell);
  _doc.Add(table);
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




iTextSharp 在固定位置输出页码:


C# Code:

/// <summary>
/// 在固定位置生成页码
/// </summary>
/// <param name="writer"></param>
/// <param name="totalPage"></param>
/// <param name="currentPage"></param>
private static void AddPageNumberContent(PdfWriter writer, int totalPage, int currentPage)
{
  
//string text = String.Format("共 {0} 页 第 {1} 页", totalPage, currentPage);
  
string text = String.Format("第 {0} 页", currentPage);
  ColumnText ct
= new ColumnText(writer.DirectContent);
  ct.SetSimpleColumn(
new Rectangle(200, 0, 533, 50));
  ct.AddElement(
new Paragraph(text, fontPageNo));
  ct.Go();
}


//来源:C/S框架网 | www.csframework.com | QQ:23404761




iTextSharp 在PDF页面固定位置输出文本



C# Code:


/// <summary>
/// 在PDF页面固定位置输出文本
/// </summary>
/// <param name="writer"></param>
/// <param name="text"></param>
/// <param name="rect"></param>
/// <param name="font"></param>
private void CreateText(PdfWriter writer, string text, Rectangle rect, Font font)
{
  
//在固定位置显示文本
  
ColumnText ct = new ColumnText(writer.DirectContent);
  ct.SetSimpleColumn(rect);
  ct.AddElement(
new Paragraph(text, font));
  ct.Go();
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



iTextSharp 在PDF生成表格


C# Code:


/// <summary>
/// 在PDF生成表格
/// </summary>
private void CreateTable(DataTable dt)
{
  iTextSharp.text.pdf.PdfPTable datatable
= new PdfPTable(6);
  
float[] headerwidths = { 50, 100, 40, 40, 100, 80 };
  datatable.SetWidths(headerwidths);
  datatable.WidthPercentage
= 100;
  datatable.HeaderRows
= 1;
  datatable.PaddingTop
= 5;
  
  
for (int i = 0; i <= dt.Columns.Count - 1; i++)
  {
    Phrase ph
= new Phrase(dt.Columns[i].ColumnName, fontContent);
    iTextSharp.text.pdf.PdfPCell cell1
= new PdfPCell(ph);
    cell1.HorizontalAlignment
= Element.ALIGN_CENTER;
    cell1.BackgroundColor
= new iTextSharp.text.BaseColor(0xC0, 0xC0, 0xC0);
    datatable.AddCell(cell1);
  }
  
  
foreach (DataRow R in dt.Rows)
  {
    datatable.AddCell(
new Phrase(R["ID"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Name"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Sex"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Age"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Phone"].ToString(), fontContent));
    datatable.AddCell(
new Phrase(R["Address"].ToString(), fontContent));
  }
  
  _doc.Add(datatable);
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



iTextSharp Demo总结:

从代码上不难看出,普遍用到的标签大多为Document、Paragraph、Table、Cell、Chunck、Font、Element,通过这些标签大概能组合出自己想要的效果。



iTextSharp 页面尺寸度量单位:

度量单位:厘米、英寸或象素,事实上,默认的度量系统以排版单位磅为基础得出其他单位的近似值,
如1英寸=72磅,如果你想在A4页面的PDF中创建一个矩形,你需要计算以下数据: 
21 厘米 / 2.54 = 8.2677 英寸 
8.2677英寸* 72 = 595 磅 
29.7 厘米 / 2.54 = 11.6929 英寸 
11.6929英寸* 72 = 842 磅 

默认边距为36磅即半英寸。 




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务


上一篇 下一篇