Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
里講一種實(shí)現(xiàn)起來比較簡(jiǎn)單的html轉(zhuǎn)pdf下載的實(shí)現(xiàn)。
html2canvas jspdf
通過html2canvas,我們可以將指定的一個(gè)dom元素,渲染到canvas中,然后從canva中獲得該圖片,并將圖片通過jspdf來生成。
function createPdf (selector,pagesize,direction,title){
var key = pagesize +''+direction;
var settings = {
'00' : {
pdf : {orientation : 'portrait',format : 'a4',unit : 'px'},
width : 448,
height : 632.5
},
'01' : {
pdf : {orientation : 'landscape',format : 'a4',unit : 'px'},
width : 632.5,
height : 448
},
'10' : {
pdf : {orientation : 'portrait',format : 'a3',unit : 'px'},
width : 632.5,
height : 894.2
},
'11' : {
pdf : {orientation : 'landscape',format : 'a3',unit : 'px'},
width : 894.2,
height : 632.5
}
};
var set = settings[key];
var doc = new jsPDF(set.pdf);
var arr = [];//根據(jù)順序保存
var $arr = $(selector);
function tempCreate(){
if($arr.length == 0){//沒有啦
//執(zhí)行生成
tempPdf();
}else{
var $dom = $arr.splice(0,1);
html2canvas($dom[0]).then(canvas => {
var dataurl = canvas.toDataURL('image/png');
arr.push(dataurl);
tempCreate();
});
}
}
function tempPdf(){
arr.forEach((item,i)=>{
if(i !== 0){
doc.addPage();
}
doc.addImage(item,'png',-1,-1,set.width,set.height);//根據(jù)不同的寬高寫入
})
//根據(jù)當(dāng)前的作業(yè)名稱
doc.save(title+'.pdf');
}
tempCreate();
}
需要指定容器(依賴jquery),然后指定紙張A4或 A3,以及橫縱向。
//調(diào)用
createPdf('.single-page',0,0,'test')
當(dāng)然,如果是數(shù)據(jù)量很大的話,就不建議在前臺(tái)生成了,最好還是放在后端去做。個(gè)人測(cè)試過,做A4的圖片生成PDF,當(dāng)數(shù)量大約在100左右的時(shí)候,瀏覽器就崩潰了,如果只是幾頁的數(shù)據(jù)的話,這個(gè)方式還是很方便的。
Ps:瀏覽器要是現(xiàn)代瀏覽器哈。
html2canvas : http://html2canvas.hertzen.com/ jspdf :https://github.com/MrRio/jsPDF
.NET的SelectPdf Html到Pdf轉(zhuǎn)換器-社區(qū)版是.NET的SelectPdf庫中提供的功能強(qiáng)大的html到pdf轉(zhuǎn)換器的免費(fèi)版本。
轉(zhuǎn)換器提供了許多強(qiáng)大的選項(xiàng)(將任何網(wǎng)頁轉(zhuǎn)換為pdf,將任何html字符串轉(zhuǎn)換為pdf,html5 / css3 / javascript支持,頁眉和頁腳支持等),唯一的限制是它最多可以生成pdf文檔。5頁長(zhǎng)。
.NET的免費(fèi)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查看器首選項(xiàng),設(shè)置pdf安全性(密碼,權(quán)限),設(shè)置轉(zhuǎn)換延遲和網(wǎng)頁導(dǎo)航超時(shí),自定義頁眉和頁腳,在頁眉中支持html和頁腳,自動(dòng)和手動(dòng)分頁符,在每個(gè)頁面上重復(fù)html表頭,支持@media類型屏幕和打印,支持內(nèi)部和外部鏈接,基于html元素自動(dòng)生成書簽,支持HTTP標(biāo)頭,支持HTTP cookie,支持需要身份驗(yàn)證的網(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,並儲(chǔ)存成檔案
/// </summary>
/// <param name="html">html</param>
/// <param name="fileName">絕對(duì)路徑</param>
public void SaveToFileByHtml(string html, string fileName)
{
var doc = SetPdfDocument(html);
doc.Save(fileName);
}
/// <summary>
/// 傳入 Url 轉(zhuǎn)成 PDF,並儲(chǔ)存成檔案
/// </summary>
/// <param name="url">url</param>
/// <param name="fileName">絕對(duì)路徑</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();
//二進(jìn)制流數(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 呢 傳入對(duì)應(yīng)的model 獲得指定動(dòng)態(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/
近碰到個(gè)需求,需要把當(dāng)前頁面生成 pdf,并下載。弄了幾天,自己整理整理,記錄下來,我覺得應(yīng)該會(huì)有人需要 :)
項(xiàng)目源碼地址:https://github.com/linwalker/render-html-to-pdf
html2canvas
簡(jiǎn)介
我們可以直接在瀏覽器端使用html2canvas,對(duì)整個(gè)或局部頁面進(jìn)行“截圖”。但這并不是真的截圖,而是通過遍歷頁面DOM結(jié)構(gòu),收集所有元素信息及相應(yīng)樣式,渲染出canvas image。
由于html2canvas只能將它能處理的生成canvas image,因此渲染出來的結(jié)果并不是100%與原來一致。但它不需要服務(wù)器參與,整個(gè)圖片都由客戶端瀏覽器生成,使用很方便。
使用
使用的API也很簡(jiǎn)潔,下面代碼可以將某個(gè)元素渲染成canvas:
通過onrendered方法,可以將生成的canvas進(jìn)行回調(diào),比如插入到頁面中:
做個(gè)小例子(demo1)代碼如下:
這個(gè)例子將頁面body中的元素渲染成canvas,并插入到body中。
nvas,并插入到body中。
jsPDF
jsPDF庫可以用于瀏覽器端生成PDF。
文字生成PDF
使用方法如下:
圖片生成PDF
使用方法如下:
文字與圖片生成PDF
生成pdf需要把轉(zhuǎn)化的元素添加到j(luò)sPDF實(shí)例中,也有添加html的功能,但某些元素?zé)o法生成在pdf中,因此可以使用html2canvas + jsPDF的方式將頁面轉(zhuǎn)成pdf。通過html2canvas將遍歷頁面元素,并渲染生成canvas,然后將canvas圖片格式添加到j(luò)sPDF實(shí)例,生成pdf。
html2canvas + jsPDF
單頁
將demo1的例子修改下:
如果頁面內(nèi)容根據(jù)a4比例轉(zhuǎn)化后高度超過a4紙高度呢,生成的pdf會(huì)怎么樣?會(huì)分頁嗎?
你可以試試,驗(yàn)證一下自己的想法。
jsPDF提供了一個(gè)很有用的API, addPage(),我們可以通過 pdf.addPage(),來添加一頁pdf,然后通過 pdf.addImage(...),將圖片賦予這頁pdf來顯示。
那么我們?nèi)绾未_定哪里分頁?
這個(gè)問題好回答,我們可以設(shè)置一個(gè) pageHeight,超過這個(gè)高度的內(nèi)容放入下一頁pdf。
來捋一下思路,將html頁面內(nèi)容生成canvas圖片,通過 addImage將第一頁圖片添加到pdf中,超過一頁內(nèi)容,通過 addPage()添加pdf頁數(shù),然后再通過 addImage將下一頁圖片添加到pdf中。
嗯~,很好!巴特,難道沒有發(fā)現(xiàn)問題嗎?
這個(gè)方法實(shí)現(xiàn)的前提是 — — 我們能根據(jù) pageHeight先將整頁內(nèi)容生成的canvas圖片分割成對(duì)應(yīng)的小圖片,然后一個(gè)蘿卜一個(gè)坑,一頁一頁 addImage進(jìn)去。
What? 想一想我們的canvas是腫么來的,不用拉上去,直接看下面:
這里的 body就是要生成canvas的元素對(duì)象,一個(gè)元素生成一個(gè)canvas;那么我們需要一頁一頁的canvas,也就是說。。。
你覺得可能嗎? 我覺得不太現(xiàn)實(shí),按這思路要獲取頁面上不同位置的DOM元素,然后通過 htnl2canvas(element,option)來處理,先不說能不能剛好在每個(gè) pageHeight的位置剛好找到一個(gè)DOM元素,就算找到了,這樣做累不累。
累的話 :可以看看下面這種方法。
多頁
我提供的思路是我們只生成一個(gè)canvas,對(duì)就一個(gè),轉(zhuǎn)化元素就是你要轉(zhuǎn)成pdf內(nèi)容的母元素,在這篇demo里就是 body了;其他不變,也是超過一頁內(nèi)容就 addPage,然后addImage,只不過這里添加的是同一個(gè)canvas。
當(dāng)然這樣做只會(huì)出現(xiàn)多頁重復(fù)的pdf,那到底怎么實(shí)現(xiàn)正確分頁顯示。其實(shí)主要利用了jsPDF的兩點(diǎn):
雖然每一頁pdf上顯示的圖片是相同的,但我們通過調(diào)整圖片的位置,產(chǎn)生了分頁的錯(cuò)覺。以第二頁為例,將豎直方向上的偏移設(shè)置為 -841.89即一張a4紙的高度,又因?yàn)槌^a4紙高度范圍的圖片不顯示,所以第二頁顯示了圖片豎直方向上[841.89,1682.78]范圍內(nèi)的內(nèi)容,這就得到了分頁的效果,以此類推。
還是看代碼吧:
兩邊留邊距
修改imgWidth,并且在addImage時(shí)x方向參數(shù)設(shè)置你要的邊距,具體代碼如下:
想要學(xué)習(xí)JS、HTML、CSS的可以私信帳號(hào)“學(xué)習(xí)交流”加群一起討論,領(lǐng)取學(xué)習(xí)視頻資料。
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。