使用Rotativa在ASP.NET Core MVC中創建PDF

来源:https://www.cnblogs.com/ZaraNet/archive/2019/02/22/10417056.html
-Advertisement-
Play Games

在本文中,我們將學習如何使用Rotativa.AspNetCore工具從ASP.NET Core中的視圖創建PDF。如果您使用ASP.NET MVC,那麼Rot​​ativa工具已經可用,我們可以使用它來生成pdf。 創建一個MVC項目,無論您是core或不core,都可以nuget下包.命令如下: ...


在本文中,我們將學習如何使用Rotativa.AspNetCore工具從ASP.NET Core中的視圖創建PDF。如果您使用ASP.NET MVC,那麼Rot​​ativa工具已經可用,我們可以使用它來生成pdf。

創建一個MVC項目,無論您是core或不core,都可以nuget下包.命令如下:

Install-Package Rotativa
#或者
Install-Package Rotativa.AspNetCore

這個工具由義大利人Giorgio Bozio創建。他需要在ASP.NET MVC中生成pdf,並且重覆的任務是設置一種方法來創建PDF文檔,用於業務流程或報告,下麵廢話不多說,我們開始吧。

在startup.cs類中配置Rotativa.AspNetCore設置

我們在Configure方法內的startup.cs類中添加此設置,以設置要訪問的wkhtmltopdf.exe文件的相對路徑。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            RotativaConfiguration.Setup(env);
        }

 我們需要在wwwroot中添加Rotativa文件夾,然後放入這兩個exe,我把這兩個文件已經放到了百度雲盤。

然後我們添加一個Demo控制器,定義一個Get方法,其定義如下,通過ViewAsPdf方法,就可以通過pdf的形式去套住cshtml,也就達到了pdf的效果。

public class DemoController : Controller
    {
        [HttpGet]
        public IActionResult DemoViewAsPdf()
        {
            return new ViewAsPdf("DemoViewAsPdf");
        }
    }

 就現在,我們需要通過控制器去創建一個視圖,然後在視圖中有如下定義:

@{
    ViewData["Title"] = "DemoViewAsPdf";
}
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <p>Hello AspNetCore!!</p>
</body>
</html>  

現在,我們把頁面重定與

http://localhost:55999/Demo/DemoViewAsPdf

邊距

除了普通的展示pdf,我們還可以進行操作,例如下載,列印。當然如果寬和高不太滿意,你可以對視圖進行設置,其中有一個類是對視圖進行配置的,其定義如下,有四大配置值。

public class Margins
    {
        [OptionFlag("-B")]
        public int? Bottom;
        [OptionFlag("-L")]
        public int? Left;
        [OptionFlag("-R")]
        public int? Right;
        [OptionFlag("-T")]
        public int? Top;

        public Margins();
        public Margins(int top, int right, int bottom, int left);

        public override string ToString();
    }

在控制器中直接new出它,然後直接return,和上面類似,現在你可以將html中的p標簽添加一些內容,然後看一下效果。

[HttpGet]
        public IActionResult DemoViewAsPdf()
        {
            return new ViewAsPdf("DemoPageMarginsPDF")
            {
                PageMargins = { Left = 20, Bottom = 20, Right = 20, Top = 20 },
            };
        }

 就這樣,我們再次啟動,可見已經有了外邊距!

橫向與縱向

它還給我們提供了橫向還是豎向的pdf效果,如以下定義:

[HttpGet]
        public IActionResult DemoViewAsPdf(string Orientation)
        {
            if (Orientation == "Portrait")
            {
                var demoViewPortrait = new ViewAsPdf("DemoViewAsPDF")
                {
                    FileName = "Invoice.pdf",
                    PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
                };
                return demoViewPortrait;
            }
            else
            {
                var demoViewLandscape = new ViewAsPdf("DemoViewAsPDF")
                {
                    FileName = "Invoice.pdf",
                    PageOrientation = Rotativa.AspNetCore.Options.Orientation.Landscape,
                };
                return demoViewLandscape;
            }
        }

通過 http//localhost:60042/demo/DemoOrientationPDF?Orientation=Portrait 或者其它路由進行訪問,你對比以下就可以看到效果。

設置PDF大小

 基本上都是A4,枚舉里很多值,自己看~

