Steps to quickly build PDF documents in asp.net core share page 1 of 2

Time:2020-4-1

For example, we need to use PDF to develop some simple reports in asp.net core, which is not difficult, but we will still rush to search for some materials. Congratulations, this post will help you, and we will not waste some precious time.

In this article, we will use dinktodfs to process our PDF documents in the. Net core web program! Let’s not talk about it now, just start the interesting part.

Preface

You can get the source code by creating PDF document in my warehouse. Welcome to a free star

Now let’s create a. Net core 3.0 project. As for MVC, API, I don’t care. After the project is created, nuget directly installs dinktopdf. Then you need to download the “native library” folder in my code warehouse, where we will find two files 32bit and 64bit, so we need to select the appropriate library for the operating system. We will select files from the 64 bit folder.

Finally, we need to start the library, and IOC dinktopdf.


public void ConfigureServices(IServiceCollection services)
  {
   var context = new CustomAssemblyLoadContext();
   context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), "libwkhtmltox.dll"));

   services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
   services.AddControllers();
  }

Establish entity#

In real-world projects, we can collect data from databases or receive data from other APIs. But for the sake of simplicity, we will collect the data of PDF documents from local storage. Later, we will create an HTML template and store it in a PDF document.


public class Employee
 {
  public string Name { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
  public string Gender { get; set; }
 }

Then, we will create a new folder services and two kinds of files, dataservices.cs and templategenerator.cs. The complete structure shall be as follows:


public class DataServices
 {
  public static List<Employee> GetAllEmployess() =>
   new List<Employee>
   {
    new Employee { Name="Hao Zi Zhang", LastName="Turner", Age=35, Gender="Male"},
    new Employee { Name="Yu Chen", LastName="Markus", Age=22, Gender="Female"},
    new Employee { Name="Jian Zhi Chu", LastName="Martins", Age=40, Gender="Male"},
    new Employee { Name="ElderJames", LastName="Packner", Age=30, Gender="Female"},
    new Employee { Name="BlaZui", LastName="Doe", Age=45, Gender="Male"}
   };
 }

Some data is returned from the add service to simulate the service. We want to generate an HTML template, so we need to modify the templategenerator.cs file:


public class TempleGenertor
 {
  public static string GetHTMLString()
  {
   var employees = DataServices.GetAllEmployess();

   var sb = new StringBuilder();
   sb.Append(@"
      <html>
       <head>
       </head>
       <body>
        <div class='header'><h1>This is the generated PDF report!!!</h1></div>
        <table align='center'>
         <tr>
          <th>Name</th>
          <th>LastName</th>
          <th>Age</th>
          <th>Gender</th>
         </tr>");

   foreach (var emp in employees)
   {
    sb.AppendFormat(@"<tr>
         <td>{0}</td>
         <td>{1}</td>
         <td>{2}</td>
         <td>{3}</td>
         </tr>", emp.Name, emp.LastName, emp.Age, emp.Gender);
   }
   sb.Append(@"
        </table>
       </body>
      </html>");

   return sb.ToString();
  }
 }

If you want to specify the CSS style, you can create some folders, and then choose the configuration through the server path in the API.


.header {
 text-align: center;
 color: green;
 padding-bottom: 35px;
}

table {
 width: 80%;
 border-collapse: collapse;
}

td, th {
 border: 1px solid gray;
 padding: 15px;
 font-size: 22px;
 text-align: center;
}

table th {
 background-color: green;
 color: white;
}

That’s it. We have HTML templates for HTML creation. Now, we can continue to execute the controller logic.

[Route("api/PdfCreator")]
 [ApiController]
 public class PdfCreatorController : ControllerBase
 {
  private IConverter _converter;

  public PdfCreatorController(IConverter converter)
  {
   _converter = converter;
  }

  [HttpGet]
  public IActionResult CreatePDF()
  {
   var globalSettings = new GlobalSettings
   {
    ColorMode = ColorMode.Color,
    Orientation = Orientation.Portrait,
    PaperSize = PaperKind.A4,
    Margins = new MarginSettings { Top = 10 },
    DocumentTitle = "PDF Report"
   };

   var objectSettings = new ObjectSettings
   {
    PagesCount = true,
    HtmlContent = TempleGenertor.GetHTMLString(),
    WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "style.css") },
    HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page 
                        12 read next page

  • asp.net
  • core
  • pdf

Related articles

  • asp.net使用DataTable构造Json字符串的方法

    Asp.net using datatable to construct JSON string

    This article mainly introduces the method of asp.net using datatable to construct JSON string, involving asp.net string serialization, traversal, construction and other operating skills. Please refer to

    2015-12-12

  • asp.net 客户端浏览器缓存的Http头介绍

    HTTP header of asp.net client browser cache

    Website development is inseparable from caching. There are many kinds of caching: server caching, third-party caching, browser caching, etc. Among them, browser cache is the least expensive, because browser cache relies on the client, and hardly consumes the resources of the server.

    2009-07-07

  • DataList中TextBox onfocus调用后台void静态方法及获取相应行数

    Textbox onfocus in datalist calls the background void static method and gets the corresponding number of rows

    I put a textbox in the datalist. Now the problem is when I put my cursor on the textbox. If you let onfocus call a static void method in the background and get the corresponding row number of datalist corresponding to the cursor in the static method, this article introduces how to implement it, and interested friends can learn the following

    2013-01-01

  • Asp.net MVC实现生成Excel并下载功能

    Asp.net MVC realizes the function of generating excel and downloading

    This article mainly introduces the function of asp.net MVC to generate excel and download it in detail, which has certain reference value. Interested partners can refer to it

    2017-12-12

  • ASP.NET 2005 Treeview终极解决方案

    Asp.net 2005 treeview ultimate solution

    Asp.net 2005 treeview ultimate solution

    2006-09-09

  • aspx中的mysql操作类sqldatasource使用示例分享

    Example sharing of MySQL operation class sqldatasource in aspx

    The server is equipped with MySQL ODBC driver. If you want to operate MySQL of another server on that IIS, find a. Net sqldatasource class to operate mysql. Next, share the usage

    2014-01-01

  • Log4net日志记录组件的使用步骤详解和下载

    Detailed explanation and download of using steps of log4net logging component

    Log4net log recording component’s use steps are explained in detail. Please refer to it for your friends

    2013-02-02

  • ASP.NET第一次访问慢的完美解决方案(MVC,Web Api)

    Perfect solution for asp.net’s first slow access (MVC, web API)

    This article mainly introduces to you the relevant materials about the perfect solution (MVC, web API) of asp.net’s first slow access. In this article, the example code is introduced in detail, which has certain reference learning value for you to learn or use asp.net. The friends who need to learn it together are as follows

    2019-07-07

  • ASP.NET Core 2.0 WebApi全局配置及日志实例

    Asp.net core 2.0 webapi global configuration and log instance

    The following editor will share an asp.net core 2.0 webapi global configuration and log instance for you. It has a good reference value and hopes to help you. Let’s follow Xiaobian to have a look

    2017-12-12

  • IIS应用池回收造成Application_Start中定时执行程序停止的问题的解决方法

    IIS application pool recycling causes the problem that the timing execution program stops in application start

    Recently, I was working on a project, and I need to perform some operations in the program regularly. As a result, I found that from 7:00 to 8:00 every day to 9:00 the next day, the timing program is often not executing. Later, I learned that the application stopped because of IIS application pool recycling.

    2010-03-03

Latest comments