![how to generate pdf report in asp net c# DEV Community](https://dev-to-uploads.s3.amazonaws.com/uploads/logos/resized_logo_UQww2soKuUsjaOGNB38o.png)
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
DEV Community
![how to generate pdf report in asp net c# Janki Mehta](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1113065%2Fd1b2d763-e5dc-47af-a115-b611b178e10a.jpg)
Posted on Nov 24, 2023
How to Create PDF Documents in ASP.NET Core
PDF generation is a common requirement for many web applications. ASP.NET Core provides several options for generating PDF documents directly from .NET code. In this article, we'll explore some of the main approaches for creating PDFs in ASP.NET Core apps.
We'll cover:
- Using built-in PDF generation support
- Third-party libraries like iTextSharp and PDFSharp
- Generating PDFs from HTML/CSS using libraries like PDFKit and Puppeteer Sharp
- Rendering to PDF on the server vs the client
- Sample code for a basic PDF generation scenario
By the end, you should have a good understanding of the different techniques available and how to get started generating PDFs from your ASP.NET Core applications.
Built-in PDF Support
The .NET Framework and .NET Core provide some basic built-in functionality for generating PDF documents programmatically without a third-party dependency.
The System.Drawing namespace includes classes like PdfDocument and XGraphics that allow creating PDF files pixel-by-pixel. You can draw text, images, vectors, and more onto a PdfPage and save the result as a PDF file.
An example:
This provides a basic building block but has limitations. Text/layout is rendered pixel-by-pixel so it may not scale or print well. There is also no support for things like vector graphics, tables, hyperlinks etc.
For richer PDF generation capabilities, third-party libraries are recommended.
Third-Party Libraries
There are a number of high-quality third-party .NET libraries for generating sophisticated PDF documents from code:
iTextSharp is one of the most full-featured and mature open source .NET PDF libraries available. It allows building PDF documents from scratch using elements like paragraphs, tables, images etc. Layout is handled separately from rendering so documents scale well.
PDFSharp is another popular open source .NET library. It uses a page-oriented model and the drawing API is similar to GDI+. This makes it easy to render to PDF from existing GDI/GDI+ code.
wkhtmltopdf
wkhtmltopdf is a command line tool that renders HTML/CSS to PDF using the Webkit rendering engine. It can be used from .NET code by launching the process. This allows generating PDFs from dynamic HTML/CSS content.
These are some of the most popular .NET PDF libraries. Each has its strengths - choose based on your specific requirements.
Generating from HTML/CSS
Another common approach is to generate PDF from HTML/CSS content since it's easy to work with. There are a few options for doing this in .NET:
PDFKit is a .NET library that uses the HTML rendering engine WebKit to convert HTML + CSS to PDF documents.
Puppeteer Sharp
Puppeteer Sharp is a .NET port of the Puppeteer Node.js library for controlling headless Chrome. It can render HTML to PDF using the Chromium rendering engine.
HTML to PDF Converter
This library uses the HTML Rendering engine in .NET to convert HTML markup to PDF.
Hence, these options allow rendering dynamic HTML/CSS content to high-fidelity PDF documents from .NET.
Server vs Client Rendering
There are two main approaches for generating PDFs - on the server or client-side:
Server-Side
- Generate PDF directly from server code using a library
- Respond with generated PDF file
- Server handles all processing
- Faster response for users
- No client-side dependencies
- Easier to implement
- More load on server
- No interactivity
Client-Side
Return HTML/data needed to render PDF Use client-side library like jsPDF to generate PDF in browser User downloads/gets link to generated file Pros:
- Reduces server load
- Allows for richer interactivity
- Slower initial response
- Requires client-side code/libraries So for simple static PDFs, server-side is better. For interactive/dynamic generation, consider a client-side approach.
Example Project To put this into practice, here is a simple ASP.NET Core MVC sample project that generates a PDF on the server:
This demonstrates:
- Creating a PDF using iTextSharp
- Adding simple content
- Writing PDF to a stream
- Returning PDF file result
With this approach, the server generates the PDF on request without any client-side processing required.
Final Thoughts
In this article, we covered several techniques for programmatically generating PDF documents from ASP.NET Core applications. Whether you need a simple solution or full featured generation, .NET provides many high quality options.
The key aspects discussed were:
- Leveraging built-in .NET PDF support
- Popular third-party libraries like iTextSharp and PDFSharp
- Generating PDFs from HTML/CSS content
- Rendering on server vs client
With the right approach, ASP.NET Core makes developing PDF generation capabilities straightforward. Choose the technique that best fits your specific application requirements.
Top comments (0)
![how to generate pdf report in asp net c# pic](https://media.dev.to/cdn-cgi/image/width=256,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8j7kvp660rqzt99zui8e.png)
Templates let you quickly answer FAQs or store snippets for re-use.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .
Hide child comments as well
For further actions, you may consider blocking this person and/or reporting abuse
![how to generate pdf report in asp net c# serhatbek profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F736549%2Fb0395982-1974-404e-a39f-ece90a728b88.png)
Vanilla JavaScript - Accordion
serhatbek - May 12
![how to generate pdf report in asp net c# omegaui profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F515594%2F878223a0-80fc-4253-9981-a4cc7a890e14.png)
Installing GitHub Repositories with this package manager
omega ui - May 12
![how to generate pdf report in asp net c# themuneebh profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1027328%2F500e9b92-46bf-44b5-b3a2-52d516d40799.jpg)
Being a "frameworker" is not bad, but...
Muneeb Hussain - May 12
![how to generate pdf report in asp net c# ridays2001 profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F447393%2F7b35efc7-9df5-4192-945c-9dec4c9eeb35.jpeg)
How to Build a Simple Instagram Clone with Next.js and Netlify
Riday - May 12
![how to generate pdf report in asp net c# DEV Community](https://media.dev.to/cdn-cgi/image/width=190,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8j7kvp660rqzt99zui8e.png)
We're a place where coders share, stay up-to-date and grow their careers.
![how to generate pdf report in asp net c# Code Maze](https://code-maze.com/wp-content/uploads/2021/02/Code-Maze-Logo-White-Text-Transparent-Small.png)
- Blazor WASM đ„
- ASP.NET Core Series
- GraphQL ASP.NET Core
- ASP.NET Core MVC Series
- Testing ASP.NET Core Applications
- EF Core Series
- HttpClient with ASP.NET Core
- Azure with ASP.NET Core
- ASP.NET Core Identity Series
- IdentityServer4, OAuth, OIDC Series
- Angular with ASP.NET Core Identity
- Blazor WebAssembly
- .NET Collections
- SOLID Principles in C#
- ASP.NET Core Web API Best Practices
- Top REST API Best Practices
- Angular Development Best Practices
- 10 Things You Should Avoid in Your ASP.NET Core Controllers
- C# Back to Basics
- C# Intermediate
- Design Patterns in C#
- Sorting Algorithms in C#
- Docker Series
- Angular Series
- Angular Material Series
- HTTP Series
- .NET/C# Author
- .NET/C# Editor
- Our Editors
- Leave Us a Review
- Code Maze Reviews
Select Page
How to Easily Create a PDF Document in ASP.NET Core Web API
Posted by Marinko SpasojeviÄ | Updated Date Jan 31, 2024 | 151
![how to generate pdf report in asp net c# How to Easily Create a PDF Document in ASP.NET Core Web API](https://code-maze.com/wp-content/uploads/2018/06/create-pdf-featured.png)
Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!
Letâs imagine that we have a .NET Core Web API project in which we need to generate a PDF report. Even though it shouldnât suppose to be too hard to do something like that, we could end up losing too much time if we donât know how to do it properly.
In this article, we are going to show how to use the DinkToPDF library to easily generate PDF documents while working on the .NET Core Web API project.
So, without further ado, letâs dive right into the fun part.
![how to generate pdf report in asp net c# Become a patron at Patreon!](https://code-maze.com/wp-content/plugins/patron-plugin-pro/plugin/lib/patron-button-and-widgets-by-codebard/images/become_a_patron_button.png)
- 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
- Basic Tips and Tricks to Boost Productivity in Visual Studio
VIDEO : How to Easily Create a PDF Document in ASP.NET Core Web API video.
You can download the source code for this article at Creating PDF Document Source Code .
In this post, we are going to cover:
Basic Project Preparations
Dinktopdf library configuration, preparing data for the pdf document, saving the pdf document on the local storage, showing a pdf document in a browser, using existing html page to generate pdf content, enabling download mode, update project for deployment.
Letâs start, by creating a brand new .NET Core 3.0 Web API project named PDF_Generator :
![how to generate pdf report in asp net c# Creating project for .NET Core Web API PDF Document Creation](https://code-maze.com/wp-content/uploads/2018/06/Creating-project-for-.NET-Core-Web-API-PDF-Document-Creation.png)
After the project creation, we are going to modify the launchSettings.json file to disable our browser to start automatically:
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 allow us to create a PDF document from our HTML string that we generate in the .NET Core project, or to create a PDF document from an existing HTML page. Furthermore, we can download the created PDF document or save it 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:
Or search for DinkToPdf inside the Nuget Package window:
![how to generate pdf report in asp net c# Nuget package .NET Core PDF Creation](https://code-maze.com/wp-content/uploads/2018/06/02-Nuget-Package.png)
After the installation completes, we need to import native library files to our root project. We can find those files in our source project in the NativeLibrary folder. Inside we will find two folders 32bit and 64bit , so we need to choose the appropriate library for our OS. We are going to choose the files from the 64bit folder:
![how to generate pdf report in asp net c# Native library files](https://code-maze.com/wp-content/uploads/2018/06/03-Native-Library.png)
Finally, we need to register 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 learn in more detail about service registration in .NET Core and how to keep Startup methods cleaner, you can read the .NET Core Service Configuration.
We have everything in place and we are ready to proceed.
In a real-world project, we can collect data from the database or receive it from other API. But for the sake of simplicity, we are going to collect data for our PDF document from the local storage. Then we are going to create an HTML template and store it in the PDF document.
So letâs first create a new folder Models and inside it the Employee.cs file:
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:
![how to generate pdf report in asp net c# Utility Folder Structure](https://code-maze.com/wp-content/uploads/2018/06/04-Utility-Folder-Structure.png)
Now, letâs modify the DataStorage.cs file:
In this code, we just return a list of employees that will be displayed inside the HTML template.
HTML Template Generation
We want to generate an HTML template, so we need to modify the TemplateGenerator.cs file:
So, we are fetching data from our static DataStorage class and fill our template with it. The HTML template is nothing more than a pure HTML code.
But we want to style our table and h1 tag as well, so letâs create the new folder assets and inside it the new styles.css file and modify it:
This CSS file is going to be loaded later in the Controller class.
That is it, we have our HTML template to use for the PDF creation. Now, we can continue to the Controller logic.
In the Controllers folder, we are going to create a new empty API controller PdfCreatorController :
Now, letâs modify the PdfCreatorController class to support the creation and saving a PDF document to a local drive:
Code Explanation
In the code above we first inject our registered Converter with the Dependency Injection inside our constructor by using IConverter interface. Then we create two objects globalSettings and objectSettings and use them as a configuration in the HtmlToPdfDcoument property. Finally, we convert our pdf configuration into a real PDF Document on our local machine.
Now letâs talk about the GlobalSettings and ObjectSettings classes.
About the GlobalSettings Class
The GlobalSettings class consists of the overall configuration properties for the PDF document. We use just a couple of those properties to set up the color mode, orientation, paper size, document title, etc⊠but if we go to the implementation of the GlobalSettings class we can find more of those properties.
The Out property is very important if we want to save our files on a local machine. So we need to set it to the path where we want our document to. If we set the Out property then we can use _converter.Convert(pdf); to convert our document. We will see how this will change once we try to show our PDF document 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 work. So in our example where we create a PDF document in the D: drive in the PDFCreator folder, we had to create the PDFCreator folder prior to PDF document creation.
About the ObjectSettings Class
The ObjectSettings class consists of the properties related to the contents of the PDF document. So, we can configure the visibility of the page counter, formatting of headers and footers, the body content of our document ( HtmlContent property) or the web settings for our document.
Of course, these are not all of the configuration properties but that’s all we need for this article.
The HtmlContent property is the very important property of this class. It contains our generated HTML template and shows the main body of a PDF document.
WebSettings is pretty important as well, especially if we have an external CSS file for the styling as we do. In this property, we can configure the encoding of our document and provide the path to our CSS file. If we inspect this property, we are going to find out more settings that we can configure like the background of a PDF document 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 request towards our PDF creator endpoint:
![how to generate pdf report in asp net c# Request for PDF creation](https://code-maze.com/wp-content/uploads/2018/06/Successfully-created-PDF.png)
As a result, we have our document created in the PDFCreator folder:
![how to generate pdf report in asp net c# Created document .NET Core PDF Creation](https://code-maze.com/wp-content/uploads/2018/06/06-Created-document.png)
And letâs inspect the content of the document:
![how to generate pdf report in asp net c# PDF Content .NET Core PDF Creation](https://code-maze.com/wp-content/uploads/2018/06/07-PDF-Content-1024x379.png)
That is awesome.
We can now continue on.
If we want to show our document in a browser instead, we can configure that quite easily.
First, we need to remove the Out property from the globalSettings object.
Then instead of this type of conversion:
We are going to use this type:
Why is that?
Well as we said if we use the Out property then the file is sent to stdout and saved to our local machine. But 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 = 10 }, 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, Center = "Report Footer" } }; var pdf = new HtmlToPdfDocument() { GlobalSettings = globalSettings, Objects = { objectSettings } }; var file = _converter.Convert(pdf); return File(file, "application/pdf"); }
And this is the result:
![how to generate pdf report in asp net c# PDF browser content .NET Core PDF Creation](https://code-maze.com/wp-content/uploads/2018/06/PDF-in-a-browser.png)
We donât have to use our custom HTML template to generate PDF content, we can use an existing HTML page. The effort is minimal. All we have to do is to remove the HtmlContent property and add the Page property of the ObjectSettings class.
So instead of this code:
letâs add this code:
And letâs inspect the result:
![how to generate pdf report in asp net c# PDF browser HTML page .NET Core PDF Creation](https://code-maze.com/wp-content/uploads/2018/06/New-web-page-in-pdf.png)
If we want to enable the download feature for the PDF document we need to modify our return statement in our action method. All we have to do is simply add the name of the file with its extension to the return statement:
As a result, we are going to have our file downloaded:
![how to generate pdf report in asp net c# PDF downloaded file](https://code-maze.com/wp-content/uploads/2018/06/10-PDF-downloaded-file.png)
And there it is.
Everything is working as it supposed to.
If we want to deploy this application, we have to make some changes. Let’s do that step by step.
First, in the Utility folder we are going to add a new class CustomAssemblyLoadContext and modify it:
After that, let’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 here, we are creating an instance of the CustomAssemblyLoadContext class and just call the LoadUnmanagedLibrary method with the path of the libwkhtmltox.dll file.
We need to do one more thing. When we publish our application, we need to have 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 choose Content and for the Copy to Output Directory , we are going to choose Copy always . We need to repeat these steps for the CSS file as well:
![how to generate pdf report in asp net c#](https://code-maze.com/wp-content/uploads/2018/09/properties-for-dll-file.png)
Now, all we have to do is to publish our application by following one of these tutorials or both of them:
.NET Core Application IIS Deployment
.NET Core Application Linux Deployment
This is the result of the IIS deployment:
![how to generate pdf report in asp net c#](https://code-maze.com/wp-content/uploads/2018/09/published.png)
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 show many different features of this library.
![how to generate pdf report in asp net c# guest](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I need an option to add images and custom fonts and CSS inline styles in html. And header and footer as customized way. I need seperate header for first page and other page in pdf. Is it possible to process my requirement. Please give me a suggestion. Here I used .net core 2.2 version asp.net Web API core 2.2.8
![how to generate pdf report in asp net c# Abhishek Singh](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
i am getting an extra blank page as i download. can you please suggest how to remove extra blank page from created pdf.
![how to generate pdf report in asp net c# rashid](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi @Team, Thanks for nice article and I have created pdf on localhost and it is working perfectly in localhost but when publishing to IIS getting following errors
Error NU1605: Detected package downgrade: System.IO.FileSystem.Primitives from 4.3.0 to 4.0.1. Reference the package directly from the project to select a different version. PB.Server -> DinkToPdf 1.0.8 -> NETStandard.Library 1.6.0 -> System.Console 4.0.0 -> runtime.win.System.Console 4.3.0 -> System.IO.FileSystem.Primitives (>= 4.3.0) PB.Server -> DinkToPdf 1.0.8 -> NETStandard.Library 1.6.0 -> System.IO.FileSystem.Primitives (>= 4.0.1)
I am using .net 6.
Could you please help me to solve this error
![how to generate pdf report in asp net c# Marinko SpasojeviÄ](https://code-maze.com/wp-content/uploads/2020/01/marinko-1x1-3-75x75.jpg)
Hello Rashid. I am not sure, but maybe this can help: https://stackoverflow.com/questions/50286990/error-nu1605-detected-package-downgrade
Hello @Marinko SpasojeviÄ , Thanks for your quick reply. I have gone through above link and now i am getting below error while publishing to IIS. I can successfully build application but getting error while publishing.
Error “dotnet.exe” exited with code 1
https://github.com/dotnet/sdk/issues/26061
above link helps me to solve mentioned error. Successfully published to IIS as well.
Thanks @Marinko SpasojeviÄ
![how to generate pdf report in asp net c# Dev](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
This article is very useful and I have tried it and successfully run/create the pdf on localhost but when I publish it it to IIS server it does not seem to work.
I am using the .Net 6.0 and also I have added the CustomAssemblyLoadContext funtion to the program.cs file.
Could you please guide me. where i am doing wrong.
Hello Dev. Well, there is no way for us to know what is going wrong only from the message you’ve posted. Also, I didn’t test this with .NET 6 but the IIS publish article is written on top of .NET 6 app, so I believe there shouldn’t be a lot of issues with this project.
Hi Marinko,
Thank you for your quick response.
Could you please explain why we need to change the
“ “launchBrowser” : false , “.
You don’t have. I like doing that during the development phase when I want to call my endpoints at a certain point and not when the app starts.
I have found the error and resolved it. Now the PDF creation method is working well.
Thanks. Really Helpful
![how to generate pdf report in asp net c# swadhinta](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
how can i make the pdf password protected.
![how to generate pdf report in asp net c# amin](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Thanks for this great tutorial! I have a problem implementing this. I have a database to be exported to pdf including images of the users in a table for each user. Images are saved locally and they are called by ImageName property for each user. only JPEG-Typed images are allowed. The problem is that a few pictures are shown and the others aren’t.
Thanks a lot ! It works !!!
![how to generate pdf report in asp net c# Amir Masood](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
very nice . the problem is that the package is old and has not been updated since 2017 . get issue with Docker . is there any newer package ?
![how to generate pdf report in asp net c# Fredrik](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi, thanks for the great solution!
I Implemented this in my solution and everything works perfectly locally. But whenever i deploy it to Azure Web App Service, the pdf-file changes format. Like everything is zoomed in and text is getting out of view. Do you have any experience with this?
![how to generate pdf report in asp net c# MarinkoSpasojevic](https://code-maze.com/wp-content/uploads/2020/01/marinko-1x1-3-75x75.jpg)
Hello Frederik. I didn’t publish this app on Azure Web App Service, but maybe you can check in the comment section since as I remember, there are a lot of comments regarding Azure deployment.
![how to generate pdf report in asp net c# Rohan Sampat](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I have successfully implemented this tool in my project but facing an issue where 20-25 files are converted and downloaded at a same time using this DLL’s then some HTML contents of those files are interchanged but when re-converted/re-downloaded then all is perfect. I m trying to find out the issue but no success yet. Can you help me in this.
Well, to be honest, there is no way for me to know why is this happening. I didn’t face situations like that one.
![how to generate pdf report in asp net c# DaniilTS](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Don’t you think that it would be much better to create dynamic pdf files using razor pages? It would be much more understandable. We just need to render page and get it as a string
Hello DaniilTS. It is completely up to you how do you want to implement your solution. We’ve shown here how things can be done and you can adapt it to your project. Of course, if anything can be generic/reusable it is always a better solution.
![how to generate pdf report in asp net c# Mohamed Hafez](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Great Article , it works fine with me on localhost but not working on iis, could you help me ?
![how to generate pdf report in asp net c# Marinko Spasojevic](https://code-maze.com/wp-content/uploads/2020/01/marinko-1x1-3-75x75.jpg)
Hello Mohamed. I am not sure what is wrong there. It should be working as you see that in the article. Also, maybe to go over the comments, a lot of publishing problems were solved there.
![how to generate pdf report in asp net c# Neil](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi. is there anyway to password encrypt the pdf stream before it is sent to the browser for download?
Well, I can’t say that there is no way, but not that I know of.
Ok so I assume this library is written on the wkhtmltopdf library? If so you will have to use another library to encrypt the stream/file?
![how to generate pdf report in asp net c# Dalia](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
But when i run on my local it work as well, but i deploy on azure, it throw error: The specified CGI application encountered an error and the server terminated the process. Please help to resolve it.
![how to generate pdf report in asp net c# Sajeesh C](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Not working when publish in Azure. Any idea? An error occurred while starting the application.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) System.Runtime.Loader.AssemblyLoadContext.InternalLoadUnmanagedDllFromPath(string unmanagedDllPath) BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
Could you check the comments on this post. I believe Andrei Iovan had the same issue and it was solved. It was explained how in his comment.
Thank you. It is worked! Another issue is how to specify out parameter in GlobalSettings object to download to local machine from server. In sample code, it was var globalSettings = new GlobalSettings { …………. Out = @”D:\PDFCreator\Order_Summary.pdf” }; If we download from local it is okay. But in server how to specify the local path?
![how to generate pdf report in asp net c# CRios](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi, how can I add an image as a background (watermark) to the generated pdf file?
![how to generate pdf report in asp net c# Marinko](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Well the first thing that comes to my mind is using a css. You can add a class on your image and add some opacity and all the stuff you want.
![how to generate pdf report in asp net c# Sneha Das](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I am trying to deploy in linux server in azure, after deployment, it gives me Application Error.
This is what I get in my output when i try to publish:
Installation of Web App Site extension Microsoft.AspNetCore.AzureAppServices.SiteExtension is in progress… Unable to install Web App extension Microsoft.AspNetCore.AzureAppServices.SiteExtension
![how to generate pdf report in asp net c# Andrei Iovan](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
DinkToPdf it works like magic on my local workspace! Really grateful for it. However, when I deploy it on the Azure Server, it does not work. After few hours of investigation I ask for your help, if you can give me a hand. The exception/error I get is this:
This happens when I start the IIS server – and I want to mention I got the error from the Event Viewer / Application Logs. The application won’t start at all, but just give this error.
Application: w3wp.exe CoreCLR Version: 4.700.20.36602 .NET Core Version: 3.1.7 Description: The process was terminated due to an unhandled exception. Exception Info: System.DllNotFoundException: Unable to load DLL ‘MY_PATHlibwkhtmltox.dll’ or one of its dependencies: The specified module could not be found. (0x8007007E) at System.Runtime.Loader.AssemblyLoadContext.InternalLoadUnmanagedDllFromPath(String unmanagedDllPath) at System.Runtime.Loader.AssemblyLoadContext.LoadUnmanagedDllFromPath(String unmanagedDllPath)
I want to mention I used the x64 version and my OS on Azure Server is also on 64 bit (windows), and I followed the setup steps described in this article very closely.
Did somebody have this issue and resolved it?
PS. I also tried to use 32 bits version of the library with no luck.
Any advise will be greatly appreciated! Thank you!
Hi. I didn’t deploy it on Azure, so I can’t be more of a help. But if I remember correctly, we had comments about similar or the same problem on this article, so maybe you can find something helpful here – in the comment section.
The solution for me was to install Microsoft Visual C++ Redistributable for Visual Studio 2015 as MONKS described below. Thanks everyone!
![how to generate pdf report in asp net c# muhammad Talha](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I am having the same issue on Centos Server Required Libraries are not found i have tried the CustomAssemblyLoadContext() too. anyone here who successfully run this on Centos server ? my project is not dockized and its Asp .net Core 3.1
![how to generate pdf report in asp net c# Limbani Akash](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
another language is not able to convert HTML to PDF. Like I try to convert HTML to PDF. In the HTML file Gujarati language is showing perfect. But after conversation that is showing like symbol. You can check image
![how to generate pdf report in asp net c# Alexandro](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hello, this deployment works in Windows, but if I run in Linux it says all the time that can’t load the library.
Hi Alexandro. I must say I am not sure why you have that error message. It is pretty clear that the library can’t be found, but I am not sure why. Have you tried checking somehow the path generated on the linux, maybe it targets something wrong… Maybe to search through the comments, I believe we had comments regarding the linux deployment.
I fixed moving the dll manually to bin folder, but… How can I tell in dotnet command to publish like VS does? because we have edited the build action and copy to output directory properties, that is saved to the project file.
I am glad you solved it. But I am not sure why dotnet command didn’t copy that file. To be honest I usually use the VS for the job.
Me too, but this time sysadmin gets the source and publish in the linux machine… Thanks.
![how to generate pdf report in asp net c# Xavier Martinez](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hello, this is really great in explaining it all. I am running into a little bump, when i insert a url for the Page attribute, I’m getting:
“http” does not exist in this current context.
I then tried the url for code maze and get a near identical error except it says https instead. I’m assuming I’m missing a library of sorts, but I’m not sure what. I looked it up but couldnt find anything. I did include the dll files. I’m able to produce the pdf from the htmlcontent, but not an outside url
Hello Xavier. The URL must be a string, so you have to enclose it in the quotation marks: Page = “https://code-maze.com”
Thank you for your prompt response. I have tried that before with the resulting pdf being empty. I’m assuming this means it either didnt resolve and pull from the url or I’m missing a service to keep it from pulling. When I looked into that issue, I got references for web requests which didn’t align with the dinktopdf usage. For context, I’m running with IIS which results in a localhost that outputs a downloadable with return file. I rewrote global settings and object settings to match the above tutorial as well, if it helps. I understand this is a stackoverflow or github forum question, but any help is appreciated.
Update: There wasn’t a missing service. I removed the websettings, header and footer as the page is already formatted. It returned exactly what I needed. I suspect it’s due to a possible overwrite of some blank html content since websettings and such were used.
Thank you, anyways!
![how to generate pdf report in asp net c# isaac](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
This is great. I came across this website and I’m really impressed with the solution I got. Very easy to understand and implement. But please, how do I insert a Logo at the top of my PDF generated. Thank you.
As I said, your explanation of how to use your library is seamlessly easy to understand. I went to the bottom of this page and I found the solution to my question.
In the case of my project, MVC Core 3.0, I derived my image path as below:
I applied it and it worked. Thank you very much.
Please, do you have a complete online tutorial of the PDF converter library?
Hello Isaac. There is one more thing you could do if you want to use the Logo in the header:
HeaderSettings = { FontName = “Arial”, FontSize = 9, Line = false, HtmUrl = @”……header.html”},
So, you can create an html file and inject it in the HeaderSettings.
But I am so glad you solved it on your own. And one more ting, this is not my library, or our library (Code Maze), I am just showing how this library can be used to generate PDF. You can look at this link: https://github.com/rdvojmoc/DinkToPdf
Marinko, thank you.
![how to generate pdf report in asp net c# Zoltan Halasz](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi! I am using this PDF creation method in my web app (asp.net core 3.1) But when I deploy to Azure, I have the error:
Exception Info: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (0x8007000B) at System.Runtime.Loader.AssemblyLoadContext.InternalLoadUnmanagedDllFromPath(String unmanagedDllPath) at System.Runtime.Loader.AssemblyLoadContext.LoadUnmanagedDllFromPath(String unmanagedDllPath) at AdminTool.PDFUtility.CustomAssemblyLoadContext.LoadUnmanagedDll(String unmanagedDllName) in D:DotnetAdminToolAdminToolPDFUtilityCustomAssemblyLoadContext.cs:line 18 at AdminTool.PDFUtility.CustomAssemblyLoadContext.LoadUnmanagedLibrary(String absolutePath) in D:DotnetAdminToolAdminToolPDFUtilityCustomAssemblyLoadContext.cs:line 14
Hello Zoltan. Well, I didn’t have a chanse to deploy this app on the Azure but maybe this link can help you: https://github.com/rdvojmoc/DinkToPdf/issues/5 . I can see a lot of advices there even Azure related.
Thanks for replying to my question. If I deploy to another IIS host (interserver.net), it works fine as it is 64 bit server. Using the 32 bit library, at least it works on Azure too, but when I load the pdf document on azure, I get characters like [][][][] or so instead of normal letters on the pdf file. Maybe you know something I missed?
Hey Zoltan. I’m glad that helped. Regarding your issue, please read the comment from the NELSON FIGUEROA. He had a similar problem and solved it by installing additional stuff to his machine, so maybe you can find a solution for your problem as well. It seems to me that your machine is missing a font support or anything like that.
Thanks… it seems he has a Linux example, whereas at Azure is Windows, with 32 bits (the F1 tier). And the machine has already the arial font which I used in the html before conversion. So… I don’t know. The thing works perfectly on a 64 bit server, Interserver.net.
Ok, my solution was to use a 64 bit instance of App Service with Asp.Net core 3.1 on Azure. Now it works, as the library used locally is for 64 bits (works on my cheap asp.net host also). The 32 bit version did not work on my Azure account.
![how to generate pdf report in asp net c# Sanjiv](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Can we use this for merging the pdf? If yes then share the sample code
Can we use this DinkToPdf to merge pdf files? If yes then please share the sample code
![how to generate pdf report in asp net c# William Hambly](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Marinko, this is such a great article. Precise & complete. Well done. Thank you! Do you have a “buy me a coffee” page?
Thank you very much William. I am so glad to hear that. I hope you like our other articles as well. And yes we do have buy us a coffee page, but it’s just not promoted on the site: https://code-maze.com/buy-us-a-coffee/ . We’ve published a book as well so, fell free to chek it out ( https://code-maze.com/ultimate-aspnet-core-3-web-api/ ) . Anyhow, thank you very much for your support. It means a world to us. Best regards and stay safe and healthy.
![how to generate pdf report in asp net c# Vastag Atila](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
HI Great article. But I encountered on a problme on Debian 9. I changed CustomAssemblyLoadConext to load the .so file like this string filePath = $@”{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}libwkhtmltox.so”; Now it is reading the linux library. But when I hit the controller to get a pdf file I got an error:
Unable to load shared library ‘Shell32.dll’ or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libShell32.dll: cannot open shared object file: No such file or directory
![how to generate pdf report in asp net c# Fatmaa Gomah](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Kindly i need to repeat table header in all pages if table content more than one page
![how to generate pdf report in asp net c# Premtim Ramadani](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Did you find a solution for this, I have the same problem!
![how to generate pdf report in asp net c# Tim Stutzman](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Great post! I have implemented and it works great! One question, I have received a request from a user to place a barcode on the generated PDF. Using your method for implementing do you have any advise on how I could implement a barcode font and display on the PDF? Any help is appreciated!
Hello Tim. I haven’t added a bar code in the project but, there are some libraries you can google out and apply them through the java script. Again, I haven’t done anything similar but it might work.
Hi Marinko. Thank you for your response. I thought of using JS, but that is where I am struggling. I do all my string manipulation and building in the TemplateGenerator.cs class which I can’t use JS libraries I have found. They are built for front end views which in my project doesn’t use the view to build the PDF. Any other suggestions?
Well if JS is no go for you, you can trie some of the libraries for ASP.NET Core. There are those as well. Again, I haven’t been using this feature, but different libs can be googled out.
![how to generate pdf report in asp net c# Abhijeet Zade](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Worked like a charm on my local machine , but when I deployed on azure app service it is showing 502 error
![how to generate pdf report in asp net c# Sheikh Sayed](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
if i want to make an image to pdf , what do in need to do ?
Hello Sheikh Sayed. This is not a problem. Just create another folder Images in your solution and place some picture inside. Than in the code where we generate the HTML content add these lines:
My test result was like this:
![how to generate pdf report in asp net c# comment image](https://uploads.disquscdn.com/images/514e2106b8830d60703b51436e321d2fce79c5f914ef73703177c826bfce2e1d.png)
As you can see, the picture is right below the table.
Best regards.
![how to generate pdf report in asp net c# Shawki Sukkar](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Thanks nice article and hope it’s will work, I am getting:
System.DllNotFoundException: ‘Unable to load DLL ‘libwkhtmltox’ or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)’ but I have copied the files to the solution
sorry I saw the solution just I have to change the debug profile becasue it was IIS
That is correct. Best regards.
![how to generate pdf report in asp net c# NELSON FIGUEROA](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I am sorry, but as stated in article, I have tested this locally and on IIS. Didn’t use it anywhere else, so, your error is strange to me as much as it is strange to you. My guess is that Amazon machine is lacking a support for something required by your PDF doc, but what… I really don’t know.
Hi, thank you. I found the solution, i just had to install this in my centos michine First I had to enable an extra repository: sudo amazon-linux-extras install epel afther sudo yum install urw-fonts libXext openssl-devel I hope it helps someone else.
Thank you Nelson, for sharing the solution with us.
![how to generate pdf report in asp net c# David Tantuo](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Your article is excellent on the PDF generation using DinkToPdf. It works perfectly in my development environment. However after deploying to Azure, I am getting a page not Found Error. I am using the returning as follows : objectSettings.Page = “https://localhost:44316/Sales/OpenQuotes/IndexPdf/” + id ; var file = _converter.Convert(pdf); return this.File(file, “application/pdf”);
Hello David. I haven’t worked with azure, but just a question: Are you sure that localhost:44316 is visible once deployed on Azure? Because the error is clear enough that the page can’t be found. Again, this is just a question, as I said, I am not familiar with the Azure deployment.
![how to generate pdf report in asp net c# Mika Gouzee](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi ! Thanks for the article, very useful.
I have an issue tho : it seems I can’t use every properties of CSS with this, as grid-display is totally ignored.
Do you have any idea/hints as to why and/or how I could correct this ?
Hello Mika. I didn’t use CSS grid with this project, but have you tried to use css-flex system? Maybe that will work.
No, I haven’t tested any other way yet, I’m not a CSS expert at all, which is also why I tested grid, since it seems easy.
Do you know how it works under the blackbox of dinkto ? Is it possible that wkhtml for instance uses IE to render the HTML, which would make the CSS have to be compatible with IE instead of the latest browsers ? My most basic css commands (like background-color) are executed, so I know the file is read, but apparently it has issue generating the template as it should.
Hello Mika. I am sorry, but I am not familiar with that at all. Never gone that deep into the dll. But I can only tell, related to CSS complexity, that css flex is not complex at all, in other words it is pretty easy to use, so you can try it for sure.
![how to generate pdf report in asp net c# smartgardenvietnam](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Thanks for your article.
This is my site: https://oneteamapp2019.azurewebsites.net/api/values/export-pdf?id=112eb418-5c5b-451f-1332-08d6add9607d
Regard…
Hello. I haven’t deployed this app on azure, and don’t know much about that part, so can’t help you with that, sorry. But maybe any of our readers did it, and they could help you. All the best.
Hello. I havenât deployed this app on azure, and donât know much about that part, so canât help you with that, sorry. But maybe any of our readers did it, and they could help you. All the best.
Thanks for your help.
I fixed my bug when i create html file, but when render to pdf, my content not correctly.
Please check my site: https://oneteamapp2019.azurewebsites.net/api/values/export-pdf
This is my html code:
public static string GetHTMLString() { var sb = new StringBuilder(); sb.Append(@”
This is the generated PDF report!!!
return sb.ToString(); } }
How can i fix that?.
This code looks fine. But I see your result is not. So maybe if you can share your code with us, then I can have a better look. If you have a good result on your local machine, then it is maybe something on the azure side. I really can’t tell more for now.
![how to generate pdf report in asp net c# David Äubela](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hello and thank you for a great article! I did follow your tutorial but I get the following error:Qt: Could not initialize OLE (error 80010106). This happens while executing converter.Convert(pdf) Now, I don’t even know where to start. I see alot of people with the same error regarding generating PDFs and I could use your help. Thanks in advance
Hello David. I would suggest to look at our source code and to compare it. If you can’t solve it, you can send us your project, so we could look at it. This has to work, it is tested by many users, as you can see from the comments, but we can check it. All the best.
Thank you for a fast reply. I worked on this a little bit and it’s strange. I choose to save the generated PDF on disk and it actually works. However, the project console contains the before mentioned error. I am currently testing different PDF generation options and have not tested it in live environment. This is actually my concern. The solution that you posted is pretty simple and straightforward and I think I implemented it ok. Unfortunately, my final solution won’t be able to follow your setup completely (the return types will differ) and that is the only change I had. Also, I haven’t made another configuration in launch.json. But those should be the only 2 differences.
Hi David. Well, as I can recall, I had the same error when I was starting this project, but it was due to the wrong IConverter registration (can’t remember exactly what I did wrong, but I think it was about that). Once I registered it as a singleton inside the IOC, the error message disappeared. Again, I am not 100% sure but I believe it was something like that.
Hmm, yeah, I read through the comments and I see most people made that mistake. However, it seems I didn’t. Although, I do have a slight difference: my IConverter is called in another project, and not in WebApi. I’m using it in Business, which WebApi is using. Could that be the problem? Should I register it in some other way? I already tried to copy the Dink files in both WebApi and Business roots, but still the same.
Well now, it is really strange. Have you tried, just for example sake, to create a test ptoject and to implement pdf logic, just to see whether the error is going to repeat. I really can’t figure out what is wrong with that.
![how to generate pdf report in asp net c# MONKS](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I struggled with the “Unhandled Exception: System.DllNotFoundException: Unable to load shared library ‘/app/libwkhtmltox.dll’ or one of its dependencies” error for much longer than I’d like to admit. The problem was not in the code, but on the server. This post illustrates the solution that worked for me. All I did was install MS Visual C++ 2015 redistributable package on the server. The dependencies were part of this distribution.
This was the solution for me also. Thanks mate!
![how to generate pdf report in asp net c# Srinivasan](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
I am trying to deploy this code in cloud (PCF) and getting dll not found error. “Unhandled Exception: System.DllNotFoundException: Unable to load shared library ‘/home/vcap/app/libwkhtmltox.dll’ or one of its dependencies.” Has anyone come across this scenario?
![how to generate pdf report in asp net c# CPTribbon yu](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi, if I will deploy in a linux ec2 instance which runs on ubuntu, do I need to add this CustomAssemblyLoadContext and in the configure services? and if so, do i include the .dll or .so file of the library. thank you and ill wait for your reply.
Hello. I didn’t try to deploy it on Linux, but I think you have to use the CustomAssemblyLoadContext and to point to dll file. (But please take this with reserve because, as I said, I didn’t do it). But try it, and if it works, be so kind and write your experience in the comment, it can help a lot to other readers and me too đ
![how to generate pdf report in asp net c# Joe_Frezza](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Tried this and it works just fine, but (this may be a dumb question…), why is it that if I type in the address bar in the browser localhost:5000/api/pdfcreator it works as expected, while if I type localhost:5000/api/pdfcreator/CreatePDF (i.e. appending the controller’s action) it returns an error? The reason is: I would like to call the action (and possibly create different actions in the same controller as well) and provide parameters to them in order to generate different reports and formatting depending on the parameters. What would be the proper way of dealing with this scenario? Thanks
Helo Joe. Thank you for reading this article. Let me answer your question. To enable such a route you need to create a proper [HttpGet] attribute for another action. So the current action (CreatePDF) is on the localhost:5000/api/pdfcreator route. But if you want another one you must write something like this:
[HttpGet(“createpdf”)] public IActionResult CreatePdf1() { //code goes here }
and call it with http:\localhost:5000apipdfcreatorcreatepdf.
And if you have params maybe, you must include them to the route and HttpGet attribute as well.
If you are not so familiar with routing and Actions in .NET Core, I recommend you reading our .NET Core tutorial, it will help you a lot for sure: http://34.65.74.140/net-core-series/
All the best.
![how to generate pdf report in asp net c# Paul](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Are there any known issues with using POST instead? I have a report that is dynamically generated on the front-end which then the HTML of that is sent to the Controller (via HttpPost). But when I return the file or stream back to the front-end, I will receive a blank (but correct number of pages) PDF file with a corrupted title. Using the ‘out’ property with POST works fine though.
Took a while (since one issue just led to another), but I got it. I ended up having to create 2 different POST controllers, one to store the HTML string (since it was too long to be sent through XMLHTTPRequest) and the other returns the generated PDF file. In the Javascript I have an AJAX call to the ‘StoreHtmlController’ which sends the HTML as a string. OnSuccess of that AJAX, it then calls the other controller through XMLHttpRequest and the file is returned to the front end without corruption.
![how to generate pdf report in asp net c# Byron](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Great Article using it. Doing Great. I have been asked to create a second page for all the pdf’s. Would you be willing to assist with how to create a second page – It is fixed data on the second page?
Hello Byron. First of all, thank you for commendation it is always nice to read that kind of comments from the reader. About your task, I am not sure that I got it quite right. Do you have the content on the first page and more space to fill on that page but now you want to start another page and to leave the first one as it is? Another question: is your content on the first page fixed size or it can vary in length?
Marinko – Thanks for your response. The situation is I have data that doesn’t fill the whole first page, but that’s OK. However, the client wants to provide fixed information about a training class as a second page on all the pdf’s that take up less than a page. This they want so they can print the a 2 sided document. I hope this clarifies your question. Thanks.
Great Article. It works ideal for me. I now have been tasked with adding a second page to each .pdf. Could you assist with this requirement or point me to an article on how to add a second page to the pdf?
Hi Byron. I have replied on your previous comment. Check it out.
![how to generate pdf report in asp net c# Ramprit Sahani](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Thanks You should move this libwkhtmltox.dll in nuget package. Because it’s very hard to keep in separate file.
Can you move this
![how to generate pdf report in asp net c# Fasil Marshooq](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
HI Ramprit,
It’s packed into one Nuget here https://www.nuget.org/packages/Bee.HtmlToPdf/
![how to generate pdf report in asp net c# Baskar Ram](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Works as explained in the article. Thanks @disqus_GtEeIZUUDN:disqus.
Have to add below code and CustomAssemblyLoadContext.cs file to solve “”Unable to load DLL ‘libwkhtmltox’ or one of its dependencies” error.
var context = new CustomAssemblyLoadContext(); context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), “libwkhtmltox.dll”)); services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
have you tried to deploy in linux? do i set the path directory file to point to the .dll file or .so file? thanks
![how to generate pdf report in asp net c# ost1m1ron -](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hello, can you help me in my project need qr code in pdf file. i dont have idea how to do it. Need dinamic create in pdf qr code. P.S. sorry my english, i hope you understand me and can help me )
I apologize for my impulsivity, but I think to turn the qr code into base64
For this, try to search little bit on the internet, I haven’t work with such a task.
it possible?
thank you for link ti github
how i can to remove footer and header ?
Just remove HeaderSettings and Footer ones from the object settings. That is all.
![how to generate pdf report in asp net c# Alvaro Lafuente](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Great article. Thank you! it is possible know the pdf number of pages from code?
Thank you Alvaro. About the page count, I think there is no possibility to know that or at least not that I know. You pages are created during run-time so I don’t know how we could know that. Maybe we can perform some calculations, to count the length of the byte array and then approximately to calculate number of pages… So, I am sure that some kind of algorithm can be written but there is no such a property or method to calculate that for you (at least I don’t know for such a thingy).
![how to generate pdf report in asp net c# arthur t](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Great article. Thank you!
You are very welcome. I hope you will find our other articles useful as well. All the best.
![how to generate pdf report in asp net c# Mateusz](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Great article! I case someone is develping project on Windows machine and deploying on Linux Docker and receiving an error like “Unhandled Exception: System.DllNotFoundException: Unable to load shared library ‘/app/libwkhtmltox.so’ or one of its dependencies”.
Try to follow this answer: https://github.com/rdvojmoc/DinkToPdf/issues/3#issuecomment-319008350 , so basically add RUN [“apt-get”, “update”] RUN [“apt-get”, “-y”, “install”, “libgdiplus”] to dockerfile. It helped me.
Hello Mateusz. First of all, thank you very much for reading this article. Especially, thank you so much for that information you provided in your comment. It is quite normal that we can’t cover all the cases in a single article, thus your comment has a great importance, not only for us but to all who read this article. One more time, thank you very much. All the best.
No problem! I’ve spent a few hours searching for solution so I decided to save other developers’ time đ
did you follow the CustomAssemblyLoadContext and in the configure services? did you point it to the dll file or the .so? i did not add those yet. thanks
Yes, of course I followed. But beacause I run the app on Windows during development and in release mode I run it on Linux container, I added some lines like these #if DEBUG context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), “libwkhtmltox.dll”)); #else context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), “libwkhtmltox.so”)); #endif
CPTribbon yu I got an error on Debian 9. Did you had this kind of error:
Unable to load shared library ‘Shell32.dll’ or one of its dependencies.In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libShell32.dll: cannot open shared object file: No such file or directory
![how to generate pdf report in asp net c# Ankusha Rana](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Thanks for giving such useful information on show how to use the Dink To PDF library to easily generate PDF documents while working on the .NET Core Web API project.
You are very welcome Ankusha Rana. Hope you enjoy our other articles as well.
![how to generate pdf report in asp net c# MD ISMAIL](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi, Thanks for the post we are able to generate pdf from html but after converting we are getting a masked text saying “Word to PDF Converter Converted By BCLTechnologies”, how to remove this. do we need to purshase licence for it?
![how to generate pdf report in asp net c# AWhiteCat](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
How could this be implemented on a real server(IIS or nginx)? It needs permission, so i’m curious how I would go about it, especially on linux?
Hello AwhiteCat. Well I haven’t deployed this app to the real server. But we have two articles about deployment .net core app to the IIS and Linux (nginx) so if you want you can read them here: http://34.65.74.140/net-core-web-development-part16/ and http://34.65.74.140/net-core-web-development-part17/ , and then you can help us all with your experience đ
I got it to work on IIS on a shared hosting site(webwiz). I published the app as self-contained. I also used the 32bit .dlls. Then I turned off managed code (“no managed code”) in their webadmin panel for the site. I will try on linux next week or so
![how to generate pdf report in asp net c# Gustavo Alejandro](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hi. Did it work for you? I tried to implement it on IIS, but the PDF isn’t returned by the api, unfortunately. Though it works fine on visual studio IIS express.
Hello Gustavo, I just want to notify you that I have updated this article with the IIS deployment, so feel free to try it and reply to us as well if you wish so.
Hello AWhiteCat, I just want to notify you that I have updated this article with the IIS deployment, so feel free to try it and reply to us as well if you wish so.
Where do i find the native library DLL’s?
![how to generate pdf report in asp net c# Marinko](https://code-maze.com/wp-content/uploads/2020/01/marinko-1x1-3-75x75.jpg)
Hello Leuan. On the top of this article, you can find a link to the source code. It leads to our GitHub repository and there you will find the NativeLibrary folder. Inside it you can find zipped native files.
@disqus_GtEeIZUUDN:disqus Thanks for the fast response. I have now added the DLL’s to the root of my project. But I’m still getting the following error “Unable to load DLL ‘libwkhtmltox’ or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)”
Hello Leuan. This seems to me as the IOC configuration problem. Have you registered your library inside the IOC as a singletom? This line of code: services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
All you have to do is to install DinkToPDF, to copy dll’s to the root of your app and to register it inside the IOC.
If you still have the same problem, you can upload your code, and then we can check it out. Of course, you can always compare my code with yours as well.
@disqus_GtEeIZUUDN:disqus Thanks but ye, i have compared it and its largly the same. Here is a link to the repo – https://github.com/IeuanWalker/PdfWebApi
I will look at it in more detail, and get you back. I see you have implemented Swagger but that shouldn’t be the problem. It can’t find the dll file even though it is in the root of your project. For now, don’t know what is the problem. But I just took a glance at it, today will look in more detail.
Great, thank you đ
Well, I am just typing you. I have gone through entire article on completely new machine (not my own), and everything works fine. So just for my clarification, there is nothing wrong with the code in article. I am sorry to tell you that I can’t find what is wrong in your code. My suggestion is to start again, but to follow complete example form the article, and then if that works, to modify and add your own features. As I said, this works for me on two different machines, so something is scrambled in your project but I can’t find it. If you start it again, I would appreciate your reply is it working or not.
![how to generate pdf report in asp net c# Eric Wo](https://code-maze.com/wp-content/uploads/2024/05/default-avatar.jpg)
Hey Leuan, in case you are still struggling with this: I had the exact same problem but was able to solve it after all.
What you want to to is adjust some settings: (right-click) Project -> Properties -> Debug. There set the “Profile” to PDF_Generator (‘cos default is IIS Express). Finally, toggle the dropdown right to the green play button in the navigation and change “IIS Express” to “PDF_Generator”. That should do the trick. Open your browser at the defined localhost port and there the path “api/pdfcreator”.
Hope this helps, otherwise reply to my comment! đ
![how to generate pdf report in asp net c# wpdiscuz](https://code-maze.com/wp-content/plugins/wpdiscuz/assets/img/plugin-icon/icon_info.png)
Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .
- United States
- United Kingdom
![how to generate pdf report in asp net c# Joydip Kanjilal](https://images.idgesg.net/images/article/2017/06/joydipkanjilal-100724852-byline.jpg?auto=webp&quality=85,70)
By Joydip Kanjilal , Contributor, InfoWorld |
How to create PDF documents in ASP.NET Core 5
Take advantage of the dinktopdf and wkhtmltopdf libraries to generate pdf documents from html templates in asp.net core 5..
![how to generate pdf report in asp net c# How to create PDF documents in ASP.NET Core 5](https://images.techhive.com/images/article/2014/05/paper-airplane-149083888-100265467-large.jpg?auto=webp&quality=85,70)
When working on web applications in ASP.NET Core 5 or ASP.NET Core MVC 5, you will often need to generate and display PDF documents to the user. Such documents might include invoices, salary slips, reports, etc.
This article presents a discussion of how we can use the DinkToPdf library to generate PDF documents in ASP.NET Core 5 applications. DinkToPdf is a .NET Core P/Invoke wrapper to the wkhtmltopdf library , which renders HTML to PDF (and other formats) using the Qt WebKit rendering engine.
To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you donât already have a copy, you can download Visual Studio 2019 here .
Create an ASP.NET Core MVC 5 project in Visual Studio 2019
First off, letâs create an ASP.Net Core project in Visual Studio 2019. Following these steps should create a new ASP.NET Core MVC 5 project in Visual Studio 2019.
- Launch the Visual Studio IDE.
- Click on âCreate new project.â
- In the âCreate new projectâ window, select âASP.NET Core Web App (Model-View-Controller)â from the list of templates displayed.
- Click Next.
- In the âConfigure your new projectâ window, specify the name and location for the new project.
- Optionally check the âPlace solution and project in the same directoryâ check box, depending on your preferences.
- In the âAdditional Informationâ window shown next, select .NET 5.0 as the target framework from the drop-down list at the top. Leave the âAuthentication Typeâ set to None (default).
- Ensure that the check boxes âEnable Docker,â âConfigure for HTTPS,â and âEnable Razor runtime compilationâ are unchecked as we wonât be using any of those features here.
- Click Create.
Following these steps will create a new ASP.NET Core MVC 5.0 project. Weâll use this project in the subsequent sections in this article.
Install the DinkToPdf NuGet package
The DinkToPdf library is available as a NuGet package. To get started working with the DinkToPdf library, you must install it from NuGet. You can either install it via the NuGet Package Manager or by using the following command at the NuGet Package Manager Console window.
Once youâve installed this library, you can verify the installation by locating the DinkToPdf.dll library as shown in Figure 1 below.
Figure 1. DinkToPdf NuGet package installation.
Register the DinkToPdf library with the IoC container
Now that the DinkToPdf library has been installed on your project, you must register the library with the built-in IoC container. To do this, you can write the following code in the ConfigureServices method.
To make the above code snippet work, you should include the following libraries in the Startup.cs file:
Create a ReportService class in ASP.NET Core 5
Now that DinkToPdf has been configured, the next step is to create the ReportService class. This class will contain the logic for generating the PDF document. Weâll first create an interface named IReportService that will be extended by the ReportService class. Create a file called IReportService.cs and enter the following code.
The ReportService class extends the IReportService interface and implements the GeneratePdfReport method as shown below.
Note how the IConverter instance has been injected using constructor injection.
Implement a GeneratePdfReport method in ASP.NET Core 5
The following code snippet shows the GeneratePdfReport method that contains all of the necessary code for generating the report.
Create a ReportController class in ASP.NET Core 5
While the GeneratePdfReport method of the ReportService class builds the report data as a byte array, the actual report file is created in the ReportController class as shown in the code listing given below.
When you run the application and hit the HttpGet endpoint of the ReportController class, a report file will be created and downloaded in your computer. The generated report from our example is shown in Figure 2 below.
Figure 2. Our example PDF report.
There is no built-in reporting framework in ASP.NET Core 5 or ASP.NET Core MVC 5, so if we want to generate PDF documents, weâll need to take advantage of a third-party library. DinkToPdf is one of many such libraries available.
DinkToPdf is a .NET Core wrapper for wkhtmltopdf that can be used to convert an HTML template to a PDF document. You can learn more about DinkToPdf on GitHub .
How to do more in ASP.NET Core:
- How to use immutable objects in ASP.NET Core MVC 5
- Dependency injection best practices for ASP.NET Core MVC 5
- How to use security headers in ASP.NET Core MVC 5
- How to handle unknown actions in ASP.NET Core 5 MVC
- How to overload action methods in ASP.NET Core 5 MVC
- How to use multiple implementations of an interface in ASP.NET Core
- How to use IHttpClientFactory in ASP.NET Core
- How to use the ProblemDetails middleware in ASP.NET Core
- How to create route constraints in ASP.NET Core
- How to manage user secrets in ASP.NET Core
- How to build gRPC applications in ASP.NET Core
- How to redirect a request in ASP.NET Core
- How to use attribute routing in ASP.NET Core
- How to pass parameters to action methods in ASP.NET Core MVC
- How to use API Analyzers in ASP.NET Core
- How to use route data tokens in ASP.NET Core
- How to use API versioning in ASP.NET Core
- How to use Data Transfer Objects in ASP.NET Core 3.1
- How to handle 404 errors in ASP.NET Core MVC
- How to use dependency injection in action filters in ASP.NET Core 3.1
- How to use the options pattern in ASP.NET Core
- How to use endpoint routing in ASP.NET Core 3.0 MVC
- How to export data to Excel in ASP.NET Core 3.0
Next read this:
- Why companies are leaving the cloud
- 5 easy ways to run an LLM locally
- Coding with AI: Tips and best practices from developers
- Meet Zig: The modern alternative to C
- What is generative AI? Artificial intelligence that creates
- The best open source software of 2023
- Microsoft .NET
- Software Development
Joydip Kanjilal is a Microsoft MVP in ASP.NET, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .NET and related technologies.
Copyright © 2021 IDG Communications, Inc.
![how to generate pdf report in asp net c# Dot Net Tutorials](https://dotnettutorials.net/wp-content/uploads/2019/09/cropped-dotnettutorials.png)
How to Generate PDF in ASP.NET Core MVC
Back to: ASP.NET Core Tutorials For Beginners and Professionals
In this article, I will discuss How to Generate PDFs in ASP.NET Core MVC Application with Examples. Please read our previous article discussing How to Import Excel Data to a Database in an ASP.NET Core MVC Application with Examples. Letâs continue with the application we worked on in previous articles.
Generate PDF in ASP.NET Core MVC
Several libraries are available for generating PDFs in ASP.NET Core, such as iText, iTextSharp, DinkToPdf, and Rotativa.AspNetCore. Each has its own set of features and ways of working.Â
What is a PDF?
PDF stands for “Portable Document Format.” It is a file format used to present documents independently of application software, hardware, and operating systems. Here are some key characteristics and uses of PDF:
- Multi-Dimensional: PDFs can contain text, images, hyperlinks, embedded fonts, video, and more.
- Consistent Format: One of the primary benefits of a PDF is that it maintains the document’s formatting regardless of what device or software it is viewed on. This means that a PDF will look the same on any device.
- Widely Used: It’s a standard format for documents in many fields because it maintains consistency across different platforms.
- Security: PDFs can be encrypted and digitally signed, making them a secure option for sensitive documents. They also support watermarks and passwords for added protection.
- Compression: PDFs support efficient data compression, making them relatively smaller than other formats with similar content.
- Standardization: The International Organization for Standardization (ISO) standardizes the format. PDF/A, for instance, is a version of PDF meant for archiving and long-term preservation of electronic documents.
- Versatility: PDFs are used in various applications, from business documents, legal forms, research papers, and eBooks to application forms and more.
- Creation and Editing: Originally created by Adobe Systems, PDFs can now be created and edited by many different software tools, including Adobe Acrobat, Microsoft Office, and various other PDF editing and creation tools.
Generate PDF in ASP.NET Core MVC Using iText Library.
Let us see an example of how to generate a PDF in ASP.NET Core MVC using iTextSharp. Here, we are going to create an invoice PDF using iText.
Install iTextS Package:
First, you need to install the iText library. You can do this through the NuGet Package Manager. In Visual Studio, go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. Search for iText7 and install it as shown in the below image.
![Install iTextS Package Install iTextS Package](https://dotnettutorials.net/wp-content/uploads/2024/01/word-image-46438-1.png)
Create Models
Create a model to represent your invoice data. So, create a class file named InvoiceModel.cs and then copy and paste the following code.
Create a PDF Generation Service
Create a service class that will handle PDF generation. So, add a class file named PDFService.cs and then copy and paste the following code. The following code is self-explained, so please go through the comment line for a better understanding.
Create the PDF Generation Action Method
Now, we need to call the PDF Generation service in our controller to handle a route that generates the PDF. Please add the following method within the FileUpload Controller. This action method is going to generate and return the PDF.
Create a View to Trigger PDF Generation
You can create a simple view with a link or a button to trigger the PDF generation. So, let us first add the following action method within the FileUpload controller.
Next, add a view named DownloadPDF.cshtml within the Views/FileUpload folder and then copy and paste the following code.
Run and Test
Run your application and navigate to the URL FileUpload/DownloadPDF, which should open the following page. Clicking on the Download Invoice link, as shown in the image below, triggers the PDF generation and download.
![How to Generate a PDF in the ASP.NET Core MVC Application How to Generate a PDF in the ASP.NET Core MVC Application](https://dotnettutorials.net/wp-content/uploads/2024/01/word-image-46438-2.png)
Once you click on the Download Invoice link, it will generate and download the Invoice as shown in the below image:
Why PDF in ASP.NET Core MVC?
- Consistent Formatting: PDFs maintain consistent formatting regardless of the device or PDF reader used. This consistency is crucial for official documents where layout, spacing, and fonts need to remain unchanged.
- Client-Side Independence: Generating a PDF server-side ensures that the document’s appearance is not dependent on client-side factors like browser type, installed fonts, or screen resolution.
- Security and Read-Only Nature: PDFs can be made secure and read-only. This is important for sensitive documents as it prevents unauthorized editing.
- Offline Accessibility: PDFs can be easily saved, emailed, and accessed offline, making them convenient for users who need to access documents without an internet connection.
- Legal and Compliance Requirements: In many industries, documents need to be stored or transmitted in a widely recognized and accepted format. PDF is a universally accepted format in many legal, educational, and corporate environments.
- Integration with Other Systems: PDFs are often used in integrations with other systems (like email, document management systems, or cloud storage) because of their wide acceptance and compatibility.
- Print-Ready Format: PDF is a preferred format for documents that need to be printed, such as legal contracts or tickets, as it preserves the layout and formatting when printed.
In the next article, I will discuss How to Generate Password Protected PDF in ASP.NET Core MVC Application with examples. In this article, I try to explain How to Generate a PDF in the ASP.NET Core MVC Application with Examples. I hope you enjoy this article on How to Generate a PDF in the ASP.NET Core MVC.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Create or Generate PDF Files in ASP.NET Core with C#
![Bjoern Meyer Bjoern Meyer](https://s1-www.textcontrol.com/application-1.6738.76617/img/blog/author/bjoern-meyer.jpg)
Text Control's digital document processing libraries can be used for the editing, creation, and viewing of Adobe PDF documents. In this tutorial, you will learn how to create a new ASP.NET Core Web application that generates PDF documents and how to make those documents available by using the Document Viewer.
Text Control's libraries for digital document processing can be used to edit, create, and view Adobe PDF documents. In this tutorial, you will learn how to create a new ASP.NET Core Web application that generates PDF documents and how to make those documents available by using the Document Viewer.
Requirements In order to create the project in this tutorial, it is required to install TX Text Control .NET Server for ASP.NET. Download a trial version here: Download trial version
- Creating the Application
Make sure that you downloaded the latest version of Visual Studio 2022 that comes with the .NET 6 SDK .
In Visual Studio 2022, create a new project by choosing Create a new project .
Select ASP.NET Core Web App (Model-View-Controller) as the project template and confirm with Next .
Choose a name for your project and confirm with Next .
In the next dialog, choose .NET 6 (Long-term support) as the Framework , disable Configure for HTTPS for effortless testing, do not check Enable Docker and confirm with Create .
![Creating the .NET 6 project Creating the .NET 6 project](https://s1-www.textcontrol.com/application-1.6962.56402/blog/2023/10/02/b/assets/visualstudio1.webp)
- Adding the NuGet Package
In the Solution Explorer , select your created project and choose Manage NuGet Packages... from the Project main menu.
Select Text Control Offline Packages from the Package source drop-down.
Install the latest version of the following packages:
- TXTextControl.TextControl.ASP.SDK
- TXTextControl.Web.DocumentViewer
![ASP.NET Core Web Application ASP.NET Core Web Application](https://s1-www.textcontrol.com/application-1.6962.56402/blog/2023/10/02/b/assets/visualstudio2.webp)
- Building the Document
The TX Text Control API is used to generate a document that can be exported to all supported file formats, including PDF and PDF/A.
Find the HomeController.cs file in the Controllers folder. Replace the Index() method with the following code:
Learn More In the example above, the document is created from scratch. However, there are many ways to create a PDF document, from using MS Word templates to converting other formats to PDF. Creating PDF Files using TX Text Control .NET in C#
- Displaying the PDF
In order to deploy the PDF document, the Document Viewer is used to render the document that has been generated.
Find the Index.cshtml file in the Views -> Home folder. Replace the complete content with the following code:
Compile and start the application.
![Rendered PDF Rendered PDF](https://s1-www.textcontrol.com/application-1.6962.56402/blog/2023/10/02/b/assets/results.webp)
- Adding PDF.js Support
PDF documents are rendered using TX Text Control by default. You can add a reference to PDF.js to use this rendering engine for the display of PDF documents in the Document Viewer.
Right-click the project in the Solution Explorer and select Add -> Client-Side Library... from the context menu.
In the dialog that opens, type pdf.js in the Library text box and let Visual Studio autocomplete the entry with the latest version. Make sure that Include all library files is selected and confirm with Install .
![Rendered PDF Rendered PDF](https://s1-www.textcontrol.com/application-1.6962.56402/blog/2023/10/02/b/assets/pdfjs.webp)
Using CDN Package Sources In the example above, the PDF.js files are imported directly into the project. If you want to link to a CDN-hosted version, simply add the full path to the BasePath property. This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters @ using TXTextControl . Web . MVC . DocumentViewer @ using System . Text < div style = " width : 800 px ; height : 600 px ; " > @Html.TXTextControl().DocumentViewer(settings => { settings . DocumentData = Convert . ToBase64String ( ViewBag . Document ); settings . Dock = DocumentViewerSettings . DockStyle . Fill ; settings . DocumentLoadSettings . PDFJS . BasePath = " https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.2.146 " ; } ).Render() </ div > view raw test.cshtml hosted with †by GitHub
The first true WYSIWYG, HTML5-based Web editor and reporting template designer. Give your users an MS Word compatible editor to create powerful reporting templates anywhere - in any browser on any device. Our ASP.NET components combine the power of a reporting tool and an easy-to-use WYSIWYG word processor - fully programmable and embeddable in your ASP.NET application.
See ASP.NET products
Related Posts
Transforming financial documents into smart and secure forms in asp.net core c#.
This article shows how to transform financial documents into smart and secure forms in ASP.NET Core C#. All the necessary steps, from prepopulating the form fields to digital signatures, are explained in this article.
Document Viewer: Long Polling Support for Loading Documents
The Document Viewer now supports long polling for loading documents. This allows an asynchronous loading of documents and is especially useful for large documents or slow connections.
Adding and Sharing Annotations across Document Types using the Document Viewer in ASP.NET Core C#
Learn how to add and share annotations across different document types using the Document Viewer in ASP.NET Core C#. This article shows how to create a simple web application that allows users to view and annotate documents in a collaborative environment.
DOCX to HTML: Convert Documents to HTML and Prepare for Shadow DOM Rendering
Learn how to convert DOCX documents to HTML and prepare the HTML for rendering in a Shadow DOM. The sample project uses the TX Text Control .NET Server component to convert DOCX to HTML, to create stylesheets and to prepare the HTML for the Shadow DOM.
Popular Products
- TX Text Control .NET Server for ASP.NET
- Client-Side Packages (Angular, React)
- TX Text Control .NET for Windows Forms
- TX Text Control .NET for WPF
Technologies
- Document Editing
- PDF Processing
- Electronic Signatures
- Document Viewing
Get Products
- Trial Access Token
- Free Trials
- Online Store
- Documentation
Getting Started
- ASP.NET Core
- Windows Forms
- Open Support Case
- Support FAQ
Ready To Talk?
- USA: +1 704-544-7445
- Germany: +49 421 42706710
Text Control is an award-winning vendor of document processing and reporting components for Windows, web, cloud and mobile development technologies.
We â„ documents.
Copyright © 2024 Text Control, LLC. All rights reserved. Legal Notices .
TX Text Control, DS Server, ReportingCloud and other product names used herein might be trademarks or registered trademarks of Text Control, LLC and/or one of its subsidiaries or affiliates in the U.S. and/or other countries.
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
QuestPDF is a modern open-source .NET library for PDF document generation. Offering comprehensive layout engine powered by concise and discoverable C# Fluent API. Easily generate PDF reports, invoices, exports, etc.
QuestPDF/QuestPDF
Folders and files, repository files navigation.
QuestPDF is a modern open-source .NET library for PDF document generation. Offering comprehensive layout engine powered by concise and discoverable C# Fluent API.
Please help by giving a star.
Choosing a project dependency could be difficult. We need to ensure stability and maintainability of our projects. Surveys show that GitHub stars count play an important factor when assessing library quality.
â Please give this repository a star. It takes seconds and help thousands of developers! â
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://private-user-images.githubusercontent.com/9263853/329534446-3eb438af-96cd-4cdb-b3da-6de938e64068.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MTU2NTUzNTcsIm5iZiI6MTcxNTY1NTA1NywicGF0aCI6Ii85MjYzODUzLzMyOTUzNDQ0Ni0zZWI0MzhhZi05NmNkLTRjZGItYjNkYS02ZGU5MzhlNjQwNjgucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI0MDUxNCUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNDA1MTRUMDI1MDU3WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9YWJjMjM2ZjgyYWI3MmJmOGJmNjI4MGRjNTc3NzkzMzA0NDAyMjUwMzJhZWQxODg1ZTgxMThmYTVhNjE3NjJjNyZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QmYWN0b3JfaWQ9MCZrZXlfaWQ9MCZyZXBvX2lkPTAifQ.eJiE-zpG1sXcQKFXEQKDhDnLBePe8EWMOcjiDFw8-mU)
Please share with the community
As an open-source project without funding, I cannot afford advertising QuestPDF in a typical way. Instead, the library relies on community interactions. Please consider sharing a post about QuestPDF and the value it provides. It really does help!
Let's get started
Begin exploring the QuestPDF library today. You are 250 lines of C# code away from creating a fully functional PDF invoice implementation.
Read the Getting Started tutorial to familiarize yourself with general library architecture, important layout structures as well as to better understand helpful patterns and practices. Easily start designing your PDF documents, reports, invoices and even more.
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
Library License
We identify the importance of the library in your projects, so we want to ensure you can safely and confidently continue the development.
Being a healthy and growing community is the primary goal that motivates us to pursue professionalism.
The library is available for free to the vast majority of users. However, please look at the QuestPDF License and Pricing webpage for more details:
QuestPDF on JetBrains OSS Power-Ups
QuestPDF was presented on one of the episodes of OSS Power-Ups hosted by JetBrains. Huge thanks for Matthias Koch and entire JetBrains team for giving me a chance to show QuestPDF. You are the best!
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://github.com/QuestPDF/QuestPDF-Documentation/raw/main/docs/public/jetbrains-oss-powerups-youtube.png?raw=true)
Code of conduct
Security policy, releases 58, sponsor this project, used by 1.2k.
Contributors 28
Using ASP.NET MVC and Razor To Generate PDF Files
From reports to scan sheets, the need to generate PDF files has been present in every line-of-business application Iâve ever worked on. In the past, Iâve used a variety of tools to achieve this such as SQL Server Reporting Services or Telerik Reporting . While these kinds of tools work well enough for generating reports straight from the database, itâs been surprising how few resources exist to aid in generating PDF files from arbitrary data.
It turns out there is a pretty simple way to enable the generation of PDF files in an ASP.NET MVC application using the same Razor view engine that youâre probably already using. This allows you to make use of view models, HTML helpers, etc. in your PDF logic. The code here is based primarily on the code in MVC itself, specifically the ActionResult and ViewResult classes. Itâs also based on general concepts used in two open source projects, MvcRazorToPdf and RazorPDF . In a nutshell, the commands necessary to create a given PDF file (typically as XML) are placed in a standard .cshtml view, rendered and interpreted as any Razor view would be, passed to a PDF generation library (I use the excellent Aspose.Pdf , but this approach can also work with iTextSharp or any other PDF generation library that takes markup such as XML), and then returned to the client as PDF content. This is what the process looks like in a nutshell:
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://www.daveaglick.com/posts/images/pdf-process.png)
The PdfResult Class
The PdfResult class is the heart of this approach. It contains all of the logic necessary to locate the view, set up the view context, render the view, and generate the PDF file. Though it does all the heavy lifting, there actually isnât that much code involved:
Letâs go through this from top to bottom.
First off, itâs derived from PartialViewResult . Why PartialViewResult and not ViewResult or ActionResult ? ViewResult has a more robust implementation of FindView() that looks in several places for the view and includes the convention-based view search logic weâre used to using with normal views. It also includes built-in support for managing the ViewData for a view. So why use PartialViewResult ? The reason is that PartialViewResult never attempts to render layouts as part of the view. This is important if youâre using a global layout via a _ViewStart.cshtml file or something similar. Since our PDF file obviously shouldnât have the same layout logic as one of our actual web pages, we need to make sure that doesnât get included in the rendered PDF syntax. The easiest way to do that is to derive our PdfResult class from PartialViewResult , which ensures a layout is not used by returning a slightly different ViewEngineResult (and thus IView ) in itâs own FindView() implementation.
Looking at the body, the only method is an override of ExecuteResult() . This method is called when the PdfResult (or any ActionResult ) is processed by MVC and is intended to manipulate the result sent to the client (by adding content, setting headers, etc.). The first thing we do is check to make sure we have a context. This block, and most of the rest of the first part of the method, is copied straight from the implementation in MVC. Next we set the model (if there is one) and the other data that will be passed to the view. This is necessary to make sure that when we interpret our view code we have access to all of the same kinds of data we would have if this were just a normal web view. Then we get the name of the view from the action name if a view name wasnât already provided. We set this in the ViewName member which FindView() uses to locate the view.
This is where things get a little bit interesting. Next we call FindView() which locates the actual view .cshtml file using MVC conventions and instantiates an IView for us that can be used for rendering the view. We then create a ViewContext to hold all of the data our view might need and call the Render() method of the IView we were previously provided. This triggers the Razor view engine and is where the view magically gets transformed into content we can pass to our PDF generation library.
Once we have the content to pass to the PDF generator library, we create the PDF file. The code above is written for Aspose.Pdf , but could be adapted to work with iTextSharp like this (from MvcRazorToPdf ):
One final note about the FileDownloadName property and itâs use in the FileContentResult . If null is supplied for FileDownloadName , the PDF file will be delivered to the browser and rendered inline. However, if a value is supplied for FileDownloadName , the browser will initiate a file download of a PDF file with that name. This lets you control the way in which the client views and downloads the PDF file.
The Controller
Now that we have the PdfResult class complete, how do we use it to actually generate a PDF file? This step is optional, but I prefer to add a method to my Controller base class to support alternate view results from an action. The base Controller in MVC already does this â you typically write return View(); not return new ViewResult() { ... }; If you donât already have a custom base Controller in your MVC application, I suggest adding one. Even if itâs just to hold the next bit of code, itâs worthwhile. And Iâve found over time that itâs nice having a base Controller class into which I can add all sorts of other helper methods and additional logic. To that end, the following are overloads for a Pdf() method that can be used as the return value for an action:
The result of all this is that you can write you PDF generating actions in a very similar way to how you write your normal web actions:
The code about will cause a PdfResult class to be instantiated which will attempt to find a view named âPdfTest.cshtmlâ in the conventional location. It will be given an int[] array as itâs model and then rendered by the Razor view engine.
The final step is the view, where the actual PDF content is specified. Recall that I said Iâm using Aspose.Pdf , so the XML in my view corresponds to the XML that Aspose.Pdf expects. If youâre using iTextSharp or any other PDF generation library then the XML (or other type of) content contained in your view may look drastically different. But for the sake of example, hereâs what a sample view might look like using the Aspose.Pdf XML format:
The Razor syntax checker in Visual Studio will probably complain that all these XML elements are not valid HTML5 (or whatever other validation type you have configured), but thatâs fine â the actual view engine will deal with them without issue. One small complication youâll see above is that the Aspose.Pdf XML specification uses an element called Text . Unfortunately, this element also has a very special meaning in Razor syntax . We need to escape it when used directly inside a code block by using @: .
That about covers it. This was a pretty long article, mainly because I wanted to explain how everything fit together. Hopefully youâll see that when you get right down to it the approach is actually pretty simple. Now go forth and populate your web apps with lots of useful PDF documents.
- Clean Architecture
- Modular Monolith NEW
![how to generate pdf report in asp net c# How To Easily Create PDF Documents in ASP.NET Core](https://www.milanjovanovic.tech/blog-covers/mnw_063.png?imwidth=3840)
How To Easily Create PDF Documents in ASP.NET Core
5 min read · November 11, 2023
Thank you to our sponsors who keep this newsletter free to the reader:
Progress is holding a free webinar: Discover the Magic of .NET 8 and Beyond! Join the webinar and find out all the hot news in .NET 8. Register today for FREE!
How do you choose the right PDF library? Microsoft MVP Jeff Fritz compared the most popular HTML-to-PDF libraries: iTextSharp, Syncfusion, Aspose, and IronPDF. Take a look at his findings and find out which PDF library is the best.
Reporting is essential for business applications like e-commerce, shipping, fintech, etc.
One of the most popular document formats for reporting purposes is PDF.
PDF stands for Portable Document Format. It's a file format to present documents (including text formatting and images) independently of application software, hardware, and operating systems.
Some common problems .NET developers will face when working with PDF files:
- Creating dynamic PDF documents
- Designing a consistent page layout
- Customizing fonts on printed documents
Today I want to show you a few interesting ways to generate PDF files in .NET.
Creating PDF Files With QuestPDF
QuestPDF is an open-source .NET library for generating PDF documents. It exposes a fluent API you can use to compose together many simple elements to create complex documents. Unlike other libraries, it does not rely on HTML-to-PDF conversion.
Let's install the QuestPDF NuGet package:
Here's how you can generate a simplified invoice with QuestPDF:
What I like about QuestPDF:
- Easy to use
- Good documentation
What I don't like about QuestPDF:
- Having to write a lot of code to create documents
- Limited scope of features
- No HTML-to-PDF support
QuestPDF is free for small companies and development use. There's also a commercial license for larger companies. You can check out the licensing details here.
HTML to PDF Conversion With IronPDF
The more common approach for generating PDF files is using an HTML template.
My favorite library that supports this is IronPDF.
IronPDF is a C# PDF library that allows for fast and efficient manipulation of PDF files. It also has many valuable features, like exporting to PDF/A format and digitally signing PDF documents.
But what's the idea behind using an HTML template?
First of all, you have more control over formatting the document. You can use CSS to style the HTML markup, which will be applied when exporting to a PDF document.
An interesting implementation approach is using ASP.NET Core MVC views and the Razor syntax. You can pass an object to the view at runtime to render dynamic HTML content.
I've used this approach with MVC views on a few projects with excellent results.
Let's start by installing the IronPDF NuGet package:
I'm using a strongly typed Razor view to define my markup. The InoviceViewModel class is the model, and it's used to create dynamic content.
Now, you need to use the IronPDF ChromePdfRenderer to convert the HTML to a PDF document.
It really is that simple.
IronPDF is free for development use and has multiple pricing tiers for commercial use that you can check out here.
Merging Multiple PDF Files
Another common requirement I've seen is merging multiple PDF files. For example, you could implement a feature to merge the monthly receipts for the accounting department.
You can use the PdfDocument.Merge method to implement this. It accepts a PdfDocument collection as the argument. You'll first have to load the PDF documents into memory before merging them.
Here's an example:
Exporting PDF Files From an API
It's pretty straightforward to return a PDF file from an API endpoint in ASP.NET Core.
Minimal APIs have the Results.File method accepting either a file path, stream, or byte array. You also need to specify the content type and an optional file name. The MIME type for PDF files is application/pdf .
Here's how you can return a PDF file from a byte array:
Choosing which PDF library you will use in .NET is an important consideration to make. And while pricing is a significant factor, the features you want to use will also dictate your choice.
QuestPDF is an excellent choice if you're looking for a (mostly) free option with rich features. The library is constantly improved, and new features are being added. However, it doesn't support HTML-to-PDF conversion and modifying existing documents.
IronPDF is the library I've used most often on commercial projects. It has fantastic features for working with PDF files, with many customization options. The HTML-to-PDF conversion works like a charm.
The hardest part is picking the right tool for the job.
So I hope this is helpful.
See you next week.
Whenever you're ready, there are 4 ways I can help you:
- Modular Monolith Architecture (NEW): Join 500+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.
- Pragmatic Clean Architecture: Join 2,750+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.
- Patreon Community: Join a community of 1,050+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.
- Promote yourself to 49,000+ subscribers by sponsoring this newsletter.
Become a Better .NET Software Engineer
Join 49,000+ engineers who are improving their skills every Saturday morning.
Join The .NET Weekly đ
More than 49,000+ engineers get practical tips and resources every week. If you want to improve your .NET and architecture skills, start today.
Share This Article On:
[email protected] 800.631.5006
Customer Login Cart [ 0 ] item
- COM/ActiveX
- Customer Login
- Company
- Products
- Subscriptions
- Report Writer
- Print Manager
- HTML Converter
- HTML to PDF
- HTML to PDF Byte Array
- Acro Form Filling
- Add Barcodes to PDF
- Add Form Fields to PDF
- Add Image to PDF
- Add Page Numbers to PDF
- Add Signature Field to PDF
- Annotations
- Bookmarks & Outlines
- Combine PDFs
- Create a PDF
- Create PDF Report
- Digital Certificate
- Digital Signature
- Disk Buffering
- Encrypt a PDF
- Font Kerning and Tracking
- Form Flattening
- Group of Elements
- JavaScript Actions
- Layout Grid
- New Content in existing PDF
- Package PDF
- Password Protect PDF
- PDF Report with different data sources
- PDF/A compatible PDF
- PDF/X compatible PDF
- Read Form Field Values
- Reader Events
- Read-Only Form Fields
- Remove Form Fields
- Retrieving Form Field Location
- Stamping a PDF
- Text & Formatted Text
- Text Encoding
- TIFF to PDF
- Timestamp Server URL
- Watermark a PDF
- XMP Metadata
- Print multiple PDFs
- Print PDF from Bytearray
- Setting Print Options
- Excel to PDF
- Powerpoint to PDF
- Word to PDF
- PDF to Image
- PDF to TIFF
- Open Encrypted PDF
- Open PDF from Byte Array
- Open PDF from File path
- 2D Barcodes
- Linear Barcodes
- Postal Barcodes
- Clear Filter (No Matching Examples)
Generate PDF Report (.NET Core/Framework)
Use DynamicPDF Designer combined with DynamicPDF ReportWriter to automate PDF report generation. Create reports from JSON data, business objects, or a variety of data sources including SQL Server, Oracle, and MySQL databases.
- Generate PDF Report
GitHub Project
Getting started.
- Available in Other Platforms
How to Generate PDF Report
DynamicPDF Designer creates PDF report templates (DLEX files) and then ReportWriter combines the data and DLEX to layout and create a PDF report.
DynamicPDF Designer is a free graphical tool to create DLEX reports. Refer to Designer - Quick Tour for more information.
Steps to Generate PDF report
- Create a DocumentLayout object using a DLEX file as a template.
- Create a NameValueLayoutData object and add the necessary data.
- Call the Layout method on the DocumentLayout to create a Document object.
- Invoke the Draw method on the Document to save the PDF.
Sample Code - C#
Clone or view the example project at GitHub. This example on this page is in the Examples/GeneratePDFReport.cs file.
NuGet Package
DynamicPDF Generator is available on NuGet and is part of the ceTe.DynamicPDF.CoreSuite.NET package. The easiest way to install the DynamicPDF Core Suite package is through the Visual Studio Package Manager. You can also download directly from NuGet.
DynamicPDF ReportWriter Information
More information on DynamicPDF Core Suite (ReportWriter) can be found on its webpage.
- DynamicPDF ReportWriter
DynamicPDF Designer Information
More information on DynamicPDF Designer can be found on the DynamicPDF API website.
Available on Other Platforms
DynamicPDF ReportWriter PDF Library is also available for COM/AxtiveX platforms. Refer to the product page for more details.
- COM/ActiveX - DynamicPDF ReportWriter for COM/ActiveX
Why Choose DynamicPDF?
- Transparent Pricing
- Lots of Features
- Easy to Use
- Great Support
- Efficient Performance
- Product Maturity (Over 22 Years)
- Free Evaluation
- .NET Core Support (Most Products)
- Flexible Licensing
Weâre Not The Only Ones That Think Weâre Great!
- File Formats
- Create PDF file in ASP NET Core
Create or Generate PDF file in ASP.NET Core
11 Aug 2023 18 minutes to read
The Syncfusion .NET Core PDF library is used to create, read, and edit PDF documents. This library also offers functionality to merge, split, stamp, forms, and secure PDF files.
To include the .NET Core PDF library into your ASP.NET Core application, please refer to the NuGet Package Required or Assemblies Required documentation.
NOTE Beginning with our Volume 2, 2023 release, we have eliminated the dependency on the System.Drawing.Common package from our Syncfusion.Pdf.Imaging.Net.Core package. Instead, we have introduced SkiaSharp as the alternative library.
Steps to create PDF document in ASP.NET Core
![how to generate pdf report in asp net c# Create ASP.NET Core Web application in Visual Studio](https://help.syncfusion.com/Asp.Net.Core_images/Creation1.png)
NOTE Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, you also have to add âSyncfusion.Licensingâ assembly reference and include a license key in your projects. Please refer to this link to know about registering Syncfusion license key in your application to use our components.
Step 4: A default controller with name HomeController.cs gets added on creation of ASP.NET Core project. Include the following namespaces in that HomeController.cs file.
Step 5: A default action method named Index will be present in HomeController.cs. Right click on Index method and select Go To View where you will be directed to its associated view page Index.cshtml. Add a new button in the Index.cshtml as shown below.
Step 6: Add a new action method named CreatePDFDocument in HomeController.cs file and include the below code example to generate a PDF document using the PdfDocument class. Then use the DrawString method of the PdfGraphics object to draw the text on the PDF page.
You can download a complete working sample from GitHub .
![how to generate pdf report in asp net c# ASP.Net Core output PDF document](https://help.syncfusion.com/GettingStarted_images/pdf-generation-output.png)
NOTE The WinForms and WPF controls support in .NET Core 3.0 have been provided. To run this application, please install the System.Drawing.Common NuGet package as a dependent package.
Creating a PDF document with image
Load image stream from the local files on disk and draw the images through the DrawImage method of the PdfGraphics class. The following code example shows how to create a PDF document with an image.
![how to generate pdf report in asp net c# ASP.Net Core output PDF document](https://help.syncfusion.com/GettingStarted_images/PDF_with_image.png)
Creating a PDF document with table
The PdfGrid allows you to create a table from a DataSource (data set, data table, arrays, or IEnumerable object) in a PDF document.The following code example shows how to create a PDF document with a simple table.
![how to generate pdf report in asp net c# ASP.Net Core output PDF document](https://help.syncfusion.com/GettingStarted_images/PDF_with_table.png)
Creating a simple PDF document with basic elements
The PdfDocument object represents an entire PDF document that is being created. The following code example shows how to generate a PDF document and add a PdfPage to it along with the PdfPageSettings .
- Essential PDF has APIs similar to the .NET GDI plus which helps to draw elements to the PDF page just like 2D drawing in .NET.
- Unlike System.Drawing APIs all the units are measured in point instead of pixel.
- In PDF, all the elements are placed in absolute positions and has the possibility for content overlapping if misplaced.
- Essential PDF provides the rendered bounds for each and every elements added through PdfLayoutResult objects. This can be used to add successive elements and prevent content overlap.
The following code example explains how to add an image from disk to a PDF document, by providing the rectangle coordinates.
The following methods can be used to add text to a PDF document.
- DrawString() method of the PdfGraphics
- PdfTextElement class.
The PdfTextElement provides the layout result of the added text by using the location of the next element that decides to prevent content overlapping. This is not available in the DrawString method.
The following code example adds the necessary text such as address, invoice number and date to create a basic invoice application.
Essential PDF provides two types of table models. The difference between both the table models can be referred from the link Difference between PdfLightTable and PdfGrid
Since the invoice document requires only simple cell customizations, the given code example explains how to create a simple invoice table by using PdfGrid .
The following code example shows how to save the invoice document to disk and dispose the PdfDocument object.
![how to generate pdf report in asp net c# ASP.Net Core invoice PDF document](https://help.syncfusion.com/GettingStarted_images/pdf-invoice.png)
Filling forms
An interactive form sometimes referred to as an AcroForm, is a collection of fields for gathering information interactively from the user. A PDF document or existing PDF document contain any number of fields appearing in any combination of pages, all that make a single, globally interactive form spanning the entire document.
The .NET Core PDF library allows you to create and manipulate existing form in a PDF document using the PdfForm class. The PdfLoadedFormFieldCollection class represents the entire field collection of the loaded form. To work with existing form documents, the following namespaces are required.
- Syncfusion.Pdf
- Syncfusion.Pdf.Parsing
![how to generate pdf report in asp net c# ASP.Net Core PDF form document](https://help.syncfusion.com/GettingStarted_images/fill-pdf-forms.png)
The .NET Core PDF library allows you to fill the form fields by using the PdfLoadedField class. Get the form field either by using its field name or field index.
![how to generate pdf report in asp net c# ASP.Net Core filled PDF form document](https://help.syncfusion.com/GettingStarted_images/filled-form-in-pdf.jpeg)
Merge PDF Documents
The .NET Core PDF library supports merging multiple PDF documents from stream using the Merge method of the PdfDocumentBase class.
You can merge the PDF document streams by using the following code example.
Click here to explore the rich set of Syncfusion PDF library features.
An online sample link to create PDF document in ASP.NET Core.
Creating A PDF In C# .NET
So⊠This post spun a little out of control. What turned into a hunt for a simple use case (Turn an HTML string into a PDF) turned into a full blown thesis. So hereâs some quick links to jump to various parts of the article if you are coming here straight from Google, it may make things a bit easier. But I do highly recommend reading from the start to get an idea of what PDF Generation really looks like on .NET Core .
Introduction
What i was looking for.
- The Rest (WKHTMLTOPDF, Spire PDF, EO PDF, Aspose PDF, ITextSharp)
Table of Contents
Need a more powerful PDF generator?
Our sponsor, the DocRaptor HTML-to PDF API , lets you create complex PDFs from HTML, CSS, and JavaScript. Only DocRaptorâs API supports advanced features such as varying headers and footers, page break fine-tuning, accessible PDFs, and more. Pricing starts at just $15/mo.
Itâs a pretty common use case to want to generate PDFâs in C# code, either to serve directly to a user or to save locally. When I came to do it recently, suddenly I was over(and under)whelmed with the options available to actually achieve this. Certainly natively, there is nothing in C# or .NET Core that can generate PDFâs for you. And when it came to actually looking at feature sets of third party libraries (e.g. I want to use HTML as a template option), there were all sorts of problems.
So with that being said, instead of giving you code to generate a PDF with a particular PDF library, Iâll talk about how I evaluated each option.
Before I set out on my journey, I wrote down 3 really crucial points that I would judge the libraries on. These arenât too complex or even that much of an ask (Or so I hoped).
Obviously free is ideal. Something open source that I can debug myself is even better. But if I do have to pay for a âpremiumâ library. Iâm looking for a one time fee that isnât some stupid âper user/seat/machine/serverâ model. If Iâm looking at this library as a company, I donât want future architecture or decisions to be made based on the pricing of a library.
If there is some sort of freemium model in play, then I also wanted to make sure that the limitations werenât too crazy (e.g. single pages only, set number of images allowed per PDF). Freemium is OK as long as the free version is actually useable.
HTML Templating (Or something close)
I had already decided that I wanted to use HTML as my templating mechanism. I was open to using some other reasonable alternative (e.g. HTML with some XSLT engine), but ideally I just want to feed an HTML file to the library and out comes my PDF. What I really donât want to do is have to place each element manually on the PDF like we had to back in the day when printing a document from a WinForms application.
Ease Of Use/All In One
This is probably a pretty subjective one, but when you start seeking out libraries from the corners of the web or that stackoverflow answer from 3 years ago, you often end up getting some really half baked library that just doesnât work. Whether itâs some C++ library converted to C#, a library that needs X number of other libraries to actually function, or things just plain donât work how they should, Iâm probably going to see it all. So above else, I just want to be up and running in minutes, not hours.
First up is PDF Sharp, I feel like Iâve used this one previously but Iâm not entirely sure. The whole ____Sharp thing was all the rage in the early days of C#. Anyway straight off the bat PDFSharp does not work with .NET Core . There may be ported versions floating around but the version on Nuget does not support .NET Core. So itâs pretty much dead in the water. But this one was suggested to me over and over so I still want to do a quick write up about it.
PDF Sharp is free and open source. They do offer paid support but donât give any specifics on how this works and how much it costs. Free is free though so you canât complain too much.
HTML Templating
Oh boy. HTML Templating doesnât make it into the PDF Sharp library unfortunately. Instead we are stuck with writing syntax like we are back in the GDI+ dark days of C# :
I get it that this was what you had to do in the year 2000, but itâs just not going to fly right now. There are ways around this using another library that extends PDFSharp⊠But thatâs still another library that you have to grab and work with. So basically, in terms of a decent template engine out of the box, itâs a fail.
Ease Of Use
Well. It doesnât work with .NET Core which is probably going to be a blocker. The last published version was 2013. And it doesnât have HTML rendering packaged (And the library that currently does extend it to do HTML templating also doesnât support .NET Core). So all in all. Forget about it.
I got pushed to SelectPDF by a tonne of stackoverflow answers (Kinda felt like maybe they were astroturfing a littleâŠ). Itâs a paid library (Which made it all the more annoying they were commenting on stackoverflow answers with âSure just use this great library called SelectPDFâ and not mentioning the cost), But regardless I wanted to check them out and see what they offered.
It ainât free, thatâs for sure. Licensing starts at $499 and goes up to $1599. Interestingly they do offer an online version where they can generate the PDF for you by sending a URL or HTML code. Honestly I think thatâs way more interesting as a business model, but the pricing again starts at $19 but goes all the way up to $449 a month so I canât really see many people taking this option.
EDIT : So weirdly enough, there seems to be a âhiddenâ free community edition that you can only find via a tiny footer link. You can read more about the Community Edition here . It seems like the only limitation is that you canât generate PDFs over 5 pages. Doesnât seem to be any limitation on commercial use. But again, seems strange to only make this a tiny footer link and not sure it anywhere elseâŠ
HTML Templating is definitely here. And it seems to work well. In just a few lines we are up and running. While documentation is pretty good, I found it sort of all over the place. Loading HTML from a string versus loading HTML from a URL was all mixed together and so when reading examples, you had to check the code example to see what it was actually used for. But that being said, HTML Templating works so tick!
Hereâs the code to render HTML :
So on that level, ease of use seems good. I would say that many code examples were done using old school .NET WebForms which made me uneasy. Not sure why but using such an old technology like that doesnât make me feel like Iâm using the best in class.
Itâs hard to fault SelectPDF on the actual bones of what itâs doing. It generates PDFâs and does what it says on the tin. But I canât help but feel like itâs a âbudgetâ option for the price â Itâs probably the logo not being transparent.
Last up, IronPDF . These guys create a bunch of libraries called IRON______ so you may have run into them before. Iâve run into them a few times for their OCR library, and thatâs unfortunate because as soon as they came up, I knew the pricing was gonna be out of this world.
For starters they have all these tiers. Like you can get a single project license, but you have to pay per developer (ugh). But.. If you are a SAAS company, then you have to pay per user of your SAAS product. If you are developing desktop software or something distributed, well thatâs a new license again. But letâs just stick with being a SAAS company for now, for 1000+ users Iâm going to be paying $1599USD for the library and a years worth of support.
![how to generate pdf report in asp net c#](https://dotnetcoretutorials.com/wp-content/uploads/2019/06/IronPDFPricing.png)
In fairness, most large companies arenât going to bat an eye at that. Itâs not super crazy, and it is one off, but itâs still pretty pricey.
Yes and yes. In IronPDF it just works. What impressed me the most about IronPDF was their documentation . It wasnât just âHereâs a snippet, good luck!â. They even went as far to show you examples of how you might use Handlebars as a templating engine, implementing page breaks in your HTML, and even watermarking. To say that itâs feature rich would be an understatement.
Again, IronPDF comes up trumps when it comes to ease of use. In literally 4 lines everything just works and the output PDF is exactly as it should be :
Now here Iâm using inline HTML, but I can load an HTML file or load a remote URL even and it still just works. Compared to the other libraries weâve tried, this one is certainly the best when it comes to ease of use.
Here are the other libraries I looked at but didnât even bother going past the first hurdle (I sort of learnt my lesson after PDFSharp didnât even work on .NET Core).
WKHTMLTOPDF
This shouldnât really even be considered on the face of it. WKHTMLTOPDF is actually a binary that can generate PDFâs from HTML files, but there are a bunch of .NET wrappers to make use of it. Just felt odd to me and didnât feel like a solution as much as it was a bunch of pieces hobbled together that should get you there in the end. Even if you do want to go through that pain, features are rather limited. But itâs free!
Ridiculous pricing. Starts at $599 for a single developer and goes up to $9000 for over 10 developers. Might be OK for people who hate money but I skipped this one.
Another one for haters of money. Pricing starts at $749 and goes up to $4000. Support for .NET Core also seemed extremely sketchy. With the documentation half saying they support .NET Core, but to target Full Framework .
You guessed it, another one with ridiculous pricing. Starts at $999 and goes up to $14000 (Fourteen thousand) for an OEM license that still only allows 10 developers. Of course if you want the enterprise support edition youâre going up to $22000 (Twenty two thousand). Pass.
ITextSharp/IText 7
Hidden pricing which typically means âenterpriseâ priced where some salesman will call you to sell you on the library. Seems to work on AGPL license for free applications but rather not get into that.
So after all of that. Where does it leave us? Honestly in my opinion the only valid option right now to generate PDFâs on .NET Core is IronPDF . I know it costs but relatively speaking, $1500 is actually nothing compared to some of these other libraries. And again in my opinion, it seemed to have the most fully featured API along with the most up to date documentation. If you have another PDF option in .NET Core, feel free to drop a comment below!
EDIT : Itâs been pointed out that SelectPDF does have a free community so thatâs worth a crack too if you really want something out and out free. But itâs definitely still a two horse race.
50 thoughts on âCreating A PDF In C# .NETâ
Thereâs another option here: https://github.com/VahidN/iTextSharp.LGPLv2.Core Also there are some .NET Core wrappers for https://github.com/topics/wkhtmltopdf?l=c%23
there are mono builds for pdfsharp, also pdfsharp is a low level api, not meant for templating, you have to look into migradoc for templating
You could call out to ghostscript too. You can render (i.e. print) the html to pdf.
Whilst ghostscript is a binary, itâs available on probably every platform ever createdâŠincluding the kitchen sink.
WKHTMLTOPDF is the best option for .net core.. its great for html to pdf conversion directly and its free..
You forgot the most important thing when addressing a PDF library for .Net Core, it should be compatible to work cross platform on Windows and Linux as well. Iâve used all of the libraries youâve mentioned and even more. SelectPDF does not work on Linux, they specifically say that it only work on Windows. IronPDF, they say that it works on Linux, they even have an answer for that in their FAQâs where they even give the command line to run in terminal to install the relevant binaries, BUT their binaries are no where to be found and the command line fails to install them. Iâve contacted their support, sent them the full error message and they havenât replied for over a month now. All other libraries, including PDFSharp, doesnât work on Linux.
The ONLY library that currently works on Linux is iText7 which is the newer version of iText5 (iTextSharp).
Great comment Liran! Thanks for that. Also sad to see that IronPDF hasnât responded to you given itâs supposed to be a âpremiumâ library.
Very useful comment, thank you. I too have been plugging away at finding a cross platform html2pdf library. Iâve evaluated over 10 already, and IronPdf seemed like the only one to support Linux (based only on their documentation).
Is itext7.html2pdf free?
The other option is that you deploy a (web)service with your application that can execute JavaScript.
Then you can request a PDF from the service, with a free JS pdf library like https://parall.ax/products/jspdf .
We ran through the same comparison, and ended up with the same frustration (we are software vendor with both SAAS and on-prem customers). We ended up with JSReports. Maybe not a very intuitive decision â but what about thinking out of the box đ JSReports runs as a separate NodeJS application; our .Net Core generates HTML string and POSTs it to JSPreport that generates PDF. Works pretty neat
FWIW â There is a FreeSpire .NET version which has some restrictions in terms of the number of pages, etc. I havenât tried to see if it run on Linux, however.
There are also other libraries, for example syncfusions: https://www.syncfusion.com/sales/products/fileformats there is also a free community license: https://www.syncfusion.com/products/communitylicense that includes all their products! đ
This, SyncFusion is the way to go, Iâve used their PDF generator a few times and it just works. Plus they offer a community license.
Iâve used syncfusion pdf generator also, works great, although their html formatting in the pdf is not so good yet. they provide a HTMLElement but it does not work properly
I am surprise you did not mention https://www.evopdf.com/ . They have .NET and .NET Core versions. They have a great and easy to implement HTML to PDF converter for multiple platforms. It has Nuget packages available. While they have a deployment license which is single server, single application, they have a company license available. The company license is unlimited devs, unlimited apps, unlimited deployments. The bad part is you canât just purchase for a single platform. For $200 more, you get other tools also like PDF Merge and PDF Split. They actually give you a lot of bang for the buck, but most of it will probably go unused.
SpirePDF has a free edition, free edition is limited to 10 pages of pdf!
I made a wrapper around wkhtmltopdf that includes all binaries, it works on windows, linux and mac. https://github.com/pug-pelle-p/pugpdf
wkhtmltopdf is workable solution, but it doesnât support password protection If you have case like my (.net core, free library, ubuntu container and password protection is needed) for now good solution is using nuget packages: -PdfSharpCore for creating pdf -HtmlRendererCore.PdfSharpCore for rendering pdf from html
Example of usage: var document = PdfGenerator.GeneratePdf(html, PageSize.Letter)
RUN apt-get update && apt-get install -y libgdiplus is needed for docker
Did anyone try Adobeâs library? https://www.datalogics.com/products/libraries/adobe-pdf-library/
Thatâs not Adobe, itâs DataLogics
I did on this very blog! https://dotnetcoretutorials.com/2020/11/12/reading-and-writing-pdfs-in-c-with-datalogics-pdf-sdk/
Itâs pricey but I had to say, it has some really really advanced features in OCR and redacting text etc. I think you would want to be doing more with PDFâs than just generating them from a HTML file, but itâs got a crazy level of power.
And @Alan Bourke, true that it is DataLogics but DataLogics is Adobeâs official partner for the C# SDK (e.g. You wonât find any other C# SDK given out by Adobe).
I too have conducted similar research, also with disappointing results. We are happy to pay for the license providing it is reasonable. Aspose and Syncfusion pricing is simply crazy, so I have not even evaluated them.
We are using the Mvc razor engine for templating, and extract the Html directly from that. We therefore needed a library to convert Html strings or streams to Pdf documents.
For us, a crucial component was that we could specify the header in Html. This eliminated any wkhtmltopdf wrapper library, since wkhtmltopdf only supports a header as a document or url. Writing the header to a temp file and deleting afterwards smelled too bad for my liking. If this is not crucial for you, then one of the wrappers for wkhtmltopdf could work very well, DinkToPdf is probably the best bet.
Another crucial for us was that the css style âpage-break-inside: avoid;â must actually work. IronPdf was one of the few libraries that seemed to completely ignore this style and would split a table row in half at the page break. Wow! This completely ruled out IronPdf for us.
Two libraries not mentioned above are HiQPdf and Winnovative. These are both reasonably priced, and in my test use case worked the best. Page headers were simple and css was very well honoured. However, as with most of these libraries, they donât support Linux directly!
So, after 2 weeks of research we still donât really have a solution.
Have you looked at Puppeteer Sharp? That uses Headless Chromium to fetch your website and create a pdf from it. We are using that with MVC Razor to create pdfs â by simply hosting the pages and pointing puppeteer at it. It may sound like overkill, but when you have set it up, it works fine.
Puppeteer Sharp did not work on Azure/ windows as it use GDI and GDI is restricted on Azure for security reasons
Hello there, what did you come up with at the end? After 2 weeks of searching, I could not find any tool that suits my purposes.
HiQPdf dosnât work on linux !
I always used FONET, which is simple to use and open-source (Apache V2). You can import it to your project through Nuget. It works with XML and XSL stylesheet. You can also embed images.
Well, hereâs another idea. Why not run your own âSaaSâ PDF generator thingy. Just build a simple web API with .NET Framework (which will be supported for many years) and an open-source package that does HTML to PDF, and host it on a VM somewhere.
> PDFSharp does not work with .NET Core
Itâs open source and can be trivially built for .NET Core. Use migrate-2019 + System.Drawing.Common NuGet package.
We did have to wait for some updates to .net core for fonts, but Scryber now works on 3.1 and open-source with Mac and Linux support (adding GDI+). Hope it helps someone, without being a selfless plug.
https://github.com/richard-scryber/scryber.core
Has anyone tried PdfSharpCore? https://github.com/ststeiger/PdfSharpCore
Can anyone please tell which is the best option for a PDF viewer that toolbar can be customized. My need is to open a PDF file without download option. Mine is a .net core project.
For *displaying* a PDF, you need a JS option such as PDF.js https://mozilla.github.io/pdf.js/
no one mentioned pdftron â https://www.pdftron.com/documentation/linux/guides/
apparently you donât pay until you ship.
plus foxit has an SDK and they have linux version
To be honest, any library with âsecret pricingâ shouldnât really need to be mentioned.
Has anyone tried DevExpress Office File API Version 20.1?
Weâre a bit too heavily invested in wkhtmltopdf to switch now, at least for existing projects. I kinda miss Crystal Reports, it had issues and quirks, but worked well for labels with a specific fixed layout. Getting that kind of layout correct in html can be tricky.
Can confirm that a .NET Core port of (free) PdfSharp worked for me in .NET 5, after several days of trying various solutions. I can now batch WPF layouts into a multi-page XpsDocument and save it as PDF. The one that worked for me is https://www.nuget.org/packages/PdfSharp.Xps.dotNet.Core with less than 2,000 downloads
A little bit of my own experiencesâŠ
My use case is pretty strictly HTML to PDF, with a little manipulation of existing PDFs like deleting pages.
I tried IronPDF back in July 2018 and had a horrible experience both technically and personally. The font rendering just didnât seem to work right. It ignored any fonts that were in the style sheets and everything was blocky. Their customer support was slow and couldnât provide a way to fix the problem. They then argued profusely with me when I asked them for a refund. Definitely not âcustomer orientedâ folks over there at the time. Luckily the reseller (MyCommerce) quickly supported me and refunded me without delay.
So my goto remains Eo.PDF. Iâve used that successfully for many, many years. It has its limitations and annoyances, yes. Itâs not cheap, and costs $240/year to renew for updates; it doesnât really support .NET Core; and it doesnât work in a shared web environment like Azure App Service, it has to run on a machine. But it works very, very well with all the HTML I throw at it.
Itâs funny that I found this post because I was looking to see if there was anything new, cheaper or better before I renew Eo.PDF again. And there may be? But this has actually convinced me to just renew. đ
Docati supports .Net core ans runs on Windows and Linux. It uses Word documents as templates and requires an add-in for Word to edit the templates. The idea behind using Word is that business people can maintain the templates and that Word is a better document design
This is their sample code: https://github.com/kwaazaar/docati.api.demo
Thank you for the tutorial. But you forgot to mention PDFFlow library ( https://www.pdfflow.io ) for C#. It also creates PDF documents from scratch. But it supports repeating headers, automatic page numeration, multi-page spread tables and many other automatic layouting options which are not described in your tutorial regarding other libraries. Also, there are samples of different business documents in repo ( https://github.com/gehtsoft-usa/PDF.Flow.Examples ), I havenât seen that much from other PDF generating libraries.
A bit late to the party, but removing the PDFSharp package from my solution and using NuGet to install the PDFSharpCore version solved the issue as of 7/2021
What about https://playwright.dev/dotnet/ ?
Not tried it yet myself but it seems to support printing to PDF (as well as all the automation things etc) and you would get something like the Chromium engine for rendering.
Microsoft supported as well and Linux support etc.
I tried all the options you mentioned and some others in a .Net 5 / Docker environment, and became convinced that your conclusion about IronPDF is right (SelectPDF works very well too, but is Windows only, despite claiming .net core compatibility). But IronPDF does its job by downloading and using chrome (or chromium), and there is now a free and open source way to do exactly the same thing, which is to use Puppeteer-Sharp. See https://www.kambu.pl/blog/how-to-generate-pdf-from-html-in-net-core-applications/
Did similar research and was disappointed by the lack of good solutions at affordable prices. However, head and shoulders above all other solutions, was GemBox which has a fairly restrictive free version but uses c# only implementation of word/ excel/ pdf templating and the word/ excel fidelity is excellent for most use cases. The paid for versions are not eye wateringly expensive and but have relatively competitive prices on all solutions. Samples are easy to follow and you will be able to get an example up and running very quickly. Other than being a customer, for a company who have implemented in an enterprise solution, I have no association with the company but think it is an excellent product. see https://www.gemboxsoftware.com/
https://github.com/pug-pelle-p/pugpdf â made a .net 6 app that creates PDF and it runs/works on MAC, fyi (so I assume itâll work on Linux) â free library
If you donât need advanced pdf features but want perfect html rendering, I can recommend PuppeteerSharp (or Playwrigth). The best is that you can easily tune your html and try to print it as pdf in Chrome â youâll get exactly the same result from PuppeteerSharp. Weâre creating 200+ pages pdfs and it works well.
Iâm really surprised that no-one has mentioned XSL-FO which is a robust templating approach to rendering PDFs and Apache FOP is a free rendering engine. It may not account for all of the HTML to PDF requirements out there since XSL-FO is itâs own templating language (Xml based), and modern HTML and CSS wouldnât translate too wee because Table Layouts are the best way to get what you are looking for. But it wouldnât be unheard of to apply some XSLT to convert simple HTML to XSL-FO⊠I think IBM used to host a set of XSLTs that did that in a tutorial somewhere.
But, for those wanting great control and flexibility then any XSLT templates or Razor templates work great to render the output and then ApacheFOP runs awesome in a serverless setup for a Pdf-as-a-Service capabilityâŠ. and ApacheFOP.Serverless is a ready-to-go project for Azure Functions; of which Iâm the owner the ApacheFOP.Serverless project on GitHub.
Some working examples are also in my .NET Repo: https://github.com/cajuncoding/PdfTemplating.XslFO
I think DevExpress PDF report generating library is not so bad and also pricing is manageable. https://www.devexpress.com/subscriptions/reporting/
Hi, from which year is this article?
Leave a Comment Cancel reply
Save my name, email, and website in this browser for the next time I comment.
Study through a pre-planned curriculum designed to help you fast-track your DotNet career and learn from the worldâs best collection of DotNet Resources.
Find us on social media:
As Featured On
![how to generate pdf report in asp net c#](https://dotnetcoretutorials.com/wp-content/uploads/2022/10/as-featured.png)
Contact: [email protected] Â | Phone Number: (973) 916-2695Â | Address: 288 Rosa Parks Blvd, Paterson, New Jersey 07501, USA
Disclaimer: Efforts are made to maintain reliable data on all information presented. However, this information is provided without warranty. Users should always check the offer providerâs official website for current terms and details. Our site receives compensation from many of the offers listed on the site. Along with key review factors, this compensation may impact how and where products appear across the site (including, for example, the order in which they appear). Our site does not include the entire universe of available offers. Editorial opinions expressed on the site are strictly our own and are not provided, endorsed, or approved by advertisers.
2022 © DotNetCoreTutorials All rights reserved.
![ezoic how to generate pdf report in asp net c#](https://go.ezodn.com/utilcave_com/ezoic.png)
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://www.codeproject.com/script/Membership/Images/octicons_github-lg.png)
- Latest Articles
- Top Articles
- Posting/Update Guidelines
- Article Help Forum
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://www.codeproject.com/images/write13.png)
- View Unanswered Questions
- View All Questions
- View C# questions
- View C++ questions
- View Javascript questions
- View Visual Basic questions
- View Python questions
- CodeProject.AI Server
- All Message Boards...
- Running a Business
- Sales / Marketing
- Collaboration / Beta Testing
- Work Issues
- Design and Architecture
- Artificial Intelligence
- Internet of Things
- ATL / WTL / STL
- Managed C++/CLI
- Objective-C and Swift
- System Admin
- Hosting and Servers
- Linux Programming
- .NET (Core and Framework)
- Visual Basic
- Web Development
- Site Bugs / Suggestions
- Spam and Abuse Watch
- Competitions
- The Insider Newsletter
- The Daily Build Newsletter
- Newsletter archive
- CodeProject Stuff
- Most Valuable Professionals
- The Lounge Â
- The CodeProject Blog
- Where I Am: Member Photos
- The Insider News
- The Weird & The Wonderful
- What is 'CodeProject'?
- General FAQ
- Ask a Question
- Bugs and Suggestions
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://www.codeproject.com/App_Themes/CodeProject/Img/print48.png)
Create/Read Advance PDF Report using iTextSharp in C# .NET: Part I
![how to generate pdf report in asp net c# how to generate pdf report in asp net c#](https://www.codeproject.com/Uploads/Membership/ProfileImages/{e0449b90-7399-4e06-8ca2-4608407d14c4}.jpg)
- Download source - 1.4 MB
- Download iTextSharp_5.4.4.zip - 1.4 MB
Introduction
Requirements, installation.
- Creating PDF Document in 6 Steps
- Working with Page Size of PDF Document
- Setting Background Color of PDF Document
- Setting Page Margins of PDF Document
- Setting Text Alignment in PDF Document
- Setting Meta Information or Properties of a PDF Document
- Creating a Multipage Document
- Creating a New PDF Document from an existing PDF Document
- Adding Watermark to PDF Document using Layer
- Removing Watermark from the just created Watermarked Document by Removing Layer
- Adding Watermark to each Page during Creation
- Export/Print/Output the PDF File directly to the Client without saving it to the Disk
- Setting Viewer Preferences of a PDF Document
- Encrypting a PDF Document
Declaration
Recently I was looking for an Advance Tool to create complex PDF Report in C#.Net and I found iTextSharp . The main problem is that lacks of Documentation. Yes, there are a few examples in C#, but that is not sufficient to the Beginners and the examples are in older version of iTextSharp , there are lots of change in the latest version. So, it will be difficult for beginners to convert older version to latest version. Besides, I think that if I write an Article on this, then it will help me also as a future reference as I'll describe each functionality of this library with example. Frankly speaking, in this Article, you find all the examples from Chapter 1 of the book iText in Action, Second Edition which is written for Java Developers. I'll explain all the examples of the rest Chapters in my next release of this Article. So if any one is interested in using this library, he/she will get a good kick start.
To know the history or any other details of iTextSharp, please go through the Official Website
- To compile this library, you need a C# 2008 compiler or better, Visual Studio 2008 or Visual C# 2008 Express Edition
- .NET 4.0 Client Profile
- .NET 4.5 Client Profile
- Simply install the NuGet package
Or you can download the library DLL from the above link or from the SourceForge . Then do the following:
- iTextSharp.text
- iTextSharp.text.pdf
Quick Start
Creating pdf document in 6 steps:.
- Step 1: Create a System.IO.FileStream object: C# FileStream fs = new FileStream( " Chapter1_Example1.pdf" , FileMode.Create, FileAccess.Write, FileShare.None);
- Step 2: Create a iTextSharp.text.Document object: C# Document doc = new Document();
- Step 3: Create a iTextSharp.text.pdf.PdfWriter object. It helps to write the Document to the Specified FileStream: C# PdfWriter writer = PdfWriter.GetInstance(doc, fs);
- Step 4: Openning the Document: C# doc.Open();
- Step 5: Adding a Paragraph by creating a iTextSharp.text.Paragraph object: C# doc.Add( new Paragraph( " Hello World" ));
- Step 6: Closing the Document: C# doc.Close();
Working with Page Size of PDF Document:
Creating a Page of specified size, we must have to create a iTextSharp.text.Rectangle object and Passing the size as argument to its constructor. There are a few way to define Page Size:
- First Way to define Page Size: Creating Page Size by Pixels or Inch. NOTE: In iTextSharp library, unit is 'point'. 72 points = 1 inch. Suppose we want to create a PDF File of width = 2 inch & height = 10 inch, then we need 144pt for 2 inch & 72pt for 10 inch. Lets see, how to do this: C# Rectangle rec = new Rectangle( 144 , 720 );
- A4_LANDSCAPE
- CROWN_OCTAVO
- CROWN_QUARTO
- DEMY_OCTAVO
- DEMY_QUARTO
- LARGE_CROWN_OCTAVO
- LARGE_CROWN_QUARTO
- LEGAL_LANDSCAPE
- LETTER_LANDSCAPE
- PENGUIN_LARGE_PAPERBACK
- PENGUIN_SMALL_PAPERBACK
- ROYAL_OCTAVO
- ROYAL_QUARTO
- SMALL_PAPERBACK
- Third Way to define Page Size: Rotating Document i.e. height becomes width & vice-versa: C# Rectangle rec3 = new Rectangle(PageSize.A4.Rotate());
Now, just pass this iTextSharp.text.Rectangle object (any one) i.e. either 'rec', or 'rec2' or 'rec3' to the iTextSharp.text.Document 's constructor during object creation like below:
Setting Background Color of PDF Document:
There are a few ways to set background color:
- First Way to Set Background Color: It takes the object of iTextSharp.text.BaseColor . BaseColor constructor takes in-built System.Drawing.Color object Or you can pass RGB values to the constructor in different forms: C# rec.BackgroundColor = new BaseColor(System.Drawing.Color.WhiteSmoke);
- Second Way to Set Background Color: It takes the object of iTextSharp.text.pdf.CMYKColor . CMYKColor constructor takes only CMYK values in different forms: C# rec2.BackgroundColor = new CMYKColor( 25 , 90 , 25 , 0 );
Setting Page Margins of PDF Document:
Margins can be set during Document object creation like Page Size Suppose we set the margins as below:
- Left Margin: 0.5 inch
- Right Margin: 1 inch
- Top Margin: 1.5 inch
- Bottom Margin: 2.5 inch
So, we need to do set the following points for the Left, Right, Top, Bottom Margins respectively as we already know that iTextSharp library only understand points where 72 points = 1 inch.
- Left Margin: 36pt => 0.5 inch
- Right Margin: 72pt => 1 inch
- Top Margin: 108pt => 1.5 inch
- Bottom Margini: 180pt => 2.5 inch
Lets implement:
Setting Text Alignment in PDF Document:
Alignment is one of the property of iTextSharp.text.Paragraph 's object. iTextSharp Library provides various types of Alignments. These Alignments can be access through iTextSharp.text.Element class. The following are Alignment types provides iTextSharp:
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_BASELINE" > ALIGN_BASELINE </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_BOTTOM" > ALIGN_BOTTOM </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_CENTER" > ALIGN_CENTER </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_JUSTIFIED" > ALIGN_JUSTIFIED </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_JUSTIFIED_ALL" > ALIGN_JUSTIFIED_ALL </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_LEFT" > ALIGN_LEFT </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_MIDDLE" > ALIGN_MIDDLE </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_RIGHT" > ALIGN_RIGHT </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_TOP" > ALIGN_TOP </ a > [ ^ ]
- <a href= " http://api.itextpdf.com/itext/com/itextpdf/text/Element.html#ALIGN_UNDEFINED" > ALIGN_UNDEFINED </ a > [ ^ ]
As we already see the iTextSharp.text.Document 's constructor takes iTextSharp.text.Paragraph 's object during Document creation. So, after creating the Paragraph object and setting Alignment property, we can pass this object to iTextSharp.text.Document 's constructor during Document ceration. Lets implement:
Setting Meta Information or Properties of a PDF Document:
The following Meta information of PDF Document, you can set through iTextSharp.text.Document 's methods by creating its object i.e. doc here:
- Author Name[ ^ ]
- Creation Date[ ^ ]
- Creator Name[ ^ ]
- Header Name & Content[ ^ ]
- Keywords[ ^ ]
- Langugae[ ^ ]
- Producer[ ^ ]
- Subject[ ^ ]
Lets implement a few of them:
![how to generate pdf report in asp net c# PDF Document Properties](https://www.codeproject.com/KB/cs/686994/Document_Properties_resized.png)
Creating a Multipage Document:
We can create a new page through iTextSharp.text.Document 's NewPage() method by creating its object. Lets add five pages in PDF Document:
Creating a New PDF Document from an existing PDF Document:
We can read from a PDF Document using iTextSharp.text.pdf.PdfReader 's object and write it to another PDF Document using iTextSharp.text.pdf.PdfStamper 's object. Lets implement:
Adding Watermark to PDF Document using Layer:
Watermark can be add after creating the PDF Dodument in iTextSharp Library. Here I'll add Watermark to existing PDF Document i.e. Original.pdf , through creating a iTextSharp.text.pdf.PdfLayer object. Lets implement:
![how to generate pdf report in asp net c# Watermarked.pdf](https://www.codeproject.com/KB/cs/686994/Watermarked_Resized.png)
Removing Watermark from the just created Watermarked Document by Removing Layer:
Whenever we add Layer in PDF Document, then the content of the Layer resides under OCG Group. So if I remove this Layer we can remove the content of the Layer also e.g. here it is Watermark Text. To remove all the Layers from PDF Document, you have to remove OCG Group completely from the Document using reader.Catalog.Remove(PdfName.OCPROPERTIES) . Now follow the Steps below to remove the Watermark Text from Layer:
- Read the existing watermarked document using iTextSharp.text.pdf.PdfReader 's object
- Taking each Page in the iTextSharp.text.pdf.PdfDictionary 's object using GetPageN(int pageNumber) method of iTextSharp.text.pdf.PdfReader 's object.
- Taking the Content of the Page in the iTextSharp.text.pdf.PdfArray 's object using GetAsArray(PdfName.CONTENTS) method of iTextSharp.text.pdf.PdfDictionary 's object
- Loop through this array and Get each element as iTextSharp.text.pdf.PRStream 's object using GetAsStream(int arrayIndex) method of iTextSharp.text.pdf.PdfArray 's object
- Convert each stream into Bytes using Static method GetStreamBytes(PRStream stream) of iTextSharp.text.pdf.PdfReader class
- Convert these Bytes into String using System.Text.Encoding.ASCII.GetString(byte[] bytes) method
- Search for the String "/OC" and also the Watermarked Text . If found then remove it by giving it zero length and zero data using two methods: Put() & SetData() of iTextSharp.text.pdf.PRStream class
- Write this modified document exists in the reader to a new document using iTextSharp.text.pdf.PdfStamper 's object
Lets Implement it:
Adding Watermark to each Page during Creation:
Now, we already know that, watermark cannot be add during Page creation, it have to add after document creation. So, I've created a class PDFWriterEvents which implements the interface iTextSharp.text.pdf.IPdfPageEvent and modify the event OnStartPage . This interface contains a set of events from the Openning & to Closing the PDF Document. The events are following:
- public void OnOpenDocument(PdfWriter writer, Document document)
- public void OnCloseDocument(PdfWriter writer, Document document)
- public void OnStartPage(PdfWriter writer, Document document)
- public void OnEndPage(PdfWriter writer, Document document)
- public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition)
- public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition)
- public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
- public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition)
- public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title)
- public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition)
- public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text)
You may modify other events accroding to your needs which occured against a particular action. Let see the which I've created:
Lets see how & when you use the object of this class:
See, OnStartPage event called during adding a new paragraph. So I don't need to add watermark later:)
Export/Print/Output the PDF File directly to the Client without saving it to the Disk:
We can create PDF File in memory by creatig System.IO.MemorySystem 's object. Lets see:
Setting Viewer Preferences of a PDF Document:
The values of the different ViewerPreferences were originally stored in iTextSharp.text.pdf.PdfWriter class as an integer constant. You can set the ViewerPreferences by following two ways:
- By setting property ViewerPreferences of iTextSharp.text.pdf.PdfWriter class. To know all the ViewerPreferences and its purpose, please read this first. E.g.- writer.ViewerPreferences = PdfWriter.HideMenubar;
- By calling method AddViewerPreference(PdfName key, PdfObject value) of iTextSharp.text.pdf.PdfWriter 's object. To know which value is appropiate for which key , read this first. E.g.- writer.AddViewerPreference(PdfName.HIDEMENUBAR, new PdfBoolean( true ));
Encrypting a PDF Document:
By SetEncryption() method of iTextSharp.text.pdf.PdfWriter 's object, we can encrypt a PDF document. Read full documentation of this method here . To know all the encryption types, click here . E.g.-
- iText Official Website
- iText in Action, Second Edition
- Core iText API Documentation
- RubyPdf Blog - iText# in Action
- Create PDFs in ASP.NET - getting started with iTextSharp
- Basic PDF Creation Using iTextSharp - Part I
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
![how to generate pdf report in asp net c# LinkedIn](https://www.codeproject.com/images/linkedin-32.png)
Comments and Discussions
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
1) SQL Server's built in Reporting Services. 2) Adobe Forms. 3) Crystal Reports. This information I need as PDF directly parallels what is already being displayed in the user's web browser as HTML, so creating a print stylesheet and converting the browser body to PDF is an option as well. So this creates option 4:
To put this into practice, here is a simple ASP.NET Core MVC sample project that generates a PDF on the server: // Controller action public IActionResult GeneratePdf() { // Create document object Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 25); // Write content WriteParagraph(pdfDoc, "Hello World!");
If we want to show our document in a browser instead, we can configure that quite easily. First, we need to remove the Out property from the globalSettings object. Then instead of this type of conversion: _converter.Convert(pdf); We are going to use this type: var file = _converter.Convert(pdf);
If you want to create pdf/excel/word using rdlc report I recommend you can use AspNetCore.Reporting library. This is open source and comes as a nuget package. you can integrate this in your .NET Core API or .NET Core Azure function. You can generate a byte array convert it to base 64 string and retrieve that to your client side.
Click on "Create new project.". In the "Create new project" window, select "ASP.NET Core Web App (Model-View-Controller)" from the list of templates displayed. Click Next. In the ...
Create a PDF Generation Service. Create a service class that will handle PDF generation. So, add a class file named PDFService.cs and then copy and paste the following code. The following code is self-explained, so please go through the comment line for a better understanding. using iText.Kernel.Pdf;
In Visual Studio 2022, create a new project by choosing Create a new project. Select ASP.NET Core Web App (Model-View-Controller) as the project template and confirm with Next. Choose a name for your project and confirm with Next. In the next dialog, choose .NET 6 (Long-term support) as the Framework, disable Configure for HTTPS for effortless ...
Offering comprehensive layout engine powered by concise and discoverable C# Fluent API. Easily generate PDF reports, invoices, exports, etc. - QuestPDF/QuestPDF. QuestPDF is a modern open-source .NET library for PDF document generation. Offering comprehensive layout engine powered by concise and discoverable C# Fluent API.
Once we have the content to pass to the PDF generator library, we create the PDF file. The code above is written for Aspose.Pdf, but could be adapted to work with iTextSharp like this (from MvcRazorToPdf ): // Create a PDF from the rendered view content. var workStream = new MemoryStream();
Now, you need to use the IronPDF ChromePdfRenderer to convert the HTML to a PDF document. var html = ConvertRazorViewToHtml(invoice); var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf(html); pdf.SaveAs($"invoice-{invoice.InvoiceNumber}.pdf"); It really is that simple. Licensing.
Step 3: Create a new PDF document. In the Program.cs file's Main method, paste these two lines of code between the braces. Create a new document by calling GcPdfDocument class. Then add a new ...
Steps to Generate PDF report. Create a DocumentLayout object using a DLEX file as a template. Create a NameValueLayoutData object and add the necessary data. Call the Layout method on the DocumentLayout to create a Document object. Invoke the Draw method on the Document to save the PDF.
In this example, we'll create a simple PDF document containing text and a rectangular shape. using System; using GrapeCity.Documents.Pdf; using GrapeCity.Documents.Text; class Program { static void Main(string[] args) { // Create a new PDF document var doc = new GcPdfDocument(); // Add a page to the document var page = doc.NewPage(); // Create ...
How to Generate a PDF Report in ASP.NET Core Web API free.Blazor PDF Report (Free): https://www.youtube.com/watch?v=jYN8nw_WoYs Download Source Code: https:...
Steps to create PDF document in ASP.NET Core. Step 1: Create a new C# ASP.NET Core Web Application project. Step 2: Select Web Application pattern (Model-View-Controller) for the project. Step 3: Install the Syncfusion.Pdf.Net.Core NuGet package as reference to your ASP.NET Core applications from NuGet.org. NOTE.
HTML Templating doesn't make it into the PDF Sharp library unfortunately. Instead we are stuck with writing syntax like we are back in the GDI+ dark days of C# : // Get an XGraphics object for drawing XGraphics gfx = XGraphics.FromPdfPage(page); // Create a font XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); // Draw the text.
Recently I was looking for an Advance Tool to create complex PDF Report in C#.Net and I found iTextSharp. The main problem is that lacks of Documentation. Yes, there are a few examples in C#, but that is not sufficient to the Beginners and the examples are in older version of iTextSharp, there are lots of change in the latest version. So, it ...
On the server-side, you can output HTML of a view as string and can use any library that generate PDF from HTML string. to render a view into string see this link Return View as String in .NET Core after you got HTML, you need to pass it to the library see this link to convert HTML to string Convert HTML to PDF in .NET. 1 Create a C# extension method to render view to string
8. My go-to choice for PDF generation in C# is Winnovative's PDF generator. While we primarily utilize it for converting HTML to PDF, it's versatile enough to handle various PDF generation tasks efficiently. This is no MIT licensed software package.
Here you can use a PDF library of your choice ( iText.Net, Nitro PDF, Amyuni PDF Creator.Net), load your PDF form, set the values to each field, flatten your file if needed, and save. The code for this part depends on the library being used, but they are usally well documented so you should be able to find sample code easily.