Upload Pdf Files to Ec2 Instance .net Core
Let'south imagine that nosotros have a .Internet Cadre Web API project in which we need to generate a PDF report. Even though it shouldn't suppose to be likewise hard to do something like that, we could end upwards losing likewise much time if we don't know how to practice information technology properly.
In this commodity, we are going to show how to use the DinkToPDF
library to hands generate PDF documents while working on the .Internet Core Web API project.
So, without farther ado, let's swoop right into the fun part.
- Global Error Handling in .Net Core Web API
- Implementing Action Filters in ASP.NET Core Web API
- ASP.NET Core Authentication with JWT and Angular
- Async Generic Repository Pattern in .NET Core
- Bones Tips and Tricks to Heave Productivity in Visual Studio
VIDEO: How to Hands Create a PDF Document in ASP.Internet Core Web API video.
You can download the source code for this article at Creating PDF Document Source Lawmaking.
In this post, we are going to comprehend:
- Bones Projection Preparations
- DinkToPdf Library Configuration
- Preparing Data for the PDF Document
- Saving the PDF Document on the Local Storage
- Showing a PDF Certificate in a Browser
- Using Existing HTML Page to Generate PDF Content
- Enabling Download Mode
- Update Projection For Deployment
- Conclusion
Basic Project Preparations
Let's starting time, by creating a brand new .NET Core 3.0 Web API project named PDF_Generator
:
Afterward the project creation, nosotros are going to modify the launchSettings.json
file to disable our browser to kickoff automatically:
{ "profiles": { "PDF_Generator": { "commandName": "Projection", "launchBrowser": false, "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
DinkToPdf Library Configuration
DinkToPdf
is a cross-platform oriented library which is the wrapper for the Webkit HTML to PDF library. It uses the WebKit engine to convert HTML to PDF.
It will let us to create a PDF document from our HTML cord that we generate in the .NET Core project, or to create a PDF document from an existing HTML page. Furthermore, nosotros tin download the created PDF certificate or save information technology on a certain location or return a new HTML page with the PDF content.
We are going to cover all these features in this article.
So, let's install the DinkToPdf
library first:
PM> Install-Package DinkToPdf
Or search for DinkToPdf
inside the Nuget Package window:
After the installation completes, we need to import native library files to our root projection. We can find those files in our source project in the NativeLibrary folder. Inside we will discover 2 folders 32bit
and 64bit
, so nosotros need to choose the appropriate library for our Bone. We are going to choose the files from the 64bit binder:
Finally, we need to annals this library with our IoC container in the StartUp
class:
public void ConfigureServices(IServiceCollection services) { services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools())); services.AddControllers(); }
To acquire in more item well-nigh service registration in .Cyberspace Cadre and how to keep Startup methods cleaner, you tin read the .Cyberspace Cadre Service Configuration.
Excellent.
We accept everything in place and we are ready to proceed.
Preparing Data for the PDF Document
In a real-globe project, we can collect data from the database or receive it from other API. Only for the sake of simplicity, nosotros are going to collect data for our PDF certificate from the local storage. Then we are going to create an HTML template and store information technology in the PDF document.
So permit's first create a new folder Models
and inside it the Employee.cs
file:
namespace PDF_Generator.Models { public course Employee { public cord Proper noun { get; set; } public string LastName { get; prepare; } public int Age { get; set; } public string Gender { get; set; } } }
To continue, we are going to create a new folder Utility
and two class files inside it DataStoage.cs
and TemplateGenerator.cs
. A complete structure should look like this:
Now, allow's modify the DataStorage.cs
file:
using PDF_Generator.Models; using System.Collections.Generic; namespace PDF_Generator.Utility { public static class DataStorage { public static Listing<Employee> GetAllEmployees() => new List<Employee> { new Employee { Proper name="Mike", LastName="Turner", Age=35, Gender="Male person"}, new Employee { Proper name="Sonja", LastName="Markus", Age=22, Gender="Female"}, new Employee { Name="Luck", LastName="Martins", Age=40, Gender="Male"}, new Employee { Proper noun="Sofia", LastName="Packner", Age=thirty, Gender="Female"}, new Employee { Proper name="John", LastName="Doe", Age=45, Gender="Male"} }; } }
In this lawmaking, we just render a list of employees that volition be displayed inside the HTML template.
HTML Template Generation
We desire to generate an HTML template, so we demand to modify the TemplateGenerator.cs
file:
using Organization.Text; namespace PDF_Generator.Utility { public static class TemplateGenerator { public static cord GetHTMLString() { var employees = DataStorage.GetAllEmployess(); var sb = new StringBuilder(); sb.Append(@" <html> <head> </head> <torso> <div grade='header'><h1>This is the generated PDF report!!!</h1></div> <table align='eye'> <tr> <th>Name</th> <thursday>LastName</th> <th>Age</thursday> <th>Gender</th> </tr>"); foreach (var emp in employees) { sb.AppendFormat(@"<tr> <td>{0}</td> <td>{i}</td> <td>{2}</td> <td>{3}</td> </tr>", emp.Name, emp.LastName, emp.Historic period, emp.Gender); } sb.Append(@" </table> </trunk> </html>"); return sb.ToString(); } } }
And so, we are fetching data from our static DataStorage
class and make full our template with information technology. The HTML template is nothing more than than a pure HTML code.
But we want to style our table and h1 tag likewise, and then allow'south create the new folder avails
and within it the new styles.css
file and change it:
.header { text-align: center; color: green; padding-bottom: 35px; } table { width: 80%; edge-collapse: collapse; } td, th { border: 1px solid greyness; padding: 15px; font-size: 22px; text-align: centre; } tabular array th { background-color: green; color: white; }
This CSS file is going to exist loaded later in the Controller class.
That is information technology, we have our HTML template to apply for the PDF creation. Now, nosotros tin continue to the Controller logic.
Saving the PDF Certificate on the Local Storage
In the Controllers
folder, we are going to create a new empty API controller PdfCreatorController
:
namespace PDF_Generator.Controllers { [Road("api/pdfcreator")] [ApiController] public form PdfCreatorController : ControllerBase { } }
Now, let's change the PdfCreatorController
course to support the creation and saving a PDF document to a local bulldoze:
using DinkToPdf; using DinkToPdf.Contracts; using Microsoft.AspNetCore.Mvc; using PDF_Generator.Utility; using System.IO; namespace PDF_Generator.Controllers { [Route("api/pdfcreator")] [ApiController] public course 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 Written report", Out = @"D:\PDFCreator\Employee_Report.pdf" }; var objectSettings = new ObjectSettings { PagesCount = true, HtmlContent = TemplateGenerator.GetHTMLString(), WebSettings = { DefaultEncoding = "utf-eight", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "avails", "styles.css") }, HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Folio [page] of [toPage]", Line = truthful }, FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Middle = "Report Footer" } }; var pdf = new HtmlToPdfDocument() { GlobalSettings = globalSettings, Objects = { objectSettings } }; _converter.Convert(pdf); return Ok("Successfully created PDF document."); } } }
Code Explanation
In the code above we first inject our registered Converter with the Dependency Injection inside our constructor by using IConverter
interface. And then we create two objects globalSettings
and objectSettings
and employ them as a configuration in the HtmlToPdfDcoument
holding. Finally, we convert our pdf configuration into a existent PDF Document on our local machine.
Now permit'southward talk well-nigh the GlobalSettings
and ObjectSettings
classes.
About the GlobalSettings Class
The GlobalSettings
class consists of the overall configuration backdrop for the PDF document. Nosotros utilise merely a couple of those properties to ready the color way, orientation, paper size, document championship, etc… simply if nosotros become to the implementation of the GlobalSettings
class we tin find more of those properties.
The Out property is very important if we want to relieve our files on a local auto. And so we need to set it to the path where nosotros desire our document to. If nosotros set the Out
property so we can use _converter.Convert(pdf);
to convert our document. We will see how this will modify once we try to show our PDF certificate inside a browser.
One more important note is that all the folders from the Out
path should be previously created or the conversion won't piece of work. And then in our example where we create a PDF document in the D:
drive in thePDFCreator
binder, we had to create the PDFCreator
binder prior to PDF document creation.
About the ObjectSettings Course
The ObjectSettings
class consists of the properties related to the contents of the PDF document. So, we can configure the visibility of the folio counter, formatting of headers and footers, the trunk content of our document (HtmlContent
holding) or the web settings for our document.
Of grade, these are not all of the configuration backdrop simply that's all we need for this article.
The HtmlContent
property is the very important property of this course. Information technology contains our generated HTML template and shows the chief body of a PDF document.
WebSettings
is pretty important as well, especially if we have an external CSS file for the styling as we exercise. In this property, we tin can configure the encoding of our certificate and provide the path to our CSS file. If we audit this property, we are going to find out more settings that nosotros can configure similar the background of a PDF certificate or if we should load images or what the minimum font size is, etc…
Inspecting Results
Let's start our app, open our browser and send a simple asking towards our PDF creator endpoint:
As a result, we have our document created in the PDFCreator folder:
And allow's inspect the content of the document:
That is crawly.
Nosotros tin can now continue on.
Showing a PDF Document in a Browser
If we want to bear witness our certificate in a browser instead, we tin configure that quite hands.
Start, nosotros need to remove the Out
holding from the globalSettings
object.
So instead of this blazon of conversion:
_converter.Catechumen(pdf);
We are going to use this blazon:
var file = _converter.Convert(pdf);
Why is that?
Well as we said if we use the Out
belongings then the file is sent to stdout and saved to our local machine. Simply without the Out
property, our output will be stored in a buffer. While converting we need to create a byte array and store it inside the file
variable.
Finally, we are using that file
variable and return it to the requester with a content type.
This is our CreatePDF()
method after modification:
[HttpGet] public IActionResult CreatePDF() { var globalSettings = new GlobalSettings { ColorMode = ColorMode.Color, Orientation = Orientation.Portrait, PaperSize = PaperKind.A4, Margins = new MarginSettings { Top = ten }, DocumentTitle = "PDF Report" }; var objectSettings = new ObjectSettings { PagesCount = true, HtmlContent = TemplateGenerator.GetHTMLString(), WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") }, HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true }, FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Middle = "Report Footer" } }; var pdf = new HtmlToPdfDocument() { GlobalSettings = globalSettings, Objects = { objectSettings } }; var file = _converter.Convert(pdf); return File(file, "application/pdf"); }
And this is the outcome:
Using Existing HTML Page to Generate PDF Content
We don't have to use our custom HTML template to generate PDF content, we can employ an existing HTML folio. The endeavour is minimal. All we take to do is to remove the HtmlContent
property and add the Folio
holding of the ObjectSettings
grade.
So instead of this code:
HtmlContent = TemplateGenerator.GetHTMLString()
let's add this lawmaking:
Page = "https://lawmaking-maze.com/"
And allow'south audit the result:
Enabling Download Mode
If we desire to enable the download characteristic for the PDF document we demand to change our render
statement in our action method. All we accept to do is only add the name of the file with its extension to the render
statement:
return File(file, "application/pdf", "EmployeeReport.pdf");
As a result, we are going to have our file downloaded:
And at that place it is.
Everything is working as information technology supposed to.
Update Project For Deployment
If we want to deploy this application, we have to make some changes. Let's practice that step by step.
Start, in the Utility
folder we are going to add a new courseCustomAssemblyLoadContext
and modify it:
internal class CustomAssemblyLoadContext : AssemblyLoadContext { public IntPtr LoadUnmanagedLibrary(cord absolutePath) { return LoadUnmanagedDll(absolutePath); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { render LoadUnmanagedDllFromPath(unmanagedDllName); } protected override Associates Load(AssemblyName assemblyName) { throw new NotImplementedException(); } }
After that, allow's modify the ConfigureServices
method in the StartUp
class:
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(); }
In hither, we are creating an instance of the CustomAssemblyLoadContext
class and just telephone call the LoadUnmanagedLibrary
method with the path of the libwkhtmltox.dll
file.
We need to practice one more thing. When nosotros publish our application, we need to take the libwkhtmltox.dll
file and the styles.css
file in the published directory. To ensure that, right-click on the dll
file in Solution Explorer
and choose properties
. For the Build Action
we are going to cull Content
and for the Re-create to Output Directory
, we are going to cull Re-create always
. We need to repeat these steps for the CSS file as well:
At present, all nosotros have to practise is to publish our application past following one of these tutorials or both of them:
.Cyberspace Core Application IIS Deployment
.Internet Core Application Linux Deployment
This is the result of the IIS deployment:
Conclusion
In this article, we have used the DinkToPdf library to create PDF documents while working with the .NET Core Web API project. We have created our PDFs in different ways to bear witness many unlike features of this library.
stapletonexciation91.blogspot.com
Source: https://code-maze.com/create-pdf-dotnetcore/
0 Response to "Upload Pdf Files to Ec2 Instance .net Core"
Post a Comment