Search code examples
c#asp.net-core-mvcwkhtmltopdf

How to set wkhtmltopdf options in ASP.NET Core 3.1 MVC?


I am trying to generate a custom PDF using wkhtmltopdf with ASP.NET Core 3.1, here are the docs: https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

My main problem is: how and where should I put those options? Inside cshtml? Inside a controller? Where?

I cannot find documentation over the internet how to use it in ASP.NET Core MVC.

This is my code that is working ok:

public async Task<IActionResult> PDF(int? id)
{
        if(id == null)
        {
            return StatusCode(400);
        }

        var comanda = _comandasRepository.Get((int)id);

        if(comanda == null)
        {
            return StatusCode(404);
        }

        return await _generatePdf.GetPdf("Views/Comandas/PDF.cshtml", comanda);
}

This generates a PDF:

enter image description here

But if you notice that PDF has margins, I want to remove these margins. I found in the docs that I have to use --margin-top 0 but I do not know where to put it to make it work.

I tried:

public async Task<IActionResult> PDF(int? id)
{
    if(id == null)
    {
        return StatusCode(400);
    }

    var comanda = _comandasRepository.Get((int)id);

    if(comanda == null)
    {
        return StatusCode(404);
    }

    return await _generatePdf.GetPdf("--margin-top 0 Views/Comandas/PDF.cshtml", comanda);
}

but does not work, and I tried to put it in a plain html inside cshtml code and didn't work either. My issue looks so simple but I cannot make this work, how do I solve this?


Solution

  • My main problem is: how and where should I put those options? Inside cshtml? Inside a controller? Where?

    Your shared document is used to teach you how to use command line to do some operation with your pdf.It does not used to work in code behind.

    But if you notice that PDF has margins, I want to remove these margins. I found in the docs that I have to use --margin-top 0 but I do not know where to put it to make it work.

    You need add the margins by creating ConvertOptions instance:

    public async Task<IActionResult> PDF(int? id)
    {
        var options = new ConvertOptions
        {
            PageMargins = new Wkhtmltopdf.NetCore.Options.Margins()
            {
                Top=0
            }
        };
    
        _generatePdf.SetConvertOptions(options);
    
        var comanda = _comandasRepository.Get((int)id);
    
        var pdf = await _generatePdf.GetByteArray("Views/Comandas/PDF.cshtml", comanda);
    
        var pdfStream = new System.IO.MemoryStream();
        pdfStream.Write(pdf, 0, pdf.Length);
        pdfStream.Position = 0;
        return new FileStreamResult(pdfStream, "application/pdf");
    }
    

    More detailed usage you could download the example code on github:

    https://github.com/fpanaccia/Wkhtmltopdf.NetCore.Example