Search code examples
c#html-renderinghtml-renderer

How to give custom size to PdfSharp generated Pdf


I was trying to generate a pdf from HTML which containing a table using PdfSharp and HTMLRenderer. The following shows the code.

            pdf = PdfGenerator.GeneratePdf(html, PageSize.A3);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }

Is there any possibility for me to provide a custom size to the PDF and change the orientation of the page. I am using a memory stream to show the PDF directly on the browser display.


Solution

  • You can use the PdfGenerateConfig parameter of the GeneratePdf method to specify a custom page size using the ManualPageSize property.

    Use the PageOrientation to get standard page sizes in landscape.

    Code from comment:

    var config = new PdfGenerateConfig();
    config.PageOrientation = PageOrientation.Landscape;
    config.ManualPageSize = new PdfSharp.Drawing.XSize(1080, 828);
    
    pdf = PdfGenerator.GeneratePdf(html, config);