3

我正在使用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.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>

PDF输出看起来像

在此处输入图像描述

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

4

1 回答 1

2

在 CSS 中,您可以使用它@media print来指定打印时的格式。您可以更改 CSS 的任何部分以用于打印。但是,如果您只是将 body 更改为 A4 尺寸,那么请让您div的 s 适合该 100%。只需将其放入您的 CSS 即可解决问题:

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

在此处输入图像描述

某些浏览器可能不完全支持这一点,我在示例中使用的是 chrome。完整的 HTML 和 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>

于 2019-08-30T15:33:08.360 回答