[HttpGet]
        public IActionResult DemoViewAsPdf(string Orientation)
        {
            return new ViewAsPdf("DemoPageSizePDF")
            {
                PageSize = Rotativa.AspNetCore.Options.Size.A4
            };
        }

小案例

 創建一個模型,這是一個非常簡單的模型,定義如下:

public class Customer
    {
        public int CustomerID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Country { get; set; }
        public string City { get; set; }
        public string Phoneno { get; set; }
    }

在控制器中new幾個對象,然後返回pdf。

[HttpGet]
        public IActionResult DemoViewAsPdf()
        {
            List<Customer> customerList = new List<Customer>() {
                 new Customer { CustomerID = 1, Address = "Taj Lands Ends 1", City = "Mumbai" , Country ="India", Name ="Sai", Phoneno ="9000000000"},
                 new Customer { CustomerID = 2, Address = "Taj Lands Ends 2", City = "Mumbai" , Country ="India", Name ="Ram", Phoneno ="9000000000"},
                 new Customer { CustomerID = 3, Address = "Taj Lands Ends 3", City = "Mumbai" , Country ="India", Name ="Sainesh", Phoneno ="9000000000"},
                 new Customer { CustomerID = 4, Address = "Taj Lands Ends 4", City = "Mumbai" , Country ="India", Name ="Saineshwar", Phoneno ="9000000000"},
                 new Customer { CustomerID = 5, Address = "Taj Lands Ends 5", City = "Mumbai" , Country ="India", Name ="Saibags", Phoneno ="9000000000"}
            };
            return new ViewAsPdf("DemoModelPDF", customerList);
        }

在視圖中,我們只是迭代集合,渲染頁面。

 

@model List<MvcHtmlToPdf.Models.Customer>
@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div class="container">
        <h2>Customer</h2>
        <p>Customer Details</p>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>CustomerID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Country</th>
                    <th>City</th>
                    <th>Phoneno</th>
                </tr>
            </thead>
            <tbody>

                @foreach (var item in Model)
                {
                    <tr>
                        <td>@item.CustomerID</td>
                        <td>@item.Name</td>
                        <td>@item.Address</td>
                        <td>@item.Country</td>
                        <td>@item.City</td>
                        <td>@item.Phoneno</td>
                    </tr>
                }

            </tbody>
        </table>
    </div>
</body>
</html> 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 實常式序的界面效果如下圖所示: 在表單中的搜索條件有姓名,學號,成績。他們在一行中按照水平三等分排列。 在cshtml中用html實現上述表單效果的的代碼如下: 1 <form class="form-horizontal" role="form"> 2 <div class="row"> 3 <d ...
  • 寫程式的過程應該是一種藝術創作過程,我們寫出來的程式體現了我們的技術水平和個人修養, 也就是說作為程式員,自己寫的程式就是自己的臉面。讓自己有臉有面的第一步就是要遵循程 序編碼規範,這裡總結一些程式編寫規範。 1. 命名規範 表達清晰是命名規範的核心,常見的命名分格有: 1.1 Pascal風格 包 ...
  • //載入配置文件 var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, relo ...
  • 這一篇繼續完善webnotebook,如果你讀過上一篇的內容,你應該知道怎麼去掛載webnotebook日誌和容器的遠程訪問,但是這些還遠不夠,webnotebook 總要和一些資料庫打交道吧,比如說mysql,mongodb,redis,通常情況下這些存儲設備要麼是以容器的方式承載,要麼是由DBA ...
  • ///這個是拿別人的,找到好多這個方法,溜了,不知道誰是原創 protected void btnPrint_Click(object sender, EventArgs e) { string url = "QR_CodePrintView.aspx?Code=" + tbAssetCode.Te ...
  • 一.管理資料庫架構概述 EF Core 提供兩種主要方法來保持 EF Core 模型和資料庫架構同步。一是以 EF Core 模型為基準,二是以資料庫為基準。 (1)如果希望以 EF Core 模型為準,請使用遷移。 對 EF Core 模型進行更改時,此方法會以增量方式將相應架構更改應用到資料庫, ...
  • 1 ...
  • 1. Unobtrusive JavaScript介紹 說到Unobtrusive Ajax,就要談談UnobtrusiveJavaScript了,所謂Unobtrusive JavaScript即為非侵入式JavaScript(即將Js代碼與html代碼分離,方便閱讀與維護),是目前在Web開發領 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...