简体   繁体   English

在 ASP.net 内核 3.1 Razor 页中打印 PDF

[英]Printing PDF in ASP.net core 3.1 Razor Pages

In my quest to learn ASP.net core I've created a simple CRUD application using asp.net core 3.1.为了学习 ASP.net 内核,我使用 asp.net 内核 3.1 创建了一个简单的 CRUD 应用程序。 I want to print my Details page as a Invoice.我想将我的详细信息页面打印为发票。 I have looked around and it seems like printing PDF in full.Net Framework was more available.我环顾四周,似乎在 full.Net Framework 中打印 PDF 更可用。

Can anyone point me in the right direction?谁能指出我正确的方向? I have come across free libraries like SelectPDF, WKHTMLTOPDF, PDFSharp but quiet frankly the samples are pre- asp.net core and cannot quiet integrate it with asp.net core Razor Pages.我遇到过 SelectPDF、WKHTMLTOPDF、PDFSharp 等免费库,但坦率地说,这些样本是 asp.net 内核之前的,无法将它与 asp.net 内核 ZE405C1DF83BD248A67FC9A91227 安静地集成Actually, if I'm not mistaken some of the libraries mentioned above are not compatible with Razor Pages Core.实际上,如果我没记错的话,上面提到的一些库与 Razor Pages Core 不兼容。

I have come across free libraries like SelectPDF, WKHTMLTOPDF, PDFSharp but quiet frankly the samples are pre- asp.net core and cannot quiet integrate it with asp.net core Razor Pages.我遇到过 SelectPDF、WKHTMLTOPDF、PDFSharp 等免费库,但坦率地说,这些样本是 asp.net 内核之前的,无法将它与 asp.net 内核 ZE405C1DF83BD248A67FC9A91227 安静地集成

I suggest that you could use client side library.Because what you metioned are all server side libraries,they all need to find the view and convert to string.As far as I known,it seems no such direct method to convert razor pages to string.So I suggest that you could use jsPDF library.我建议你可以使用客户端库。因为你提到的都是服务器端库,它们都需要找到视图并转换为字符串。据我所知,似乎没有直接的方法将 razor 页面转换为字符串.所以我建议你可以使用jsPDF库。

Here is a whole working demo:这是一个完整的工作演示:

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

Disclaimer: I work for SelectPdf.免责声明:我为 SelectPdf 工作。

SelectPdf does support ASP.NET Core + Razor Page. SelectPdf 确实支持 ASP.NET 核心 + Razor 页面。 Samples are available via download from SelectPdf website.样本可从 SelectPdf 网站下载。

Sample code here:示例代码在这里:

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

        }
    }
}

You can also check with Syncfusion, they have a great library.您也可以查看 Syncfusion,他们有一个很棒的库。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Razor 页面的 ASP.NET Core 3.1 路由 - ASP.NET Core 3.1 Routing for Razor Pages 路由覆盖在 asp.net 核心 3.1 razor 页面中不起作用 - Route Override not working in asp.net core 3.1 razor pages ASP.Net Core 3.1 Razor Pages 和使用 Dapper 的 CRUD 操作 - ASP.Net Core 3.1 Razor Pages and CRUD operation with Dapper 上传 asp.net 内核 3.1 Razor - Uploading asp.net core 3.1 Razor asp-controller 和 asp-action 在 ASP.NET Core 3.1 Razor Pages 应用程序中不起作用 - asp-controller and asp-action not working in ASP.NET Core 3.1 Razor Pages app Class 部分页面的库标记帮助程序在 ASP.NET 核心 3.1 Razor 页面应用程序中不起作用 - Class Library Tag Helper for Partial Pages not working in ASP.NET Core 3.1 Razor Pages application ASP.NET Core 3.1 Razor 页面 - 向标题添加不同的子对象 - ASP.NET Core 3.1 Razor pages - adding different child objects to header 在 ASP.NET Core 3.1 MVC+Razor Pages+Web API 中设置默认页面 - Set default page in ASP.NET Core 3.1 MVC+Razor Pages+Web API 带有 ASP.NET Core 3.1 Razor 页面的 Microsoft Identity Platform 中的可疑错误 - Suspected bug in Microsoft Identity Platform with ASP.NET Core 3.1 Razor Pages Asp.net core 3.1 with Razor 页面重定向到索引页面而不是预期页面 - Asp.net core 3.1 with Razor Pages redirects to the Index page instead of the intended page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM