程序问答   发布时间:2022-05-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在 ASP.net core 3.1 Razor Pages 中打印 PDF大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在 ASP.net core 3.1 Razor Pages 中打印 PDF?

开发过程中遇到在 ASP.net core 3.1 Razor Pages 中打印 PDF的问题如何解决?下面主要结合日常开发的经验,给出你关于在 ASP.net core 3.1 Razor Pages 中打印 PDF的解决方法建议,希望对你解决在 ASP.net core 3.1 Razor Pages 中打印 PDF有所启发或帮助;

为了学习 ASP.net 核心,我使用 ASP.NET 核心 3.1 创建了一个简单的 CRUD 应用程序。我想将我的详细信息页面打印为发票。我环顾四周,似乎在完整的 .Net Framework 中打印 pdf 更可用。@H_772_3@

谁能指出我正确的方向?我遇到过像 SELEctpdf、WKHTMLTOpdf、pdfSharp 这样的免费库,但坦率地说,这些样本是 pre-asp.net 核心,不能安静地将它与 asp.net 核心 Razor Pages 集成。实际上,如果我没记错的话,上面提到的一些库与 Razor Pages Core 不兼容。@H_772_3@

解决方法

免责声明:我为 SELEctPdf 工作。@H_772_3@

SELEctPdf 确实支持 ASP.NET Core + Razor Page。可从 SELEctPdf 网站下载示例。@H_772_3@

此处的示例代码:@H_772_3@

@page
@model SELEctPdf.Samples.Pages.ConvertUrlToPdfModel
@{
    Layout = "~/Pages/_Layout.cshtml";
    ViewData["title"] = "SELEctPdf Free Html To Pdf Converter for .NET Core - Convert from Url to Pdf - C# / ASP.NET Core MVC6";
    ViewData["Description"] = "SELEctPdf Convert from Url to Pdf Sample for C# ASP.NET MVC. Pdf Library for .NET with full sample code in C# and VB.NET.";
    ViewData["Keywords"] = "convert from url to pdf,pdf library,sample code,html to pdf,pdf converter";
}

<form method="post">
    <article class="post type-post status-publish format-standard hentry">
        <header class="entry-header">
            <h1 class="entry-title">SELEctPdf Free Html To Pdf Converter for .NET Core - Convert from Html to Pdf - C# / ASP.NET Core MVC6 Sample</h1>
        </header>
        <!-- .entry-header -->

        <div class="entry-content">
            <p>
                This sample shows how to use SELEctPdf html to pdf converter to convert an url to pdf,also setTing a few properties.
            </p>
            <p>
                Url:<br />
                <input type="text" style="width: 90%;" value="https://SELEctpdf.com" asp-for="TxtUrl" />
            </p>
            <div class="col2">
                Pdf Page Size:<br />
                <SELEct asp-for="DdlPageSize" asp-items="Model.PageSizes"></SELEct>
                <br />
                <br />
                Pdf Page Orientation:<br />
                <SELEct asp-for="DdlPageOrientation" asp-items="Model.PageOrientations"></SELEct><br />
                <br />
            </div>
            <div class="col2">
                Web Page Width:<br />
                <input type="text" style="width: 50px;" value="1024" asp-for="TxtWidth" /> px<br />
                <br />
                Web Page Height:<br />
                <input type="text" style="width: 50px;" value="" asp-for="TxtHeight" /> px<br />
                (leave empty to auto detect)<br />
                <br />

            </div>
            <div class="col-clear"></div>
            <p>
                <input type="submit" name="BtnConvert" value="Create PDF" class="mybutton" />
            </p>
        </div>
        <!-- .entry-content -->
    </article>
</form>

