using iTextSharp.text; using iTextSharp.text.pdf; using System.IO;
[HttpPost] public IActionResult ConvertToPdf(IFormFile file) { // 获取文件名和文件扩展名 string fileName = Path.GetFileNameWithoutExtension(file.FileName); string extension = Path.GetExtension(file.FileName);
// 如果文件扩展名不是PDF,则转换为PDF
if (extension != ".pdf")
{
// 创建新的PDF文件名
string newFileName = fileName + ".pdf";
// 创建PDF文档
Document pdfDoc = new Document();
// 为PDF文档添加页面
pdfDoc.AddAuthor("Author Name");
pdfDoc.AddTitle("Title");
// 添加新页面
pdfDoc.Open();
// 读取上传的文件流并将其添加到PDF文档中
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
// 在PDF中添加上传的文件
pdfDoc.Add(new Paragraph(fileName));
pdfDoc.Close();
byte[] content = stream.ToArray();
return File(content, "application/pdf", newFileName);
}
}
// 如果文件已经是PDF,则返回原始文件
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
byte[] content = stream.ToArray();
return File(content, "application/pdf", fileName);
}
}
这个控制器方法会判断上传的文件是否是PDF,如果不是PDF,则将它转换为PDF。
注意:需要将iTextSharp依赖项添加到项目中。