How to generate PDF by C #

In the previous project, we used wkhtmltopdf to render web pages to generate PDF files. This scheme has not been very stable, and the styles of different scenes are often different, so it needs to be adjusted. Today, we have studied the scheme of generating PDF directly by C #, which is relatively simple. The overall scheme is as follows:

Generate XPS file through WPF library
Convert XPS file into PDF file through pdfsharp
first, take a look at the code of generating XPS file. The code is as follows:

var fixedDoc = new FixedDocument();
var pageContent = new PageContent();
var fixedPage = new FixedPage();
 
fixedPage.Children.Add(canvas);
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
 
using var xpsd = new XpsDocument(@"r:\3.xps", FileAccess.ReadWrite);
var xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
 
xw.Write(fixedDoc);
xpsd.Close();

Because visual in WPF can be converted to XPS file. Thanks to the powerful display ability of WPF, even rendering complex XPS files is very easy.

After having the XPS file, the next step is to convert it to PDF. Here, I use the free pdfsharp package. Because I use. Net 5, I introduce PDF PdfSharp.Xps.dotNet . core, the code is relatively simple, a line of code can be done.

PdfSharp.Xps.XpsConverter.Convert(@"r:\3.xps", @"r:\3.pdf", 0);

The scheme of generating PDF is simple and easy to use with the help of class library of WPF platform, and can realize visualization. The disadvantage is that you can’t run on Linux. If you want to realize PDF generation on Linux platform, you can also 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 for C to generate PDF. For more information about C to generate PDF, please refer to

Read More: