rdvojmoc / DinkToPdf

C# .NET Core wrapper for wkhtmltopdf library that uses Webkit engine to convert HTML pages to PDF.
MIT License
1.09k stars 417 forks source link

Error when trying to use custom paper size #107

Closed silvairsoares closed 4 years ago

silvairsoares commented 4 years ago

Since I didn't find a paper size that matched my need here: https://github.com/rdvojmoc/DinkToPdf/blob/b0546d21641eaef71f6fe0ddfd3998e8502baab7/src/DinkToPdf/Utils/PaperKind.cs

I'm trying to use the value "PaperKind.Custom" in the "GlobalSettings" object, however I get the following error stack:

ex.Message: "The given key 'Custom' was not present in the dictionary."
ex.Source: "System.Private.CoreLib"
ex.StackTrace: "at System.ThrowHelper.ThrowKeyNotFoundException[T](T key)
    at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
    at DinkToPdf.PechkinPaperSize.op_Implicit(PaperKind paperKind)
    at api.mstiDFE.Domain.PDF.Servicos.PDFService.<Create>d__2.MoveNext() 
    in C:\Users\Source\Workspace\api.mstiDFE\api.mstiDFE\Domain\PDF\Servicos\PDFService.cs:line 26"

I know I must be doing something wrong. So what would be the correct procedure for specifying a custom paper width, (in my case 80mm)?

The code I am using to generate the pdf:

byte[] file = null;
try
    {
        var globalSettings = new GlobalSettings
        {
            ColorMode = ColorMode.Color,
            Orientation = Orientation.Portrait,
            PaperSize = PaperKind.Custom; //<=PROBLEM HERE,
            Margins = new MarginSettings() { Top = MarginTop, Bottom = MarginBottom, Left = MarginLeft, Right = MarginRight },
            DocumentTitle = "Simple PDF document",
        };

        var objectSettings = new ObjectSettings
        {
            PagesCount = true,
            HtmlContent = templateHtml,
            WebSettings = { DefaultEncoding = "utf-8", EnableJavascript = true },
        };
        var pdf = new HtmlToPdfDocument()
        {
            GlobalSettings = globalSettings,
            Objects = { objectSettings }
        };

        file = _pdfConverter.Convert(pdf);
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return file;

Any tip, will be much appreciated. Thanks!

silvairsoares commented 4 years ago

I'm sorry, I didn't notice that my question had already been clarified in the question Change format Size