網頁轉PDF的方法和工具推薦(網頁如何轉PDF格式的文件)
前兩天有個客戶需要把網頁轉為pdf,之前也沒開發(fā)過類似的工具,就在百度搜索了一波,主要有下面三種
- 在線轉pdf使用瀏覽器打印功能轉pdf使用本地軟件工具轉pdf
在線轉pdf
在百度(我一般用必應)搜索“在線網頁轉pdf”就有很多可以做這個事的網站,免費的如
PDF24Tools
各種pdf的操作都有,免費使用,速度一般。
官網地址https://tools.pdf24.org/zh

PDF24 Tools
doctron
開源免費項目,使用golang寫的,提供在線轉
官網地址http://doctron.lampnick.com/

doctron在線體驗demo
還有挺多其他的,可以自己搜索,但是都不符合我的預期。
使用瀏覽器打印功能轉pdf
- 在瀏覽器右鍵,點擊打印或者ctrl+p在彈出的打印對話框中找到目標打印機選擇“另存為PDF”點擊“保存”按鈕即可下載pdf了
使用本地軟件工具轉pdf
Doctron,這是我今天要介紹的重頭戲。
Doctron是基于Docker、無狀態(tài)、簡單、快速、高質量的文檔轉換服務。目前支持將html轉為pdf、圖片(使用chrome(Chromium)瀏覽器內核,保證轉換質量)。支持PDF添加水印。
使用chrome內核保證高質量將HTML轉為pdf/圖片。簡易部署(提供docker鏡像,Dockerfile以及k8s yaml配置文件)。支持豐富的轉換參數。轉為pdf和圖片支持自定義大小。無狀態(tài)服務支持。
管他的,先把代碼下載下來再說
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=

轉換效果
然后就可以寫程序去批量轉換需要的網頁了,但是我需要轉換的網頁有兩個需求
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),打開網頁后執(zhí)行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 entity = new HttpEntity(null, null);RestTemplate restTemplate = new RestTemplate();ResponseEntity 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文件
本站部分文章來自網絡或用戶投稿。涉及到的言論觀點不代表本站立場。閱讀前請查看【免責聲明】發(fā)布者:愛自由,如若本篇文章侵犯了原著者的合法權益,可聯系我們進行處理。本文鏈接:http://www.masion.cn/dnxx/dnjq/132167.html
