如何在 ASP.NET Core 3.1 MVC 中设置 wkhtmltopdf 选项?

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

我正在尝试使用 wkhtmltopdf 和 ASP.NET Core 3.1 生成自定义 PDF,这里是文档:https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

我的主要问题是:我应该如何以及在何处放置这些选项?在 cshtml 里面?在控制器里面?在哪里?

我无法在互联网上找到如何在 ASP.NET Core MVC 中使用它的文档。

这是我的代码,运行正常:

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);
}

这会生成一个 PDF:

但是如果您注意到 PDF 有边距,我想删除这些边距。我在文档中发现我必须使用 --margin-top 0 但我不知道把它放在哪里才能让它工作。

我试过了:

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);
}

但不起作用,我试图将它放在 cshtml 代码中的普通 html 中,但也不起作用。我的问题看起来很简单,但我无法解决这个问题,我该如何解决?

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

您的共享文档用于教您如何使用命令行对您的pdf.It进行一些操作,不用于在代码隐藏中工作。

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.

您需要通过创建 ConvertOptions 实例来添加边距:

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");
}

更详细的用法您可以在github上下载示例代码:

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