C# 使div元素与PDF输出中的A4大小相同

C# 使div元素与PDF输出中的A4大小相同,c#,html,css,selectpdf,C#,Html,Css,Selectpdf,我正在使用select.htmltopdfnuget包(selectpdf.com)生成PDF public static FileResult GetPdf(string html, string filename) { HtmlToPdf htmlToPdf = new HtmlToPdf(); htmlToPdf.Options.PdfPageSize = PdfPageSize.A4; PdfDocument pdfDocument = htmlToPdf.C

我正在使用
select.htmltopdf
nuget包(selectpdf.com)生成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;
}
html看起来像

<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>

身体{
保证金:0;
填充:0;
}
.第4页{
宽度:210毫米;
高度:297mm;
}
第1页
第2页
第3页
第4页
PDF输出如下所示

<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>


为什么div与A4格式不匹配?我如何解决这个问题

在CSS中,您可以使用
@media print
指定打印时的格式。您可以仅为打印而更改CSS的任何部分。但如果你只是把身体改成A4大小,那么就把你的
div
s调整到100%。只要将其放入CSS中就可以解决问题:

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

一些浏览器可能不完全支持这一点,我在我的示例中使用的是chrome。完整的HTML和CSS:


@媒体印刷品{
身体{
宽度:21cm;
身高:29.7厘米;
} 
}
身体{
保证金:0;
填充:0;
}
.第4页{
宽度:210毫米;
高度:297mm;
}
第1页
第2页
第3页
第4页

但是,如果我将div设置为body的100%,如何呈现其他页面?我现在使用

page-break-after

,这部分解决了问题。@Muflix您实际上不必更改div。我刚刚发布了一个屏幕截图,展示了如何使用媒体CSS。有趣的是,你的完整html+CSS是什么?我仍然无法解决这个问题:/I添加
@Html.Raw(@“@media print{body{width:21cm;height:29.7cm;}”)
并编辑pageA4类
。pageA4{width:100%;height:100%;}
但下一个div仍然打印在实际页面上。@Muflix我已经更新了我的答案以放入完整的代码。还谈到了浏览器的差异,这可能也是您的问题。我得到的输出与您完全相同。使用Tom Dee的代码也没什么帮助(尽管它在Chrome的打印预览中看起来不错)。它对您有效吗?您是否必须对生成pdf的代码进行任何更改?我添加了converter.Options.CssMediaType=htmlTopDFCSMediaType.Print;我发现,通过设置网页宽度为793,我会得到想要的结果。在文档中找到它: