Search code examples
c#htmlcssselectpdf

Make div element the same size as A4 in PDF output


I am using select.htmltopdf nuget package (selectpdf.com) to generate PDF.

public static FileResult GetPdf(string html, string filename)
{

    HtmlToPdf htmlToPdf = new HtmlToPdf();
    htmlToPdf.Options.PdfPageSize = PdfPageSize.A4; 
    PdfDocument pdfDocument = htmlToPdf.ConvertHtmlString(html);

    // save pdf document 
    byte[] pdf = pdfDocument.Save();

    // close pdf document 
    pdfDocument.Close();

    // doc.Save("document.pdf");
    FileResult fileResult = new FileContentResult(pdf, "application/pdf");
    fileResult.FileDownloadName = $"{filename}.pdf";
    return fileResult;
}

the html looks like

<style>
    body {
        margin: 0;
        padding: 0;
    }

    .pageA4 {
        width: 210mm;
        height: 297mm;
    }
</style>
<html>
<head>
</head>
<body>
    <div class="pageA4" style="background-color:yellow"><h1>page 1</h1></div>
    <div class="pageA4" style="background-color:violet"><h1>page 2</h1></div>
    <div class="pageA4" style="background-color:yellow"><h1>page 3</h1></div>
    <div class="pageA4" style="background-color:violet"><h1>page 4</h1></div>
</body>
</html>

and the PDF output looks like

enter image description here

Why the div does not match A4 format ? How can I solve this issue ?


Solution

  • In CSS you can use @media print to specify formatting when printed. You can change any part of the CSS just for printing. But if you just change body to A4 size then make your divs to fit into that 100%. Just putting this into your CSS should solve the problem:

    @media print {
            body{
                width: 21cm;
                height: 29.7cm;
           } 
        }
    

    enter image description here

    Some browsers may not fully support this, I am using chrome in my example. Full HTML and CSS:

    <html>
    <style>
    @media print {
            body{
                width: 21cm;
                height: 29.7cm;
           } 
        }
        body {
            margin: 0;
            padding: 0;
        }
    
        .pageA4 {
            width: 210mm;
            height: 297mm;
        }
    </style>
    <html>
    <head>
    </head>
    <body>
        <div class="pageA4" style="background-color:yellow"><h1>page 1</h1></div>
        <div class="pageA4" style="background-color:violet"><h1>page 2</h1></div>
        <div class="pageA4" style="background-color:yellow"><h1>page 3</h1></div>
        <div class="pageA4" style="background-color:violet"><h1>page 4</h1></div>
    </body>
    </html>