C# 使用 QuestPDF 套件建立 PDF

QuestPDF 是一個開源免費(年收低於 100 萬美金以下的公司或個人)的使用 C# 產生 PDF 的套件,在筆者撰文當下(2023-10-26) 在 GitHub 上已經有 724 個 Commit ,有 7.5k Star 和 419 Fork ,在 NuGet 上累積下載次數達 2.6M ,平均每天 2.4k 的下載,和其他老牌產生 PDF 的套件相比下載次數算少,不過還算是滿活躍的,他最大的優勢就是對於大部分的人來說幾乎可以免費使用了,並且在官網上有非常詳細的教學,指導開發時的程式碼架構、撰寫方式,就算沒有要使用這個套件也非常建議依照教學嘗試一次,可以學到不錯的程式碼撰寫方式。

筆者是在 GitHub Explore Trending 的本月 C# 排行榜中發現此套件

安裝

先使用 NuGet 安裝 QuestPDF 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package QuestPDF
    

啟用授權

一開始在使用 QuestPDF 時會拋出下列例外:
    
Unhandled exception. System.Exception: QuestPDF is a modern open-source library. We identify the importance of the library in your projects and therefore want to make sure you can safely and confidently continue the development. Being a healthy and growing community is the primary goal that motivates us to pursue professionalism. 

Please refer to the QuestPDF License and Pricing webpage for more details. (https://www.questpdf.com/pricing.html) 

If you are an existing QuestPDF user and for any reason cannot update, you can stay with the 2022.12.X release with the extended quality support but without any new features, improvements, or optimizations. That release will always be available under the MIT license, free for commercial usage. 

The library does not require any license key. We trust our users, and therefore the process is simple. To disable license validation and turn off this exception, please configure an eligible license using the QuestPDF.Settings.License API, for example: 

"QuestPDF.Settings.License = LicenseType.Community;" 

Learn more on: https://www.questpdf.com/license-configuration.html 


   at QuestPDF.Drawing.DocumentGenerator.ValidateLicense()
   at QuestPDF.Drawing.DocumentGenerator.GeneratePdf(Stream stream, IDocument document)
   at QuestPDF.Fluent.GenerateExtensions.GeneratePdf(IDocument document, Stream stream)
   at QuestPDF.Fluent.GenerateExtensions.GeneratePdf(IDocument document, String filePath)
   at Program.<Main>$(String[] args)
    

說明此套件可以有條件免費商用,不需要任何金鑰,只是要在使用前設定授權類型:
    
QuestPDF.Settings.License = LicenseType.Community;
    


註:上面錯誤訊息中提到的連結是錯誤的,筆者研究了一下發現連結應該要是斜線(/),已經發 PR。
2023-10-30 更新:筆者在 GitHub 上發出的 PR 678 已被接受,此連結錯誤問題已修正,但尚未發布。
2023-11-01 更新:修正的版本已經發布更新套件後即可修正問題 😎

基本範例

以下是依照官方文件修改的範例,第一次產生文件的時候嚇了一跳,中文全部都是 ??? ,不過馬上就想到可能是字型的問題,設定後就可以正常顯示繁體中文了,可以很方便的設定預設字體。
    
using QuestPDF;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;

Settings.License = LicenseType.Community;


var document = Document.Create(container =>
    {
        container.Page(page =>
            {
                page.Size(PageSizes.A4);
                page.Margin(2, Unit.Centimetre);
                page.PageColor(Colors.White);
                page.DefaultTextStyle(x => x
                        .FontSize(20) // 設定預設字體大小
                        .FontFamily("微軟正黑體") // 設定預設字體
                );

                page.Header()
                    .Text("Hello PDF!")
                    .SemiBold().FontSize(36).FontColor(Colors.Blue.Medium);

                page.Content()
                    .PaddingVertical(1, Unit.Centimetre)
                    .Column(x =>
                    {
                        x.Spacing(20);

                        x.Item().Text("文字文字");
                        x.Item().Image(Placeholders.Image(200, 100)); // 自動產生柔和漸變圖片
                    });

                page.Footer()
                    .AlignCenter()
                    .Text(x =>
                    {
                        x.Span("第");
                        x.CurrentPageNumber();
                        x.Span("頁");
                    });
            }
        );
    }
);

string path = @"C:\Users\ruyut\Desktop\test.pdf";
document.GeneratePdf(path);
    


及時預覽

本套件最讚的一個地方就是有即時預覽功能,只要是 .NET 6 或以上就可以安裝套件作者開發的小工具 QuestPDF.Previewer ,搭配 .NET 的熱重載功能,開發時幾乎可以及時看到變更,超級方便。

安裝及時預覽套件

    
dotnet tool install QuestPDF.Previewer --global
    

下面順便附上更新和移除的指令:

更新套件:
    
dotnet tool update questpdf.previewer --global
    

移除套件
    
dotnet tool uninstall questpdf.previewer --global
    

啟用及時預覽功能

只要使用 ShowInPreviewer 就可以開啟及時預覽
    
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;

var document = Document.Create(container =>
{
    container.Page(page =>
    {
        // page content
    });
});

document.ShowInPreviewer();
    

要開啟熱重載功能請使用下列指令執行程式:
    
dotnet watch
    



參考資料:
GitHub - QuestPDF/QuestPDF
QuestPDF
Spire.PDF

留言