在 Nuget 中导入需要的插件:

.net Core 使用 iTextSharp 生成PDF 简单示例_文件路径

实现的代码:



1 [HttpGet, Route("CreatePdf")]
2 public Response CreatePdf()
3 {
4 Response resp = new Response();
5 resp.StartTime = DateTime.Now;
6 try
7 {
8 string pdfPath = @"D:\temp.pdf";
9
10 //.NET Core 在默认情况下是没有注册EncodeProvider,需要我们手动自己去注册
11 //需要先添加CodePagesEncoingProvider的引用,在NuGet包System.Text.Encoding.CodePages里面
12 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
13
14 Document document = new Document();
15 BaseFont bf = BaseFont.CreateFont(@"C:\Windows\Fonts\MSYH.TTC,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
16 Font f = new Font(bf, 9);
17 PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
18 document.Open();
19 Paragraph paragraph = new Paragraph("Hello World! 你好", f);
20 document.Add(paragraph);
21 document.Close();
22
23 resp.FilePath = pdfPath;
24 }
25 catch (Exception ex)
26 {
27 //throw ex;
28 resp.Message = ex.Message;
29 }
30
31 resp.EndTime = DateTime.Now;
32
33 return resp;
34 }


返回结果的对象:



1     /// <summary>
2 /// 返回结果
3 /// </summary>
4 public class Response
5 {
6 /// <summary>
7 /// 开始时间
8 /// </summary>
9 public DateTime StartTime { get; set; }
10 /// <summary>
11 /// 结束时间
12 /// </summary>
13 public DateTime EndTime { get; set; }
14 /// <summary>
15 /// 提示信息
16 /// </summary>
17 public string Message { get; set; }
18 /// <summary>
19 /// 文件路径
20 /// </summary>
21 public string FilePath { get; set; }
22 }