In the previous project, the pdf file generated by the web page was rendered through wkhtmltopdf. This solution has never been very stable, and the styles are often different in different scenarios, so it is always necessary to adjust. Today I studied the solution to directly generate PDFs in C#, which is relatively simple. The overall solution is as follows:
- Generate XPS files through WPF library
- Convert XPS file to PDF file through PdfSharp
First, let’s take a look at the code that generates the xps file. , the code is as follows:
var fixedDoc = new FixedDocument(); var pageContent = new PageContent(); var fixedPage = new FixedPage(); (canvas); ((IAddChild)pageContent).AddChild(fixedPage); (pageContent); using var xpsd = new XpsDocument(@"r:\", ); var xw = (xpsd); (fixedDoc); ();
Because Visual in WPF can be converted to Xps files. Thanks to WPF's powerful display capabilities, it is very easy to render even complex XPS files.
After having the XPS file, the next step is to convert it into pdf. Here I use the free PdfSharp package. Since I use .net 5, the code is relatively simple and can be done with one line of code.
(@"r:\", @"r:\", 0);
This PDF generation solution uses the WPF platform class library, which is simple and easy to use and can be visualized. The disadvantage is that you can no longer run on Linux. If you want to implement PDF generation on Linux platform, it is also OK to use PdfSharp directly. For details, please refer to this article:PDF Generation and Printing in .NET
The above is the detailed content of the method of generating PDF in C#. For more information about generating PDF in C#, please pay attention to my other related articles!