當前位置: 妍妍網 > 碼農

使用.Net將HTML簡歷匯出為PDF格式

2024-02-06碼農

現在有許多將HTML匯出PDF的第三方包,這裏介紹使用的是 Select.HtmlToPdf.NetCore

使用Select.HtmlToPdf.NetCore

  1. 整體思路是將cshtml內容讀出來,然後再轉為Pdf文件

  2. 讀取cshtml內容有兩種方法,第一種使用第三方包 RazorEngine.NetCore ,第二種使用官方方法進行讀取。(註意兩種方法的cshtml內容略有不同)

效果圖展示

我把所有的原始碼都上傳到了我的個人Github,有需要的請自取:https://github.com/WeiMing0803/ExportPdf

首先使用 ChatGPT 生成個人簡歷資訊

程式碼部份

HomeController.cs :

publicasync Task<IActionResult> ToPdf(){ PdfDocument pdfDocument = new PdfDocument(); HtmlToPdf converter = new HtmlToPdf();//例項化一個html到pdf轉換器物件 converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;//設定頁面方向 converter.Options.PdfPageSize = PdfPageSize.A4;//設定頁面大小 converter.Options.MarginTop = 10;//設定頁邊距 converter.Options.MarginBottom = 10; converter.Options.MarginLeft = 10; converter.Options.MarginRight = 10; PdfReportModel model = new PdfReportModel { Name = "彭於晏", Email = "[email protected]" };//string htmlResult = readByEngineRazor(model);//第一種方法,使用RazorEngine.NetCore讀取Cshtml檔string htmlResult = await readCshtml(model);//第二種方法if (!string.IsNullOrEmpty(htmlResult)) { pdfDocument = converter.ConvertHtmlString(htmlResult); }string savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $@"ExportPDF\{DateTime.Now.ToString("yyyyMMdd")}"); Directory.CreateDirectory(savePath);string filename = Path.Combine(savePath, $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.pdf"); pdfDocument.Save(filename);byte[] bytes = System.IO.File.ReadAllBytes(filename);return File(bytes, "application/pdf", Path.GetFileName(filename));}privatestringreadByEngineRazor(PdfReportModel model){string template = System.IO.File.ReadAllText("Views/Report/PdfReport.cshtml");string htmlResult = Engine.Razor.RunCompile(template, "PdfReport", typeof(PdfReportModel), model);return htmlResult;}privateasync Task<string> readCshtml(PdfReportModel model){string htmlResult = await _viewRenderService.RenderToStringAsync("Report/PdfReport", model);return htmlResult;}

TemplateGadgetProvider.cs :

public classTemplateGadgetProvider{publicstatic TemplateGadgetProvider _instance;publicstatic TemplateGadgetProvider Instance {get {if (_instance == null) _instance = new TemplateGadgetProvider();return _instance; } }publicstringLoad(string virtualPath) {return File.ReadAllText(virtualPath); }}

pdfReport.css :

Css樣式檔:點選檢視詳細內容
  • html {font-family: 'Open Sans', sans-serif;background: whitesmoke;}a {text-decoration: none;color: black;}hr {background: grey;}#container {position: relative;display: flex;}#profile {flex: 15%;display: block;position: relative;margin: 5%2%010%;width: 100%;height: 100%;}#info-cards {flex: 55%;display: block;margin-top: 5%;margin-right: 10%;width: 100%;height: 100%;}#image {position: relative;overflow: hidden;}#image,#profile-photo {position: relative;width: 80px;height: 80px;border-radius: 10px;}#image > a {position: absolute;top: 0;left: 0;background: rgba(0, 0, 0, 0.5) !important;height: 100%;width: 100%;display: none; }#image > a > i {-webkit-text-stroke: 1px#ffffffdd;padding: 40%; }#image:hovera {display: block; }#name {font-size: 23px!important;line-height: 20px!important;}#about,.card > ul > li {padding: 00015px;position: relative;display: inline-block;width: 100%;}#about {font-size: 20px!important;padding: 0!important;}#name,#about > p {font-weight: bolder;font-family: 'Open Sans', sans-serif; }#email {font-size: 15px!important;font-weight: bold !important;font-family: 'Cutive Mono', monospace;}#college,#email,#year-graduation,#education,#more-about,#telephone,#fax {color: #555;font-size: 13.5px;}strong,span {color: black;font-size: 16px;}#social-links,#about {display: inline-block;}#social-links {margin-bottom: 12px;}#social-linksa {margin: 010px; }#edit-intro {display: block;color: #097bbf;font-family: 'Nunito', sans-serif;}.fab {font-size: 1.1em;}.fab,.fas {color: whitesmoke;}#about > a {top: 4px;right: 8px;}.edit {top: 19px;right: 10px;}#about > a,.edit {position: absolute;font-size: 15px!important;}.stroke-transparent {-webkit-text-stroke: 1px#000;-webkit-text-fill-color: transparent;}.blue {color: #097bbf!important;font-size: 13px;}.stroke-transparent-blue {-webkit-text-stroke: 1px#097bbf;-webkit-text-fill-color: transparent;}.card {box-shadow: 03px10px0rgba(0, 0, 0, .1);overflow-x: hidden;margin-bottom: 30px;padding: 15px30px30px30px;background-color: #fff;}.card > p {color: #0e141e;font-weight: bolder;font-size: 18px;line-height: 2; }.card > p > i {font-size: 18px; }.card > a {font-weight: 400;font-size: 15px;margin: 0;margin-left: 25px;padding: 0;border: 0;height: auto;background: transparent;color: #097bbf;outline: none;cursor: pointer; }.card > ul {list- style-type: none; }.tags {font-size: 17px;font-weight: bolder;}.tags ~ a {display: none !important; }.tagsspan {font-size: 14px;font-weight: normal;color: #0e141e; }.tagsspanspan {color: #738f93; }@media screen and (1090px) {#profile {margin-left: 5%; }}@media screen and (850px) {#container {display: block; }#profile {width: 90%; }.card {margin: 05%;margin-bottom: 30px; }}

    PdfReport.cshtml :

    使用 RazorEngine.NetCore 需要修改下面兩處地方

    1. 刪除 @model PdfReportModel

    2. @Html.Raw(@ style) 修改為 @@Raw(@ style)

    檢視檔:
  • @using exportPdf.common@model PdfReportModel <!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title> @{ string style = TemplateGadgetProvider.Instance.Load(@"wwwroot\css\pdfReport.css"); }< style>@Html.Raw(@ style)</ style></head><body><divid="inner-nav"></div><divid="container"><divid="profile"><divid="image"><imgid="profile-photo"src="https://img2023.cnblogs.com/blog/233608/202303/233608-20230308165653594-2049775608.jpg"alt="Profile-Image"><ahref="#"><i class="fas fa-pen stroke-transparent"></i></a></div><pid="name">@Model.Name<br><spanid="email">@Model.Email</span></p><pid="designation">前端開發工程師<br><spanid="college">天將降大任於斯人也,必先苦其心誌,勞其筋骨,餓其體膚,空乏其身,行拂亂其所為也,所以動心忍性,增益其所不能。——【孟子】 </span></p><divid="social-links"><ahref="#"><i class="fab fa-facebook-f stroke-transparent"></i></a><a><i class="fab fa-twitter stroke-transparent"></i></a><a><i class="fab fa-linkedin-in stroke-transparent"></i></a><a><i class="fab fa-github stroke-transparent"></i></a></div><aid="edit-intro"href="#"><i class="fas fa-pen-alt blue"></i>&nbsp;&nbsp;</a><hrwidth="100%"><divid="about"><p style="display:inline;">個人詳情</p><ahref="#"><i class="fas fa-pen stroke-transparent-blue"></i></a></div><pid="year-graduation">預計畢業年份<br><strong>2023年6月</strong></p><pid="education">學歷<br><strong>湖南大學 本科</strong></p><pid="more-about">專業<br><strong> 電腦科學與技術專業</strong></p><pid="telephone">電話<br><strong>0532-2271351</strong></p><pid="fax">傳真<br><strong>+91-532-25453441</strong></p></div><divid="info-cards"><div class="card"><p><i class="fas fa-briefcase stroke-transparent"></i>&nbsp;&nbsp;&nbsp;專業技能</p><ul><li><p class="tags">1. 熟練掌握HTML、CSS、JavaScript等前端基礎技術</p></li><li><p class="tags">2. 熟悉jQuery、Bootstrap等常用前端框架和庫</p></li><li><p class="tags">3. 了解Node.js、Express等後端開發技術</p></li><li><p class="tags">4. 掌握Git、Webpack等常用開發工具</p></li><li><p class="tags">5. 具備良好的編碼風格和文件習慣</p></li></ul></div><div class="card"><p><i class="fas fa-briefcase stroke-transparent"></i>&nbsp;&nbsp;&nbsp;工作檢驗</p><ul><li><p class="tags">1. 依帆網站首頁制作(個人計畫)<br> - 使用HTML、CSS、JavaScript實作了一個響應式的網站首頁<br> - 使用Bootstrap進行布局和樣式美化,使用jQuery實作輪播圖和導航欄效果<br> - 使用Webpack進行打包和最佳化,使用Git進行版本控制和部署</p></li><li><p class="tags">2. 藝風網站後台管理系統(實習計畫)<br> - 參與了一個基於Node.js和Express的後台管理系統的開發<br> - 負責前端頁面的編寫,使用EJS樣版引擎渲染數據<br> - 使用Ajax和Fetch進行數據互動,使用Element UI元件庫提升使用者體驗<br> - 遵循MVC架構,使用Mongoose操作MongoDB資料庫</p></li></ul></div><div class="card"><p><i class="fas fa-graduation-cap stroke-transparent"></i>&nbsp;&nbsp;&nbsp;自我評價</p><ul><li><p class="tags">具備較強的學習能力和邏輯思維能力,喜歡接觸新技術和新知識</p></li><li><p class="tags">具備良好的溝通能力和團隊協作能力,能夠積極配合團隊完成任務</p></li><li><p class="tags">具備一定的創新能力和解決問題能力,能夠針對不同需求提出合理方案</p></li></ul><ahref="#">+ Add new</a></div></div></div></body></html>

    ViewRenderService :

    public classViewRenderService{privatereadonly IRazorViewEngine _razorViewEngine;privatereadonly ITempDataProvider _tempDataProvider;privatereadonly IServiceProvider _serviceProvider;publicViewRenderService(IRazorViewEngine razorViewEngine, ITempDataProvider tempDataProvider, IServiceProvider serviceProvider) { _razorViewEngine = razorViewEngine; _tempDataProvider = tempDataProvider; _serviceProvider = serviceProvider; }publicasync Task<string> RenderToStringAsync(string viewName, object model) {var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());using (var sw = new StringWriter()) {var viewResult = _razorViewEngine.FindView(actionContext, viewName, false);if (viewResult.View == null) {thrownew ArgumentNullException($"{viewName} does not match any available view"); }var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model };var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary,new TempDataDictionary(actionContext.HttpContext, _tempDataProvider), sw,new HtmlHelperOptions() );await viewResult.View.RenderAsync(viewContext);return sw.ToString(); } }}

    Program.cs :

    builder.Services.AddTransient<ViewRenderService>();

    以上就是使用 Select.HtmlToPdf.NetCore 將HTML匯出為PDF的全部內容!

    作者:百寶門-明維

    原文地址:https://blog.baibaomen.com/97-2/

    版權聲明:本文來源於網友收集或網友供稿,僅供學習交流之用,如果有侵權,請轉告小編或者留言,本公眾號立即刪除。