A simple wrapper for wkhtmltopdf in ASP.NET Core
$ dotnet add package DevBox.WkHtmlToPdfA simple wrapper for wkhtmltopdf, enabling conversion of HTML or Razor Views directly into PDF files within ASP.NET Core applications.
This is a refactor from Wkhtmltopdf.NetCore since is deprecated.
It's also important to read this recommendations.
dotnet add package DevBox.WkHtmlToPdf
.
├── MyProject
│ ├── WkHtmlToPdf
│ │ ├── Windows
│ │ │ └── wkhtmltopdf.exe
│ │ └── Linux
│ │ └── wkhtmltopdf
│ └── MyProject.csproj
└── MyProject.sln
| OS/Distribution | Supported on | Architectures |
|---|---|---|
| Windows | 64-bit | |
| Debian | 11 bullseye | 64-bit |
The package could copy the binaries automatically and verify the OS, but it would be large. This way the executable becomes configurable.
.csproj:<ItemGroup>
<Content Include="WkHtmlToPdf\**\*.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>If you have wkhtmltopdf installed in your server, you can skip item 2 configuring through
SetExecutableFilePathusing an absolute path.
IServiceCollection:services.AddHttpContextAccessor();
services.AddWkHtmlToPdf(options =>
{
options.SetExecutableFilePath("custom-absolute-path/wkhtmltopdf.exe");
// Customize the default options
options.Title = "My PDF";
options.PageSize = PageSize.A4;
options.Orientation = PdfOrientation.Landscape;
// ...
});WkHtmlToPdf/Windows/wkhtmltopdf.exeWkHtmlToPdf/Linux/wkhtmltopdfWkHtmlToPdf/Mac/wkhtmltopdflibgdiplus and libc6-dev.apt-get update
apt-get -y install libgdiplus libc6-devFROM mcr.microsoft.com/dotnet/aspnet:7.0
# ...
RUN apt-get update -qq && apt-get -y install libgdiplus libc6-devRUN apt-get update -qq && apt-get -y install libgdiplus libc6-dev fontconfig fonts-liberation
RUN fc-cache -f -vInject IPdfConverterService in any class you need.
var buffer = await _pdfConverterService.FromHtmlAsync("<html>...</html>", options =>
{
// Overrides the default options
options.Title = "My Report";
});var buffer = await _pdfConverterService.FromViewAsync("PathToView/ViewName", model, options =>
{
// If "true", you'll find all temporary files used by wkhtmltopdf in "bin/Debug/.../WkHtmlToPdf/Temp"
// or the path specified in ".SetTempPath"
options.KeepTempFiles = Debugger.IsAttached;
// Overrides the default options
options.HeaderFooter.HeaderHtml = "PathToView/HeaderViewName";
});