A 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.
- Add DevBox.WkHtmlToPdf package to your project:
dotnet add package DevBox.WkHtmlToPdf- Download the desirable version of wkhtmltopdf and add to your project:
.
├── 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.
- Edit your
.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.
- Configure your
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;
// ...
});- Default executable file path:
- Windows:
WkHtmlToPdf/Windows/wkhtmltopdf.exe - Linux:
WkHtmlToPdf/Linux/wkhtmltopdf - MAC:
WkHtmlToPdf/Mac/wkhtmltopdf
- Windows:
- If you work with Linux or Docker, you need to install
libgdiplusandlibc6-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-dev- If you have problems with differents fonts in Windows vs Docker, you can try:
RUN 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.
- Converting a HTML:
var buffer = await _pdfConverterService.FromHtmlAsync("<html>...</html>", options =>
{
// Overrides the default options
options.Title = "My Report";
});- Converting a Razor View:
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";
});