// C# code below

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace SELEctPdf.Samples.Pages
{
    public class ConvertUrlToPdfModel : PageModel
    {
        public void OnGet()
        {
            DdlPageSize = "A4";
        }

        [BindProperty]
        public String TxtUrl { get; set; }

        [BindProperty]
        public String DdlPageSize { get; set; }

        public List<SELEctListItem> PageSizes { get; } = new List<SELEctListItem>
        {
            new SELEctListItem { Value = "A1",Text = "A1" },new SELEctListItem { Value = "A2",Text = "A2" },new SELEctListItem { Value = "A3",Text = "A3" },new SELEctListItem { Value = "A4",Text = "A4" },new SELEctListItem { Value = "A5",Text = "A5" },new SELEctListItem { Value = "Letter",Text = "Letter" },new SELEctListItem { Value = "HalfLetter",Text = "HalfLetter" },new SELEctListItem { Value = "Ledger",Text = "Ledger" },new SELEctListItem { Value = "Legal",Text = "Legal" },};

        [BindProperty]
        public String DdlPageOrientation { get; set; }

        public List<SELEctListItem> PageOrientations { get; } = new List<SELEctListItem>
        {
            new SELEctListItem { Value = "PorTrait",Text = "PorTrait" },new SELEctListItem { Value = "Landscape",Text = "Landscape" },};

        [BindProperty]
        public String TxtWidth { get; set; }

        [BindProperty]
        public String TxtHeight { get; set; }

        public IActionResult OnPost()
        {
            // read parameters from the webpage
            PdfPageSize pageSize =
                (PdfPageSizE)Enum.Parse(typeof(PdfPageSizE),DdlPageSize,truE);

            PdfPageOrientation pdfOrientation =
                (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),DdlPageOrientation,truE);

            int webPageWidth = 1024;
            try
            {
                webPageWidth = System.Convert.ToInt32(TxtWidth);
            }
            catch { }

            int webPageHeight = 0;
            try
            {
                webPageHeight = System.Convert.ToInt32(TxtHeight);
            }
            catch { }

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.options.PdfPageSize = pageSize;
            converter.options.PdfPageOrientation = pdfOrientation;
            converter.options.WebPageWidth = webPageWidth;
            converter.options.WebPageHeight = webPageHeight;

            // create a new pdf document converTing an url
            PdfDocument doc = converter.ConvertUrl(TxtUrl);

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

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf,"application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}
,

我遇到了像 SELEctPDF、WKHTMLTOPDF、PDFSharp 这样的免费库,但坦率地说,这些示例是 pre-asp.net 核心,无法安静地将它与 asp.net 核心 Razor Pages 集成。@H_772_3@

我建议你可以使用客户端库。因为你提到的都是服务端库,它们都需要找到视图并转换为字符串。据我所知,似乎没有这种直接转换剃刀的方法pages 到 String。所以我建议你可以使用 jsPDF 库。@H_772_3@

这是一个完整的工作演示:@H_772_3@

@page
@model DetailsModel
<div id="details">       //be sure add this id...

    <h1>Details</h1>

    <div>
        <h4>test</h4>
        <hr />
        <dl class="row">
            <dt class="col-sm-2">
                @Html.DisplayNameFor(model => model.test.Name)
            </dt>
            <dd class="col-sm-10">
                @Html.DisplayFor(model => model.test.Name)
            </dd>
        </dl>
    </div>
    <div>
        <a asp-page="./Edit" asp-route-id="@model.test.Id">Edit</a> |
        <a asp-page="./Index">BACk to List</a>
    </div>
</div>

<button onclick="javascript:demoFromHTML();">Generate PDF</button>

@section Scripts
{
    <script src="https://cdnjs.cloudFlare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
    <script>
        function demoFromHTML() {
            var pdf = new jsPDF('p','pt','letter');
            // source can be HTML-formatted String,or a reference
            // to an actual DOM element from which the text will be scraped.
            source = $('#details')[0];

            // we support special element handlers. Register them with jQuery-style
            // ID SELEctor for either ID or node name. ("#iAmID","div","span" etc.)
            // There is no support for any other type of SELEctors
            // (class,of compound) at this time.
            specialElementHandlers = {
                // element with id of "bypass" - jQuery style SELEctor
                '#bypassme': function (element,renderer) {
                    // true = "handled elsewhere,bypass text extraction"
                    return true
                }
            };
            margins = {
                top: 80,bottom: 60,left: 40,width: 522
            };
            // all coords and widths are in jsPDF instance's declared units
            // 'inches' in this case
            pdf.fromHTML(
                source,// HTML String or DOM elem ref.
                margins.left,// x coord
                margins.top,{ // y coord
                'width': margins.width,// max width of content on PDF
                'elementHandlers': specialElementHandlers
            },function (disposE) {
                    // dispose: object with X,Y of the last line add to the PDF
                    //          this allow the insertion of new lines after html
                    pdf.save('Test.pdf');
                },margins);
        }
    </script>
}
,

您也可以查看 Syncfusion,他们有一个很棒的图书馆。@H_772_3@

https://www.syncfusion.com/pdf-framework/net-core/pdf-library@H_772_3@

大佬总结

以上是大佬教程为你收集整理的在 ASP.net core 3.1 Razor Pages 中打印 PDF全部内容,希望文章能够帮你解决在 ASP.net core 3.1 Razor Pages 中打印 PDF所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。