using static System.Net.Mime.MediaTypeNames;
using iText.Kernel.Pdf;
using iText.IO.Image;
using iText.Layout.Element;
using Image = iText.Layout.Element.Image;
using PageSize = iText.Kernel.Geom.PageSize;
using iText.Layout;
using iText.Layout.Properties;
using iText.Kernel.Font;
using iText.IO.Font;
using iText.Kernel.Colors;
using System.IO;
using iText.IO.Font.Constants;
using static iText.Kernel.Font.PdfFontFactory;
using DocumentFormat.OpenXml.Packaging;
namespace Admin.NET.Core
{
public class PdfOptHelper
{
///
///
///
///
///
///
public static string AddLineBreaks(string input, int maxLength)
{
if (string.IsNullOrEmpty(input) || maxLength <= 0)
return input;
var result = new StringBuilder();
int currentLength = 0;
foreach (var ch in input)
{
result.Append(ch);
currentLength++;
// 如果当前长度达到了最大长度,添加换行符并重置计数
if (currentLength >= maxLength)
{
result.Append('\n');
currentLength = 0;
}
}
return result.ToString();
}
///
///
///
///
///
///
///
///
///
public static byte[] CreatePdfAsync(
string pagetitle,
List headers,
List majors,
List dataModels,
DateTime dtnow)
{
var stream = new MemoryStream();
try
{
// 创建 PdfWriter
PdfWriter writer = new PdfWriter(stream, new WriterProperties().SetCompressionLevel(CompressionConstants.BEST_COMPRESSION));
PdfDocument pdf = new PdfDocument(writer);
// 设置页面大小
pdf.SetDefaultPageSize(PageSize.A4.Rotate());
Document document = new Document(pdf);
// 加载中文字体
PdfFont font = GetFont();
// 添加 logo 图像
string logoPath = "https://static-data.ycymedu.com/logo2.png";
ImageData imageData = ImageDataFactory.Create(logoPath);
Image logo = new Image(imageData).SetWidth(124).SetHeight(40);
document.Add(logo);
// 添加标题
document.Add(CreateTitle(font, pagetitle));
document.Add(CreateSubTitle(font, $"最后修改时间: {dtnow:yyyy-MM-dd HH:mm}"));
// 添加表格
foreach (var dataModel in dataModels)
{
Table universityTable = HeaderTable(font, 9, headers, new List { dataModel });
universityTable.SetMarginTop(20);
document.Add(universityTable);
Table majorTable = MajorTable(font, 9, majors, dataModel.majorModels);
document.Add(majorTable);
document.Add(new Paragraph("\n"));
}
document.Close(); // 关闭文档
return stream.ToArray();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
stream.Dispose();
throw;
}
}
private static PdfFont GetFont()
{
string fontPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot", "fonts", "AlibabaPuHuiTi.otf");
try
{
if (File.Exists(fontPath))
{
return PdfFontFactory.CreateFont(fontPath, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
}
else
{
Console.WriteLine($"字体文件 {fontPath} 不存在,使用备用字体。");
// 使用系统默认字体
return PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
}
}
catch (Exception ex)
{
Console.WriteLine($"加载字体时出错: {ex.Message},使用备用字体。");
return PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
}
}
public static async Task GeneratePdfAsync(Stream outputStream, string title,
List headers, List majors,
List dataModels, DateTime timestamp)
{
try
{
// 使用 PdfWriter 写入流
var writer = new PdfWriter(outputStream, new iText.Kernel.Pdf.WriterProperties());
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
// 设置标题
document.Add(new Paragraph(title).SetFontSize(18));
// 设置时间戳
document.Add(new Paragraph($"Generated at: {timestamp:yyyy-MM-dd HH:mm:ss}").SetFontSize(12));
// 添加表格(示例)
var table = new Table(headers.Count);
foreach (var header in headers)
{
table.AddHeaderCell(new Cell().Add(new Paragraph(header)));
}
foreach (var major in majors)
{
table.AddCell(new Cell().Add(new Paragraph(major)));
}
document.Add(table);
// 关闭文档
document.Close();
// 确保所有内容写入流
await outputStream.FlushAsync();
}
catch (Exception ex)
{
// 错误处理
throw new Exception("Failed to generate PDF.", ex);
}
}
///
/// 标题
///
///
///
///
private static Paragraph CreateTitle(PdfFont font, string titletext)
{
Paragraph title = new Paragraph(titletext)
.SetTextAlignment(TextAlignment.CENTER)
.SetFont(font)
.SetFontSize(16)
.SetMarginTop(20)
.SetMarginBottom(5);
return title;
}
///
/// 创建副标
///
///
///
///
private static Paragraph CreateSubTitle(PdfFont font, string titletext)
{
Paragraph title = new Paragraph(titletext)
.SetTextAlignment(TextAlignment.CENTER)
.SetFont(font)
.SetFontColor(ColorConstants.GRAY) // 设置字体颜色为灰色
.SetFontSize(12)
.SetMarginBottom(20);
return title;
}
///
/// table表头
///
///
///
///
private static Table HeaderTable(PdfFont font, int tb, List headers, List dataList)
{
float[] columnWidths = { 1, 1, 2, 3, 2, 2, 2, 1, 1 };
Table table = new Table(columnWidths);
table.SetWidth(UnitValue.CreatePercentValue(100));
int h = 0;
foreach (var header in headers)
{
h++;
if (h == 4)
{
table.AddHeaderCell(new Cell().Add(new Paragraph(header).SetWidth(120).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
}
else
{
table.AddHeaderCell(new Cell().Add(new Paragraph(header).SetWidth(50).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
}
}
dataList.ForEach(a =>
{
table.AddCell(new Cell().Add(new Paragraph(a.id.ToString()).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.probability).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.universityCode).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.universityName).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.planCount).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.history).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
a.years.ForEach(a =>
{
table.AddCell(new Cell().Add(new Paragraph(a).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
});
});
return table;
}
private static Table MajorTable(PdfFont font, int tb, List headers, List dataList)
{
float[] columnWidths = { 1, 1, 2, 3, 2, 2, 2, 1, 1 };
Table table = new Table(columnWidths);
table.SetWidth(UnitValue.CreatePercentValue(100));
int h = 0;
foreach (var header in headers)
{
h++;
if (h == 4)
{
table.AddCell(new Cell().Add(new Paragraph(header).SetWidth(85).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
}
else
{
table.AddCell(new Cell().Add(new Paragraph(header).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
}
}
dataList.ForEach(a =>
{
table.AddCell(new Cell().Add(new Paragraph(a.id.ToString()).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.probability).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.majorCode).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.mjaorName).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.planCount).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
table.AddCell(new Cell().Add(new Paragraph(a.history).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
a.years.ForEach(a =>
{
table.AddCell(new Cell().Add(new Paragraph(a).SetFont(font).SetTextAlignment(TextAlignment.CENTER)));
});
});
return table;
}
public class DataModel
{
// 示例数据模型
public string Name { get; set; }
public int Value { get; set; }
}
public class dataModel
{
public int id { get; set; }
///
///
///
public string probability { get; set; }
///
///
///
public string universityCode { get; set; }
///
///
///
public string universityName { get; set; }
public string planCount { get; set; }
public string planName { get; set; }
public string history { get; set; }
public List years { get; set; }
///
///
///
public List majorModels { get; set; }
}
public class dataMajorModel
{
public int id { get; set; }
///
///
///
public string probability { get; set; }
///
///
///
public string majorCode { get; set; }
///
///
///
public string mjaorName { get; set; }
public string planCount { get; set; }
public string history { get; set; }
public List years { get; set; }
}
}
}