整合營銷服務(wù)商

          電腦端+手機(jī)端+微信端=數(shù)據(jù)同步管理

          免費(fèi)咨詢熱線:

          使用Select.HtmlToPdf 把html內(nèi)容生成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 轉(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); }
            }}

          何保持頁面樣式基本不變的前提下將HTML頁面導(dǎo)出為PDF,下面提供一些示例代碼,純屬個人原創(chuàng),如對你有幫助請記得加關(guān)注、加收藏、點(diǎn)贊、轉(zhuǎn)發(fā)、分享~謝謝~~

          • 基本思路:保持頁面樣式基本不變,使用 `html2canvas` 將頁面轉(zhuǎn)換為圖片,然后再通過 `jspdf` 將圖片分頁導(dǎo)出為PDF文件(中間會遇到圖片或文字等內(nèi)容在分頁處被切割開的問題,如何解決了?詳見末尾干貨)
          • 上基礎(chǔ)代碼:下面為項目中實(shí)際代碼截取
          <div>
              <!-- 要打印的內(nèi)容區(qū) -->
              <div ref="contentRef">
                  <div class="print-item print-out-flow">這是脫離文檔流的內(nèi)容區(qū)域</div>
                  <div class="print-item">這是一行內(nèi)容,也是最小葉子元素內(nèi)容</div>
              </div>
              <!-- 打印內(nèi)容容器 -->
              <div ref="printContainerRef" class="print-container"></div>
          </div>
          /**
            * 1.使用一個隱藏div裝載有滾動條的div.innerHTML
            * 2.隱藏div使用position: absolute, z-index: -999, left: -9999px, width: 900px 控制讓用戶無感知
            * 3.根據(jù)需要覆寫隱藏div內(nèi)html樣式(例如textarea多行顯示有問題, 可以新增一個隱藏的div
            *    包裹textarea的綁定值, 然后在打印樣式中覆寫樣式, 隱藏textarea并顯示對應(yīng)div)
            */
          handleExport() {
             // 下面是VUE組件內(nèi)獲取DOM元素代碼,將內(nèi)容放置到打印區(qū)(定義的隱藏DIV)中
              const contentRef = this.$refs.contentRef as HTMLElement;
              const printContainerRef = this.$refs.printContainerRef as HTMLElement;
              // 打印區(qū)的需額外處理絕對定位值, 調(diào)整使得第一個元素的.top值為0, 以便于頁面計算
              printContainerRef.innerHTML = contentRef.innerHTML;	
              
              // 所有葉子div元素加上 print-item 樣式名, 脫離文檔流的額外添加 print-out-flow
              handlePrintItem(printContainerRef);  // 解決多頁內(nèi)容可能被切割問題
              
              html2canvas(printContainerRef, {allowTaint: false, useCORS: true}).then((canvas: any) => {
                const contentHeight = canvas.height;
                const contentWidth = canvas.width;
                // pdf每頁顯示的內(nèi)容高度
                const pageHeight = contentWidth / 595.28 * 841.89;
                // 未生成pdf的頁面高度
                let offsetHeight = contentHeight;
                // 頁面偏移值
                let position = 0;
                // a4紙的尺寸[595.28, 841.89], canvas圖片按a4紙大小縮放后的寬高
                const imgWidth = 595.28;
                const imgHeight = 595.28 / contentWidth * contentHeight;
          
                const dataURL = canvas.toDataURL('image/jpeg', 1.0);
                const doc = new jsPDF('p', 'pt', 'a4');
          
                if (offsetHeight < pageHeight) {
                  doc.addImage(dataURL, 'JPEG', 0, 0, imgWidth, imgHeight);
                } else {
                  while (offsetHeight > 0) {
                    doc.addImage(dataURL, 'JPEG', 0, position, imgWidth, imgHeight);
                    offsetHeight -= pageHeight;
                    position -= 841.89;
          
                    if (offsetHeight > 0) {
                      doc.addPage();
                    }
                  }
                }
          
                doc.save(this.generateReportFileName());
                printContainerRef.innerHTML = '';
              });
          }

          上干貨代碼:上面分頁導(dǎo)出PDF可能網(wǎng)上能看到類型代碼,但絕對找不到下面的代碼,純手搓解決分頁元素被切開問題(思路:獲取自身定位,如自己剛好在被分頁處,則加上一定的margin-top值將內(nèi)容向下移)

          /** 
           * 處理打印元素項, 修復(fù)分頁后被切割的元素
           * @param printContainerRef 打印內(nèi)容div容器
           * @param itemClassName 打印最小元素標(biāo)識類名
           * @param outFlowClassName 脫離文檔流的元素標(biāo)識類名
           */
          export function handlePrintItem(
            printContainerRef: HTMLElement,
            itemClassName: string = 'print-item',
            outFlowClassName: string = 'print-out-flow'
          ): void {
            const rootClientRect = printContainerRef.getBoundingClientRect();
            // 初始化頁面相關(guān)數(shù)據(jù)
            const totalHeight = rootClientRect.height;  // 內(nèi)容總高度
            const a4PageHeight = (printContainerRef.clientWidth / 595.28) * 841.89; // a4紙高度
            let pageNum = Math.ceil(totalHeight / a4PageHeight);  // 總頁數(shù)
            let addPageHeight = 0;  // 修正被分割元素而增加的頁面高度總和
            let currentPage = 1;  // 當(dāng)前正在處理切割的頁面
            const splitItemObj: { [key: number]: HTMLElement[] } = {};  // 內(nèi)容中各頁被切割元素存儲對象
          
            const printItemNodes: NodeListOf<HTMLElement> = printContainerRef.querySelectorAll(`.${itemClassName}`);
            for (let item of printItemNodes) {
              // 如果當(dāng)前頁已經(jīng)是最后一頁, 則中斷判斷
              if (currentPage >= pageNum) {
                break;
              }
          
              // 獲取元素絕對定位數(shù)據(jù)
              const clientRect = item.getBoundingClientRect();
              let top = clientRect.top;
              const selfHeight = clientRect.height;
              // 如果當(dāng)前元素距離頂部高度大于當(dāng)前頁面頁腳高度, 則開始判斷下一頁頁腳被切割元素
              if (top > currentPage * a4PageHeight) {
                // 換頁前修正上一頁被切割元素
                addPageHeight += fixSplitItems(currentPage, a4PageHeight, splitItemObj[currentPage], outFlowClassName);
                pageNum = Math.ceil((totalHeight + addPageHeight) / a4PageHeight);
                top = item.getBoundingClientRect().top;
                currentPage++;
              }
              // 如果元素剛好處于兩頁之間, 則記錄該元素
              if (top > (currentPage - 1) * a4PageHeight && top < currentPage * a4PageHeight && top + selfHeight > currentPage * a4PageHeight) {
                if (!splitItemObj[currentPage]) {
                  splitItemObj[currentPage] = [];
                }
                splitItemObj[currentPage].unshift(item);
                // 如果當(dāng)前元素是最后一個元素, 則直接處理切割元素, 否則交由處理下一頁元素時再處理切割
                if (item === printItemNodes[printItemNodes.length - 1]) {
                  fixSplitItems(currentPage, a4PageHeight, splitItemObj[currentPage], outFlowClassName);
                }
              }
            }
          }
          
          /**
            * 修復(fù)當(dāng)前頁所有被切割元素
            * @param currentPage 當(dāng)前頁
            * @param pageHeight 每頁高度
            * @param splitElementItems 當(dāng)前被切割元素數(shù)組
            * @param outFlowClassName 脫離文檔流的樣式類名
            */
          function fixSplitItems(
            currentPage: number,
            pageHeight: number,
            splitElementItems: HTMLElement[],
            outFlowClassName: string
          ): number {
            if (!splitElementItems || !splitElementItems.length) {
              return 0;
            }
          
            const yMargin = 5;  // y方向距離頁眉的距離
            const splitItemsMinTop = getSplitItemsMinTop(splitElementItems);
            if (!splitItemsMinTop) {
              return 0;
            }
          
            let fixHeight = currentPage * pageHeight - splitItemsMinTop + yMargin;
            const outFlowElement = splitElementItems.find((item) => item.classList.contains(outFlowClassName));
            if (outFlowElement && outFlowElement.parentElement) {
              const parentPreviousElement = outFlowElement.parentElement.previousElementSibling as HTMLElement;
              fixHeight += getMarinTopNum(parentPreviousElement, outFlowElement.parentElement);
              outFlowElement.parentElement.style.marginTop = `${fixHeight}px`;
              return fixHeight;
            }
          
            splitElementItems.forEach((splitElement) => {
              splitElement.style.marginTop = `${fixHeight}px`;
            });
            return fixHeight;
          }
          
          /**
            * 獲取被切割元素數(shù)組中最小高度值(如一行有多個元素被切割,則選出距離頂部最小的高度值)
            * @param splitElementItems 當(dāng)前被切割元素數(shù)組
            */
          function getSplitItemsMinTop(
            splitElementItems: HTMLElement[]
          ): number | undefined {
            // 獲取元素中最小top值作為基準(zhǔn)進(jìn)行修正
            let minTop: number | undefined;
            let minElement: HTMLElement | undefined;
            splitElementItems.forEach((splitElement) => {
              let top = splitElement.getBoundingClientRect().top;
              if (minTop) {
                minTop = top < minTop ? top : minTop;
                minElement = top < minTop ? splitElement : minElement;
              } else {
                minTop = top;
                minElement = splitElement;
              }
            });
          
            // 修正當(dāng)前節(jié)點(diǎn)及其前面同層級節(jié)點(diǎn)的margin值
            if (minTop && minElement) {
              const previousElement = splitElementItems[splitElementItems.length - 1].previousElementSibling as HTMLElement;
              minTop -= getMarinTopNum(previousElement, minElement);
            }
            return minTop;
          }
          
          /**
            * 通過前一個兄弟元素和元素自身的位置確認(rèn)一個距離頂部高度修正值
            * @param previousElement 前一個兄弟元素
            * @param curElement 當(dāng)前元素
            */
          function getMarinTopNum(previousElement: HTMLElement, curElement: HTMLElement): number {
            let preMarginNum = 0;
            let curMarginNum = 0;
            if (previousElement) {
              // 獲取外聯(lián)樣式需要getComputedStyle(), 直接.style時對象的值都為空
              const previousMarginBottom = window.getComputedStyle(previousElement).marginBottom;
              preMarginNum = previousMarginBottom ? Number(previousMarginBottom.replace('px', '')) : 0;
            }
            const marginTop = window.getComputedStyle(curElement).marginTop;
            curMarginNum = marginTop ? Number(marginTop.replace('px', '')) : 0;
            return preMarginNum > curMarginNum ? preMarginNum : curMarginNum;
          }

          以上純原創(chuàng)!歡迎加關(guān)注、加收藏、點(diǎn)贊、轉(zhuǎn)發(fā)、分享(代碼閑聊站)~

          融界2024年1月16日消息,據(jù)國家知識產(chǎn)權(quán)局公告,中信銀行股份有限公司申請一項名為“一種基于iText的支持生僻字轉(zhuǎn)換方法及系統(tǒng)”的專利,公開號CN117408230A,申請日期為2023年10月。

          專利摘要顯示,本發(fā)明提供了一種基于iText的支持生僻字轉(zhuǎn)換方法及系統(tǒng),涉及人工智能技術(shù)領(lǐng)域。其中,所述方法包括:獲得生僻字字庫;獲得常規(guī)字字庫;將所述生僻字字庫與所述常規(guī)字字庫進(jìn)行組合,獲得字庫集合;根據(jù)所述字庫集合對HTML進(jìn)行字體樣式設(shè)定,獲得HTML信息;將所述字庫集合設(shè)置到iText中,調(diào)用所述iText對所述HTML信息進(jìn)行PDF轉(zhuǎn)換,獲得轉(zhuǎn)換文件。解決了現(xiàn)有技術(shù)中存在遇到生成含有生僻字的HTML轉(zhuǎn)換PDF場景時,無法正常完成生僻字轉(zhuǎn)換,出現(xiàn)生僻字變?yōu)閬y碼,且使用升級現(xiàn)有中文字字庫的方法不能隨時新增生僻字,靈活性差的技術(shù)問題。

          本文源自金融界


          主站蜘蛛池模板: 老鸭窝毛片一区二区三区| 日本福利一区二区| 国产激情一区二区三区小说| 台湾无码AV一区二区三区| 波多野结衣av高清一区二区三区| 秋霞日韩一区二区三区在线观看 | 国产免费私拍一区二区三区| 亚洲AV无码一区二区三区久久精品| 99精品一区二区三区无码吞精| 人妻互换精品一区二区| 国产精品免费大片一区二区| 无码日韩精品一区二区三区免费 | 精品在线一区二区| 日本午夜精品一区二区三区电影 | 色婷婷一区二区三区四区成人网 | 国产伦精品一区二区三区免费迷| 一区二区三区视频在线播放| 亚洲欧洲精品一区二区三区| 日韩视频一区二区在线观看| 国产在线无码视频一区二区三区 | 亚洲一区在线免费观看| 国模吧无码一区二区三区| 国产成人精品一区二区A片带套| 国产自产在线视频一区| 一区二区三区国模大胆| 韩国精品一区二区三区无码视频| 久久伊人精品一区二区三区| 国产av成人一区二区三区| 成人影片一区免费观看| 亚洲国产一区二区视频网站| 高清一区二区三区视频| 无码日本电影一区二区网站| bt7086福利一区国产| 无码国产精品一区二区免费式影视| 国产在线视频一区| 中文字幕精品一区| 亚洲av午夜福利精品一区| 一区二区三区精品| 学生妹亚洲一区二区| 精品无码中出一区二区| 免费人人潮人人爽一区二区|