兩天有個客戶需要把網頁轉為pdf,之前也沒開發過類似的工具,就在百度搜索了一波,主要有下面三種
在百度(我一般用必應)搜索“在線網頁轉pdf”就有很多可以做這個事的網站,免費的如
各種pdf的操作都有,免費使用,速度一般。
官網地址https://tools.pdf24.org/zh
PDF24 Tools
開源免費項目,使用golang寫的,提供在線轉
官網地址http://doctron.lampnick.com/
doctron在線體驗demo
還有挺多其他的,可以自己搜索,但是都不符合我的預期。
Doctron,這是我今天要介紹的重頭戲。
Doctron是基于Docker、無狀態、簡單、快速、高質量的文檔轉換服務。目前支持將html轉為pdf、圖片(使用chrome(Chromium)瀏覽器內核,保證轉換質量)。支持PDF添加水印。
管他的,先把代碼下載下來再說
git clone https://gitcode.net/mirrors/lampnick/doctron.git
倉庫
運行
go build
./doctron --config conf/default.yaml
運行截圖
轉pdf,訪問http://127.0.0.1:8080/convert/html2pdf?u=doctron&p=lampnick&url=<url>,更換鏈接中的url為你需要轉換的url即可。
轉換效果
然后就可以寫程序去批量轉換需要的網頁了,但是我需要轉換的網頁有兩個需求
1、網站需要會員登錄,不然只能看得到一部分
2、需要把網站的頭和尾去掉的
這就為難我了,不會go語言啊,硬著頭皮搞了,肯定有個地方打開這個url的,就去代碼慢慢找,慢慢調試,功夫不負有心人,終于找到調用的地方了。
第一步:添加網站用戶登錄cookie
添加cookie之前
添加cookie之后
第二步:去掉網站頭尾
chromedp.Evaluate(`$('.header').css("display" , "none");
$('.btn-group').css("display" , "none");
$('.container .container:first').css("display" , "none");
$('.breadcrumb').css("display" , "none");
$('.footer').css("display" , "none")`, &ins.buf),
打開網頁后執行js代碼把頭尾隱藏掉
第三步:程序化,批量自動生成pdf
public static void createPDF(String folder , String cl , String pdfFile, String urlhref) {
try {
String fileName = pdfFile.replace("/", ":");
String filePath = folder + fileName;
File srcFile = new File(filePath);
File newFolder = new File("/Volumes/disk2/myproject" + File.separator + cl);
File destFile = new File(newFolder, fileName);
if(destFile.exists()){
return;
}
if(srcFile.exists()){
//移動到對應目錄
if(!newFolder.exists()){
newFolder.mkdirs();
}
FileUtils.moveFile(srcFile , destFile);
return;
}
if(!newFolder.exists()){
newFolder.mkdirs();
}
String url = "http://127.0.0.1:8888/convert/html2pdf?u=doctron&p=lampnick&url="+urlhref;
HttpEntity<String> entity = new HttpEntity<String>(null, null);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> bytes = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
if (bytes.getBody().length <= 100) {
if(urlList.containsKey(urlhref)){
Integer failCount = urlList.get(urlhref);
if(failCount > 3){
System.out.println("下載失敗:" + cl + " / " + pdfFile +" " + urlhref);
return;
}
failCount++;
urlList.put(urlhref , failCount);
}else{
urlList.put(urlhref , 1);
}
createPDF(folder , cl , pdfFile , urlhref);
}else{
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try (FileOutputStream out = new FileOutputStream(destFile);) {
out.write(bytes.getBody(), 0, bytes.getBody().length);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
最終成果:
文件夾分類存放
pdf文件
、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 轉成 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 轉成 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 轉成 PDF,並輸出成 byte[] 格式
/// </summary>
/// <param name="html">html</param>
/// <returns></returns>
public byte[] GetFileByteByHtml(string html)
{
var doc = SetPdfDocument(html);
return doc.Save();
}
/// <summary>
/// 傳入 Url 轉成 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 轉成 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 轉成 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);
}
}
}
PDF是一個強大的生成PDF的PHP類庫,基于FPDF和Html2FPDF,基本兼容css3和HTML標簽。
pdf模塊是基于mPDF封裝的YiAdmin模塊。
獲取MPDF實例
$pdf = ev('Pdf');
保存為PDF文件
// 保存到public目錄 前臺可訪問
$filepath = ev('PdfSave', '<h1>Hello YiAdmin</h1>', ‘path/file.pdf’, true);
// 保存到runtime目錄 前臺不可訪問
$filepath = ev('PdfSave', '<h1>Hello YiAdmin</h1>', ‘path/file.pdf’, false);
瀏覽器輸出
*請認真填寫需求信息,我們會在24小時內與您取得聯系。