果你訂閱了Airbnb 的 JavaScript 風(fēng)格指南,就會知道最好的方法是使用 "String()"
我用他是因為它是最明確的——容易讓其他人明白你代碼的意圖
請記住,最好的代碼并不需要多聰明的方式,而是能將你的代碼理解傳達給他人
const value=12345; // Concat Empty String value + ''; // Template Strings `${value}`; // JSON.stringify JSON.stringify(value); // toString() value.toString(); // String() String(value); // RESULT // '12345'
對比這 5 個方法
讓我們用不同的值測試這 5 個方法,下面是我們打算測試的值:
const string="hello"; const number=123; const boolean=true; const array=[1, "2", 3]; const object={one: 1 }; const symbolValue=Symbol('123'); const undefinedValue=undefined; const nullValue=null;
拼接空字符串
string + ''; // 'hello' number + ''; // '123' boolean + ''; // 'true' array + ''; // '1,2,3' object + ''; // '[object Object]' undefinedValue + ''; // 'undefined' nullValue + ''; // 'null' symbolValue + ''; //TypeError
從這里可以看出如果值是 symbol 這個方法會拋出一個 TypeError 錯誤,除此之外,其他都輸出正確的值
模板字符串
`${string}`; // 'hello' `${number}`; // '123' `${boolean}`; // 'true' `${array}`; // '1,2,3' `${object}`; // '[object Object]' `${undefinedValue}`; // 'undefined' `${nullValue}`; // 'null' `${symbolValue}`; // ? TypeError
實際上使用模板字符串和拼接字符串是輸出相同的結(jié)果,再者,當處理 Symbol 這也不是最理想的方式因為它會拋出一個 TypeError
TypeError: Cannot convert a Symbol value to a string
類型錯誤: 不能把 Symbol 類型的值轉(zhuǎn)換為 string
JSON.stringify()
JSON.stringify(string); // '"hello"' JSON.stringify(number); // '123' JSON.stringify(boolean); // 'true' JSON.stringify(array); // '[1,"2",3]' JSON.stringify(object); // '{"one":1}' JSON.stringify(nullValue); // 'null' JSON.stringify(symbolValue); // undefined JSON.stringify(undefinedValue); // undefined 復(fù)制代碼
你一般也不會使用 JSON.stringify 去把一個值轉(zhuǎn)成字符串,而且這里真的沒有強制發(fā)生,我主要包括這種方式來完整讓你了解可用的所有工具,然后你根據(jù)具體情況來挑選使用哪種方式
有個點我要指出來因為你可能沒注意,當你使用一個純字符串格式的值轉(zhuǎn)換出來就會包裹引號
擴展閱讀 Kyle Simpson 的 “You Don’t Know JS”: JSON Stringification
關(guān)于了解基本原理的重要性
你可能注意到我的代碼筆記經(jīng)常引用 Kyle 的書,我在上面學(xué)到了很多東西,我不是來自計算機科學(xué)背景,缺乏很多基本概念,他的書讓我意識到明白基本原來是多么重要,對于那些想要成為高級工程師的人,真正了解基本原理是提升水平的好方法,否則很難提高。你最終知道了問題在那里,但是如果你知道了基本原理,就會知道為什么從而知道如何去解決,總之,強烈推薦這個系列給那些想成為高級程序員的人!
toString()
string.toString(); // 'hello' number.toString(); // '123' boolean.toString(); // 'true' array.toString(); // '1,2,3' object.toString(); // '[object Object]' symbolValue.toString(); // 'Symbol(123)' undefinedValue.toString(); // ? TypeError nullValue.toString(); // ? TypeError
因此對比就留給了 toString 和 String, toString 也執(zhí)行的不錯,一定要注意的一點就是在 undefined 和 null 下面會拋出異常。
String()
String(string); // 'hello' String(number); // '123' String(boolean); // 'true' String(array); // '1,2,3' String(object); // '[object Object]' String(symbolValue); // 'Symbol(123)' String(undefinedValue); // 'undefined' String(nullValue); // 'null'
最后,我們找到了冠軍
可以看到 String() 處理 undefined 和 null 非常的好 ,不會拋出任何異常。記住我經(jīng)常說的,你最了解你的程序,因此你應(yīng)該選擇最適合你的方式。
在展示了所有不同的方法如何處理不同類型的值之后,希望你能意識到這些差異并且知道下次處理代碼時如何使用,如果你不確認,String()是最好的選擇
.NET的SelectPdf Html到Pdf轉(zhuǎn)換器-社區(qū)版是.NET的SelectPdf庫中提供的功能強大的html到pdf轉(zhuǎn)換器的免費版本。
轉(zhuǎn)換器提供了許多強大的選項(將任何網(wǎng)頁轉(zhuǎn)換為pdf,將任何html字符串轉(zhuǎn)換為pdf,html5 / css3 / javascript支持,頁眉和頁腳支持等),唯一的限制是它最多可以生成pdf文檔。5頁長。
.NET的免費HTML至Pdf轉(zhuǎn)換器–社區(qū)版功能:最多生成5頁pdf文檔,將任何網(wǎng)頁轉(zhuǎn)換為pdf,將任何原始html字符串轉(zhuǎn)換為pdf,設(shè)置pdf頁面設(shè)置(頁面大小,頁面方向,頁面邊距) ,在轉(zhuǎn)換過程中調(diào)整內(nèi)容大小以適合pdf頁面,設(shè)置pdf文檔屬性,設(shè)置pdf查看器首選項,設(shè)置pdf安全性(密碼,權(quán)限),設(shè)置轉(zhuǎn)換延遲和網(wǎng)頁導(dǎo)航超時,自定義頁眉和頁腳,在頁眉中支持html和頁腳,自動和手動分頁符,在每個頁面上重復(fù)html表頭,支持@media類型屏幕和打印,支持內(nèi)部和外部鏈接,基于html元素自動生成書簽,支持HTTP標頭,支持HTTP cookie,支持需要身份驗證的網(wǎng)頁,支持代理服務(wù)器,啟用/禁用javascript,修改顏色空間,多線程支持,HTML5 / CSS3支持,Web字體支持等等。
1、nuget 引用
Install-Package Select.HtmlToPdf
2、方法
using SelectPdf;
using System.Collections.Specialized;
using System.IO;
using System.Web;
namespace BQoolCommon.Helpers.File
{
public class WebToPdf
{
public WebToPdf()
{
//SelectPdf.GlobalProperties.LicenseKey="your-license-key";
}
/// <summary>
/// 將 Html 轉(zhuǎn)成 PDF,並儲存成檔案
/// </summary>
/// <param name="html">html</param>
/// <param name="fileName">絕對路徑</param>
public void SaveToFileByHtml(string html, string fileName)
{
var doc=SetPdfDocument(html);
doc.Save(fileName);
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並儲存成檔案
/// </summary>
/// <param name="url">url</param>
/// <param name="fileName">絕對路徑</param>
/// <param name="httpCookies">Cookies</param>
public void SaveToFileByUrl(string url, string fileName, NameValueCollection httpCookies)
{
var doc=SetPdfDocument(url, httpCookies);
doc.Save(fileName);
}
/// <summary>
/// 將 Html 轉(zhuǎn)成 PDF,並輸出成 byte[] 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public byte[] GetFileByteByHtml(string html)
{
var doc=SetPdfDocument(html);
return doc.Save();
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並輸出成 byte[] 格式
/// </summary>
/// <param name="url">url</param>
/// <param name="httpCookies">Cookies</param>
/// <returns></returns>
public byte[] GetFileByteByUrl(string url, NameValueCollection httpCookies)
{
var doc=SetPdfDocument(url, httpCookies);
return doc.Save();
}
/// <summary>
/// 將 Html 轉(zhuǎn)成 PDF,並輸出成 Stream 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public Stream GetFileStreamByHtml(string html)
{
var doc=SetPdfDocument(html);
var pdfStream=new MemoryStream();
doc.Save(pdfStream);
pdfStream.Position=0;
return pdfStream;
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並輸出成 Stream 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public Stream GetFileStreamByUrl(string url, NameValueCollection httpCookies)
{
var doc=SetPdfDocument(url, httpCookies);
var pdfStream=new MemoryStream();
doc.Save(pdfStream);
pdfStream.Position=0;
return pdfStream;
}
private PdfDocument SetPdfDocument(string html)
{
var converter=new HtmlToPdf();
converter.Options.WebPageWidth=1200;
html=HttpUtility.HtmlDecode(html);
return converter.ConvertHtmlString(html);
}
private PdfDocument SetPdfDocument(string url, NameValueCollection httpCookies)
{
var converter=new HtmlToPdf();
converter.Options.WebPageWidth=1200;
if (httpCookies != && httpCookies.Count !=0)
{
converter.Options.HttpCookies.Add(httpCookies);
}
return converter.ConvertUrl(url);
}
}
}
3、調(diào)用
/// <summary>
/// 下載pdf
/// </summary>
public void Downpdf(string data)
{
var stream=new BQoolCommon.Helpers.File.WebToPdf().GetFileStreamByHtml(Gethtml(data));
Response.Clear();
//二進制流數(shù)據(jù)(如常見的文件下載)
Response.ContentType="application/octet-stream";
//通知瀏覽器下載文件而不是打開
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("Profit and Loss Statement.pdf", System.Text.Encoding.UTF8));
var bytes=StreamToBytes(stream);
Response.BinaryWrite(bytes);
Response.Flush();
stream.Close();
stream.Dispose();
Response.End();
}
那么如何獲取指定頁面的html 呢 傳入對應(yīng)的model 獲得指定動態(tài)的html
private string Gethtml(string data)
{
string str="";
str=this.ControllerContext.RenderViewToString("ProfitDetails", data);
return str;
}
using BQoolCommon.Helpers.Format;
using Newtonsoft.Json;
using OrdersManager.Models.ViewModel.Report;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace OrdersManager.Web.Infrastructure
{
public static class HelperExtensions
{
public static string RenderViewToString(this ControllerContext context, string viewName, string data)
{
if (string.IsOrEmpty(viewName))
viewName=context.RouteData.GetRequiredString("action");
context.Controller.ViewData.Model=JsonConvert.DeserializeObject<ProfitDetailsmodel>(StringTools.Base64Decode(StringTools.Base64Decode(data)));
using (var sw=new StringWriter())
{
ViewEngineResult viewResult=ViewEngines.Engines.FindPartialView(context, viewName);
var viewContext=new ViewContext(context,
viewResult.View,
context.Controller.ViewData,
context.Controller.TempData,
sw);
try
{
viewResult.View.Render(viewContext, sw);
}
catch (Exception ex)
{
throw;
}
return sw.GetStringBuilder().ToString();
}
}
}
}
https://www.nuget.org/packages/Select.HtmlToPdf/
、nuget 引用
Select.HtmlToPdf
2、方法
using SelectPdf;
using System.Collections.Specialized;
using System.IO;
using System.Web;
namespace BQoolCommon.Helpers.File
{
public class WebToPdf
{
public WebToPdf()
{
//SelectPdf.GlobalProperties.LicenseKey="your-license-key";
}
/// <summary>
/// 將 Html 轉(zhuǎn)成 PDF,並儲存成檔案
/// </summary>
/// <param name="html">html</param>
/// <param name="fileName">絕對路徑</param>
public void SaveToFileByHtml(string html, string fileName)
{
var doc=SetPdfDocument(html);
doc.Save(fileName);
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並儲存成檔案
/// </summary>
/// <param name="url">url</param>
/// <param name="fileName">絕對路徑</param>
/// <param name="httpCookies">Cookies</param>
public void SaveToFileByUrl(string url, string fileName, NameValueCollection httpCookies)
{
var doc=SetPdfDocument(url, httpCookies);
doc.Save(fileName);
}
/// <summary>
/// 將 Html 轉(zhuǎn)成 PDF,並輸出成 byte[] 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public byte[] GetFileByteByHtml(string html)
{
var doc=SetPdfDocument(html);
return doc.Save();
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並輸出成 byte[] 格式
/// </summary>
/// <param name="url">url</param>
/// <param name="httpCookies">Cookies</param>
/// <returns></returns>
public byte[] GetFileByteByUrl(string url, NameValueCollection httpCookies)
{
var doc=SetPdfDocument(url, httpCookies);
return doc.Save();
}
/// <summary>
/// 將 Html 轉(zhuǎn)成 PDF,並輸出成 Stream 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public Stream GetFileStreamByHtml(string html)
{
var doc=SetPdfDocument(html);
var pdfStream=new MemoryStream();
doc.Save(pdfStream);
pdfStream.Position=0;
return pdfStream;
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並輸出成 Stream 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public Stream GetFileStreamByUrl(string url, NameValueCollection httpCookies)
{
var doc=SetPdfDocument(url, httpCookies);
var pdfStream=new MemoryStream();
doc.Save(pdfStream);
pdfStream.Position=0;
return pdfStream;
}
private PdfDocument SetPdfDocument(string html)
{
var converter=new HtmlToPdf();
converter.Options.WebPageWidth=1200;
html=HttpUtility.HtmlDecode(html);
return converter.ConvertHtmlString(html);
}
private PdfDocument SetPdfDocument(string url, NameValueCollection httpCookies)
{
var converter=new HtmlToPdf();
converter.Options.WebPageWidth=1200;
if (httpCookies != && httpCookies.Count !=0)
{
converter.Options.HttpCookies.Add(httpCookies);
}
return converter.ConvertUrl(url);
}
}
}
*請認真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。