Convert HTML to PDF in .NET

后端 未结 30 1832
不知归路
不知归路 2020-11-22 00:28

I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout

30条回答
  •  粉色の甜心
    2020-11-22 00:34

    Quite likely most projects will wrap a C/C++ Engine rather than implementing a C# solution from scratch. Try Project Gotenberg.

    To test it

    docker run --rm -p 3000:3000 thecodingmachine/gotenberg:6
    

    Curl Example

    curl --request POST \
        --url http://localhost:3000/convert/url \
        --header 'Content-Type: multipart/form-data' \
        --form remoteURL=https://brave.com \
        --form marginTop=0 \
        --form marginBottom=0 \
        --form marginLeft=0 \
        --form marginRight=0 \
        -o result.pdf
    

    C# sample.cs

    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.IO;
    using static System.Console;
    
    namespace HelloWorld
    {
        class Program
        {
            public static async Task Main(string[] args)
            {
                try
                {
                    var client = new HttpClient();            
                    var formContent = new MultipartFormDataContent
                        {
                            {new StringContent("https://duckduckgo.com/"), "remoteURL"},
                            {new StringContent("0"), "marginTop" }
                        };
                    var result = await client.PostAsync(new Uri("http://localhost:3000/convert/url"), formContent);
                    await File.WriteAllBytesAsync("duckduck.com.pdf", await result.Content.ReadAsByteArrayAsync());
                }
                catch (Exception ex)
                {
                    WriteLine(ex);
                }
            }
        }
    }
    

    To compile

    csc sample.cs -langversion:latest -reference:System.Net.Http.dll && mono ./sample.exe
    

提交回复
热议问题