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 中文字幕一区在线观看,野花日本免费视频中文,手机亚洲第一页

          整合營銷服務(wù)商

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

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

          HTML轉(zhuǎn)換成PDF,這樣就搞定了

          HTML轉(zhuǎn)換成PDF,這樣就搞定了

          嘍,今天是一篇HTML to PDF速食指南。

          Java 轉(zhuǎn)換 HTML 到PDF有許多類庫,今天我們介紹一下第三方免費(fèi)的類庫OpenPDF。

          1. OpenPDF

          OpenPDF是免費(fèi)的Java類庫 ,遵從LGPL 和 MPL協(xié)議,所以基本上能夠可以隨意使用。OpenPDF是基于iTEXT的,目前來說也是維護(hù)的比較好的Java操作PDF的開源軟件。

          話不多說,且看所需要的依賴,

          <dependency>    
              <groupId>org.jsoup</groupId>    
              <artifactId>jsoup</artifactId>   
              <version>1.13.1</version> 
          </dependency>
          <dependency>
              <groupId>com.openhtmltopdf</groupId>
              <artifactId>openhtmltopdf-core</artifactId>
              <version>1.0.6</version>
          </dependency>
          <dependency>
              <groupId>com.openhtmltopdf</groupId>
              <artifactId>openhtmltopdf-pdfbox</artifactId>
              <version>1.0.6</version>
          </dependency>
          

          jsoup可以將html文件轉(zhuǎn)換成輸入流等,也可以遍歷html的DOM節(jié)點(diǎn),提取元素及樣式等。

          2. 示例

          本篇示例將以下html文件轉(zhuǎn)換成pdf

          <html>
          <head>
              <style>
                  .center_div {
                      border: 1px solid #404e94;
                      margin-left: auto;
                      margin-right: auto;
                      background-color: #f6d0ed;
                      text-align: left;
                      padding: 8px;
                  }
                  table {
                      width: 100%;
                      border: 1px solid black;
                  }
                  th, td {
                      border: 1px solid black;
                  }
                  body,html,input{font-family:"msyh";}
              </style>
          </head>
          <body>
          <div class="center_div">
              <h1>Hello java North!</h1>
              <div>
                  <p>convert html to pdf.</p>
              </div>
              <div>
                  <table>
                      <thead>
                          <th>ROLE</th>
                          <th>NAME</th>
                          <th>TITLE</th>
                      </thead>
                      <tbody>
                          <tr>
                              <td>MARKSMAN</td>
                              <td>ASHE</td>
                              <td>THE FROST ARCHER</td>
                          </tr>
                          <tr>
                              <td>MAGES</td>
                              <td>ANNIE</td>
                              <td>THE DARK CHILD</td>
                          </tr>
                          <tr>
                              <td>射手</td>
                              <td>凱塔琳</td>
                              <td>皮城女警</td>
                          </tr>
                      </tbody>
                  </table>
              </div>
          </div>
          </body>
          </html>
          

          以上html用瀏覽器打開如下,亂碼是因?yàn)橹形淖煮w不識別,下面轉(zhuǎn)換的時候會加載對應(yīng)的字體來進(jìn)行轉(zhuǎn)換。

          使用Java轉(zhuǎn)換HTML到PDF代碼如下:

          public class HtmlToPDFOpenSource {
              public static void main(String[] args) throws IOException {
                  HtmlToPDFOpenSource htmlToPDFOpenSource=new HtmlToPDFOpenSource();
                  htmlToPDFOpenSource.generatePdfByOpenhtmltopdf();
              }
          
              private  void generatePdfByOpenhtmltopdf() throws IOException {
                  File inputHtml=new File("E:\\javaNorth\\java-study-note\\javaOpenSource\\src\\main\\resources\\test.html");
          
                  //加載html文件
                  Document document=Jsoup.parse(inputHtml, "UTF-8");
                  document.outputSettings().syntax(Document.OutputSettings.Syntax.html);
                  
                  //引入資源目錄,可以單獨(dú)引入css,圖片文件等
                  String baseUri=FileSystems.getDefault()
                      .getPath("javaOpenSource\\src\\main\\resources")
                      .toUri().toString();
                 
                  try (OutputStream os=new FileOutputStream("javaOpenSource\\src\\main\\resources\\testOpenLeagueoflegends1.pdf")) {
                      PdfRendererBuilder builder=new PdfRendererBuilder();
                      builder.withUri("javaOpenSource\\src\\main\\resources\\testOpenLeagueoflegends1.pdf");
                      builder.toStream(os);
                      builder.withW3cDocument(new W3CDom().fromJsoup(document), baseUri);
                      
                      //引入指定字體,注意字體名需要和css樣式中指定的字體名相同
                      builder.useFont(new File("javaOpenSource\\src\\main\\resources\\fonts\\msyh.ttf"),"msyh",1,BaseRendererBuilder.FontStyle.NORMAL, true);
                      builder.run();
                  }
              }
          }
          

          使用Java代碼轉(zhuǎn)換成PDF如下(示例中使用了微軟雅黑中文字體):

          上述html文件中增加如下外部樣式

          <link href="style.css" rel="stylesheet">
          

          并在resources目錄下添加style.css文件,重新生成PDF文件如下。

          3. 總結(jié)

          本片介紹了使用OpenPDF將html文件轉(zhuǎn)換成PDF文件。同時也使用了自定義字體,外部樣式。但是以下幾點(diǎn)需要格外注意。

          • Java代碼中加載的字體名稱要和HTML引用的CSS樣式中的字體名相同 ({font-family:"msyh";})。
          • HTML文件標(biāo)簽節(jié)點(diǎn)必須閉合(<xxx></xxx>).否則解析會失敗。

          全部示例在此:https://github.com/javatechnorth/java-study-note/tree/master/javaOpenSource/src/main/java/pdf

          文章來源:Java技術(shù)指北

          om-to-image庫可以幫你把dom節(jié)點(diǎn)轉(zhuǎn)換為圖片,它的核心原理很簡單,就是利用svg的foreignObject標(biāo)簽?zāi)芮度雋tml的特性,然后通過img標(biāo)簽加載svg,最后再通過canvas繪制img實(shí)現(xiàn)導(dǎo)出,好了,本文到此結(jié)束。

          另一個知名的html2canvas庫其實(shí)也支持這種方式。

          雖然原理很簡單,但是dom-to-image畢竟也有1000多行代碼,所以我很好奇它具體都做了哪些事情,本文就來詳細(xì)剖析一下,需要說明的是dom-to-image庫已經(jīng)六七年前沒有更新了,可能有點(diǎn)過時,所以我們要看的是基于它修改的dom-to-image-more庫,這個庫修復(fù)了一些bug,以及增加了一些特性,接下來我們就來詳細(xì)了解一下。

          將節(jié)點(diǎn)轉(zhuǎn)換成圖片

          我們用的最多的api應(yīng)該就是toPng(node),所以以這個方法為入口:

          function toPng(node, options) {
              return draw(node, options).then(function (canvas) {
                  return canvas.toDataURL();
              });
          }
          

          toPng方法會調(diào)用draw方法,然后返回一個canvas,最后通過canvas的toDataURL方法獲取到圖片的base64格式的data:URL,我們就可以直接下載為圖片。

          看一下draw方法:

          function draw(domNode, options) {
              options=options || {};
              return toSvg(domNode, options)// 轉(zhuǎn)換成svg
                  .then(util.makeImage)// 轉(zhuǎn)換成圖片
                  .then(function (image) {// 通過canvas繪制圖片
                      // ...
                });
          }
          

          一共分為了三個步驟,一一來看。

          將節(jié)點(diǎn)轉(zhuǎn)換成svg

          toSvg方法如下:

          function toSvg(node, options) {
              const ownerWindow=domtoimage.impl.util.getWindow(node);
              options=options || {};
              copyOptions(options);
              let restorations=[];
              return Promise.resolve(node)
                  .then(ensureElement)// 檢查和包裝元素
                  .then(function (clonee) {// 深度克隆節(jié)點(diǎn)
                      return cloneNode(clonee, options, null, ownerWindow);
                  })
                  .then(embedFonts)// 嵌入字體
                  .then(inlineImages)// 內(nèi)聯(lián)圖片
                  .then(makeSvgDataUri)// svg轉(zhuǎn)data:URL
                  .then(restoreWrappers)// 恢復(fù)包裝元素
          }
          

          node就是我們要轉(zhuǎn)換成圖片的DOM節(jié)點(diǎn),首先調(diào)用了getWindow方法獲取window對象:

          function getWindow(node) {
              const ownerDocument=node ? node.ownerDocument : undefined;
              return (
                  (ownerDocument ? ownerDocument.defaultView : undefined) ||
                  global ||
                  window
              );
          }
          

          說實(shí)話前端寫了這么多年,但是ownerDocument和defaultView兩個屬性我完全沒用過,ownerDocument屬性會返回當(dāng)前節(jié)點(diǎn)的頂層的 document對象,而在瀏覽器中,defaultView屬性會返回當(dāng)前 document 對象所關(guān)聯(lián)的 window 對象,如果沒有,會返回 null。

          所以這里優(yōu)先通過我們傳入的DOM節(jié)點(diǎn)獲取window對象,可能是為了處理iframe嵌入之類的情況把。

          接下來合并了選項(xiàng)后,就通過Promise實(shí)例的then方法鏈?zhǔn)降恼{(diào)用一系列的方法,一一來看。

          檢查和包裝元素

          ensureElement方法如下:

          function ensureElement(node) {
              // ELEMENT_NODE:1
              if (node.nodeType===ELEMENT_NODE) return node;
              const originalChild=node;
              const originalParent=node.parentNode;
              const wrappingSpan=document.createElement('span');
              originalParent.replaceChild(wrappingSpan, originalChild);
              wrappingSpan.append(node);
              restorations.push({
                  parent: originalParent,
                  child: originalChild,
                  wrapper: wrappingSpan,
              });
              return wrappingSpan;
          }
          

          html節(jié)點(diǎn)的nodeType有如下類型:

          值為1也就是我們普通的html標(biāo)簽,其他的比如文本節(jié)點(diǎn)、注釋節(jié)點(diǎn)、document節(jié)點(diǎn)也是比較常用的,如果我們傳入的節(jié)點(diǎn)的類型為1,ensureElement方法什么也不做直接返回該節(jié)點(diǎn),否則會創(chuàng)建一個span標(biāo)簽替換掉原節(jié)點(diǎn),并把原節(jié)點(diǎn)添加到該span標(biāo)簽里,可以猜測這個主要是處理文本節(jié)點(diǎn),畢竟應(yīng)該沒有人會傳其他類型的節(jié)點(diǎn)進(jìn)行轉(zhuǎn)換了。

          同時它還把原節(jié)點(diǎn),原節(jié)點(diǎn)的父節(jié)點(diǎn),span標(biāo)簽都收集到restorations數(shù)組里,很明顯,這是為了后面進(jìn)行還原。

          克隆節(jié)點(diǎn)

          接下來執(zhí)行了cloneNode方法:

          cloneNode(clonee, options, null, ownerWindow)
          
          // 參數(shù):需要克隆的節(jié)點(diǎn)、選項(xiàng)、父節(jié)點(diǎn)的樣式、所屬window對象
          function cloneNode(node, options, parentComputedStyles, ownerWindow) {
              const filter=options.filter;
              if (
                  node===sandbox ||
                  util.isHTMLScriptElement(node) ||
                  util.isHTMLStyleElement(node) ||
                  util.isHTMLLinkElement(node) ||
                  (parentComputedStyles !==null && filter && !filter(node))
              ) {
                  return Promise.resolve();
              }
              return Promise.resolve(node)
                  .then(makeNodeCopy)// 處理canvas元素
                  .then(function (clone) {// 克隆子節(jié)點(diǎn)
                      return cloneChildren(clone, getParentOfChildren(node));
                  })
                  .then(function (clone) {// 處理克隆的節(jié)點(diǎn)
                      return processClone(clone, node);
                  });
          }
          

          先做了一堆判斷,如果是script、style、link標(biāo)簽,或者需要過濾掉的節(jié)點(diǎn),那么會直接返回。

          sandbox、parentComputedStyles后面會看到。

          接下來又調(diào)用了幾個方法,沒辦法,跟著它一起入棧把。

          處理canvas元素的克隆

          function makeNodeCopy(original) {
              if (util.isHTMLCanvasElement(original)) {
                  return util.makeImage(original.toDataURL());
              }
              return original.cloneNode(false);
          }
          

          如果元素是canvas,那么會通過makeImage方法將其轉(zhuǎn)換成img標(biāo)簽:

          function makeImage(uri) {
              if (uri==='data:,') {
                  return Promise.resolve();
              }
              return new Promise(function (resolve, reject) {
                  const image=new Image();
                  if (domtoimage.impl.options.useCredentials) {
                      image.crossOrigin='use-credentials';
                  }
                  image.onload=function () {
                      if (window && window.requestAnimationFrame) {
                          // 解決 Firefox 的一個bug (webcompat/web-bugs#119834) 
                          // 需要等待一幀
                          window.requestAnimationFrame(function () {
                              resolve(image);
                          });
                      } else {
                          // 如果沒有window對象或者requestAnimationFrame方法,那么立即返回
                          resolve(image);
                      }
                  };
                  image.onerror=reject;
                  image.src=uri;
              });
          }
          

          crossOrigin屬性用于定義一些元素如何處理跨域請求,主要有兩個取值:

          anonymous:元素的跨域資源請求不需要憑證標(biāo)志設(shè)置。

          use-credentials:元素的跨域資源請求需要憑證標(biāo)志設(shè)置,意味著該請求需要提供憑證。

          除了use-credentials,給crossOrigin設(shè)置其他任何值都會解析成anonymous,為了解決跨域問題,我們一般都會設(shè)置成anonymous,這個就相當(dāng)于告訴服務(wù)器,你不需要返回任何非匿名信息過來,例如cookie,所以肯定是安全的。不過在使用這兩個值時都需要服務(wù)端返回Access-Control-Allow-Credentials響應(yīng)頭,否則肯定無法跨域使用的。

          非canvas元素的其他元素,會直接調(diào)用它們的cloneNode方法進(jìn)行克隆,參數(shù)傳了false,代表只克隆自身,不克隆子節(jié)點(diǎn)。

          克隆子節(jié)點(diǎn)

          接下來調(diào)用了cloneChildren方法:

          cloneChildren(clone, getParentOfChildren(node));
          

          getParentOfChildren方法如下:

          function getParentOfChildren(original) {
              // 如果該節(jié)點(diǎn)是Shadow DOM的附加節(jié)點(diǎn),那么返回附加的Shadow DOM的根節(jié)點(diǎn)
              if (util.isElementHostForOpenShadowRoot(original)) {
                  return original.shadowRoot; 
              }
              return original;
          }
          function isElementHostForOpenShadowRoot(value) {
              return isElement(value) && value.shadowRoot !==null;
          }
          

          這里涉及到了shadow DOM,有必要先簡單了解一下。

          shadow DOM是一種封裝技術(shù),可以將標(biāo)記結(jié)構(gòu)、樣式和行為隱藏起來,比如我們熟悉的video標(biāo)簽,我們看到的只是一個video標(biāo)簽,但實(shí)際上它里面有很多我們看不到的元素,這個特性一般會和Web components結(jié)合使用,也就是可以創(chuàng)建自定義元素,就和Vue和React組件一樣。

          先了解一些術(shù)語:

          Shadow host:一個常規(guī) DOM 節(jié)點(diǎn),Shadow DOM 會被附加到這個節(jié)點(diǎn)上。

          Shadow tree:Shadow DOM 內(nèi)部的 DOM 樹。

          Shadow boundary:Shadow DOM 結(jié)束的地方,也是常規(guī) DOM 開始的地方。

          Shadow root: Shadow tree 的根節(jié)點(diǎn)。

          一個普通的DOM元素可以使用attachShadow方法來添加shadow DOM:

          let shadow=div.attachShadow({ mode: "open" });
          

          這樣就可以給div元素附加一個shadow DOM,然后我們可以和創(chuàng)建普通元素一樣創(chuàng)建任何元素添加到shadow下:

          let para=document.createElement('p');
          shadow.appendChild(para);
          

          當(dāng)mode設(shè)為open,我們就可以通過div.shadowRoot獲取到Shadow DOM,如果設(shè)置的是closed,那么外部就獲取不到。

          所以前面的getParentOfChildren方法會判斷當(dāng)前節(jié)點(diǎn)是不是一個Shadow host節(jié)點(diǎn),是的話就返回它內(nèi)部的Shadow root節(jié)點(diǎn),否則返回自身。

          回到cloneChildren方法,它接收兩個參數(shù):克隆的節(jié)點(diǎn)、原節(jié)點(diǎn)。

          function cloneChildren(clone, original) {
              // 獲取子節(jié)點(diǎn),如果原節(jié)點(diǎn)是slot節(jié)點(diǎn),那么會返回slot內(nèi)的節(jié)點(diǎn),
              const originalChildren=getRenderedChildren(original);
              let done=Promise.resolve();
              if (originalChildren.length !==0) {
                  // 獲取原節(jié)點(diǎn)的計算樣式,如果原節(jié)點(diǎn)是shadow root節(jié)點(diǎn),那么會獲取它所附加到的普通元素的樣式
                  const originalComputedStyles=getComputedStyle(
                      getRenderedParent(original)
                  );
                  // 遍歷子節(jié)點(diǎn)
                  util.asArray(originalChildren).forEach(function (originalChild) {
                      done=done.then(function () {
                          // 遞歸調(diào)用cloneNode方法
                          return cloneNode(
                              originalChild,
                              options,
                              originalComputedStyles,
                              ownerWindow
                          ).then(function (clonedChild) {
                              // 克隆完后的子節(jié)點(diǎn)添加到該節(jié)點(diǎn)
                              if (clonedChild) {
                                  clone.appendChild(clonedChild);
                              }
                          });
                      });
                  });
              }
              return done.then(function () {
                  return clone;
              });
          }
          

          首先通過getRenderedChildren方法獲取子節(jié)點(diǎn):

          function getRenderedChildren(original) {
              // 如果是slot元素,那么通過assignedNodes方法返回該插槽中的節(jié)點(diǎn)
              if (util.isShadowSlotElement(original)) {
                  return original.assignedNodes();
              }
              // 普通元素直接通過childNodes獲取子節(jié)點(diǎn)
              return original.childNodes;
          }
          // 判斷是否是html slot元素
          function isShadowSlotElement(value) {
              return (
                  isInShadowRoot(value) && value instanceof getWindow(value).HTMLSlotElement
              );
          }
          // 判斷一個節(jié)點(diǎn)是否處于shadow DOM樹中
          function isInShadowRoot(value) {
              // 如果是普通節(jié)點(diǎn),getRootNode方法會返回document對象,如果是Shadow DOM,那么會返回shadow root
              return (
                  value !==null &&
                  Object.prototype.hasOwnProperty.call(value, 'getRootNode') &&
                  isShadowRoot(value.getRootNode())
              );
          }
          // 判斷是否是shadow DOM的根節(jié)點(diǎn)
          function isShadowRoot(value) {
              return value instanceof getWindow(value).ShadowRoot;
          }
          

          這一連串的判斷,如果對于shadow DOM不熟悉的話大概率很難看懂,不過沒關(guān)系,跳過這部分也可以,反正就是獲取子節(jié)點(diǎn)。

          獲取到子節(jié)點(diǎn)后又調(diào)用了如下方法:

          const originalComputedStyles=getComputedStyle(
              getRenderedParent(original)
          );
          function getRenderedParent(original) {
              // 如果該節(jié)點(diǎn)是shadow root,那么返回它附加到的普通的DOM節(jié)點(diǎn)
              if (util.isShadowRoot(original)) {
                  return original.host;
              }
              return original;
          }
          

          調(diào)用getComputedStyle獲取原節(jié)點(diǎn)的樣式,這個方法其實(shí)就是window.getComputedStyle方法,會返回節(jié)點(diǎn)的所有樣式和值。

          接下來就是遍歷子節(jié)點(diǎn),然后對每個子節(jié)點(diǎn)再次調(diào)用cloneNode方法,只不過會把原節(jié)點(diǎn)的樣式也傳進(jìn)去。對于子元素又會遞歸處理它們的子節(jié)點(diǎn),這樣就能深度克隆完整棵DOM樹。

          處理克隆的節(jié)點(diǎn)

          對于每個克隆節(jié)點(diǎn),又調(diào)用了processClone(clone, node)方法:

          function processClone(clone, original) {
              // 如果不是普通節(jié)點(diǎn),或者是slot節(jié)點(diǎn),那么直接返回
              if (!util.isElement(clone) || util.isShadowSlotElement(original)) {
                  return Promise.resolve(clone);
              }
              return Promise.resolve()
                  .then(cloneStyle)// 克隆樣式
                  .then(clonePseudoElements)// 克隆偽元素
                  .then(copyUserInput)// 克隆輸入框
                  .then(fixSvg)// 修復(fù)svg
                  .then(function () {
                      return clone;
                  });
          }
          

          又是一系列的操作,穩(wěn)住,我們繼續(xù)。

          克隆樣式

          function cloneStyle() {
              copyStyle(original, clone);
          }
          

          調(diào)用了copyStyle方法,傳入原節(jié)點(diǎn)和克隆節(jié)點(diǎn):

          function copyStyle(sourceElement, targetElement) {
              const sourceComputedStyles=getComputedStyle(sourceElement);
              if (sourceComputedStyles.cssText) {
                 // ...
              } else {
                 // ...
              }
          }
          

          window.getComputedStyle方法返回的是一個CSSStyleDeclaration對象,和我們使用div.style獲取到的對象類型是一樣的,但是div.style對象只能獲取到元素的內(nèi)聯(lián)樣式,使用div.style.color='#fff'設(shè)置的也能獲取到,因?yàn)檫@種方式設(shè)置的也是內(nèi)聯(lián)樣式,其他樣式是獲取不到的,但是window.getComputedStyle能獲取到所有css樣式。

          div.style.cssText屬性我們都用過,可以獲取和批量設(shè)置內(nèi)聯(lián)樣式,如果要設(shè)置多個樣式,比單個調(diào)用div.style.xxx方便一點(diǎn),但是cssText會覆蓋整個內(nèi)聯(lián)樣式,比如下面的方式設(shè)置的字號是會丟失的,內(nèi)聯(lián)樣式最終只有color:

          div.style.fontSize='23px'
          div.style.cssText='color: rgb(102, 102, 102)'
          

          但是window.getComputedStyle方法返回的對象的cssText和div.style.cssText不是同一個東西,即使有內(nèi)聯(lián)樣式,window.getComputedStyle方法返回對象的cssText值也是空,并且它無法修改,所以不清楚什么情況下它才會有值。

          假設(shè)有值的話,接下來的代碼我也不是很能理解:

          if (sourceComputedStyles.cssText) {
              targetElement.style.cssText=sourceComputedStyles.cssText;
              copyFont(sourceComputedStyles, targetElement.style);
          }
          
          function copyFont(source, target) {
              target.font=source.font;
              target.fontFamily=source.fontFamily;
              // ...
          }
          

          為什么不直接把原節(jié)點(diǎn)的style.cssText復(fù)制給克隆節(jié)點(diǎn)的style.cssText呢,另外為啥文本相關(guān)的樣式又要單獨(dú)設(shè)置一遍呢,無法理解。

          我們看看另外一個分支:

          else {
              copyUserComputedStyleFast(
                  options,
                  sourceElement,
                  sourceComputedStyles,
                  parentComputedStyles,
                  targetElement
              );
              // ...
          }
          

          先調(diào)用了copyUserComputedStyleFast方法,這個方法內(nèi)部非常復(fù)雜,就不把具體代碼放出來了,大致介紹一下它都做了什么:

          1.首先會獲取原節(jié)點(diǎn)的所謂的默認(rèn)樣式,這個步驟也比較復(fù)雜:

          1.1.先獲取原節(jié)點(diǎn)及祖先節(jié)點(diǎn)的元素標(biāo)簽列表,其實(shí)就是一個向上遞歸的過程,不過存在終止條件,就是當(dāng)遇到塊級元素的祖先節(jié)點(diǎn)。比如原節(jié)點(diǎn)是一個span標(biāo)簽,它的父節(jié)點(diǎn)也是一個span,再上一個父節(jié)點(diǎn)是一個div,那么獲取到的標(biāo)簽列表就是[span, span, div]。

          ? 1.2.接下來會創(chuàng)建一個沙箱,也就是一個iframe,這個iframe的DOCTYPE和charset會設(shè)置成和當(dāng)前頁面的一樣。

          ? 1.3.再接下來會根據(jù)前面獲取到的標(biāo)簽列表,在iframe中創(chuàng)建對應(yīng)結(jié)構(gòu)的DOM節(jié)點(diǎn),也就是會創(chuàng)建這樣一棵DOM樹:div -> span -> span。并且會給最后一個節(jié)點(diǎn)添加一個零寬字符的文本,并返回這個節(jié)點(diǎn)。

          ? 1.4.使用iframe的window.getComputedStyle方法獲取上一步返回節(jié)點(diǎn)的樣式,對于width和height會設(shè)置成auto。

          ? 1.5.刪除iframe里前面創(chuàng)建的節(jié)點(diǎn)。

          ? 16.返回1.4步獲取到的樣式對象。

          2.遍歷原節(jié)點(diǎn)的樣式,也就是sourceComputedStyles對象,對于每一個樣式屬性,都會獲取到三個值:sourceValue、defaultValue、parentValue,分別來自原節(jié)點(diǎn)的樣式對象sourceComputedStyles、第一步獲取到的默認(rèn)樣式對象、父節(jié)點(diǎn)的樣式對象parentComputedStyles,然后會做如下判斷:

          if (
              sourceValue !==defaultValue ||
              (parentComputedStyles && sourceValue !==parentValue)
          ) {
              // 樣式優(yōu)先級,比如important
              const priority=sourceComputedStyles.getPropertyPriority(name);
              // 將樣式設(shè)置到克隆節(jié)點(diǎn)的style對象上
              setStyleProperty(targetStyle, name, sourceValue, priority);
          }
          

          如果原節(jié)點(diǎn)的某個樣式值和默認(rèn)的樣式值不一樣,并且和父節(jié)點(diǎn)的也不一樣,那么就需要給克隆的節(jié)點(diǎn)手動設(shè)置成內(nèi)聯(lián)樣式,否則其實(shí)就是繼承樣式或者默認(rèn)樣式,就不用管了,不得不說,還是挺巧妙的。

          copyUserComputedStyleFast方法執(zhí)行完后還做了如下操作:

          if (parentComputedStyles===null) {
              [
                  'inset-block',
                  'inset-block-start',
                  'inset-block-end',
              ].forEach((prop)=> targetElement.style.removeProperty(prop));
              ['left', 'right', 'top', 'bottom'].forEach((prop)=> {
                  if (targetElement.style.getPropertyValue(prop)) {
                      targetElement.style.setProperty(prop, '0px');
                  }
              });
          }
          

          對于我們傳入的節(jié)點(diǎn),parentComputedStyles是null,本質(zhì)相當(dāng)于根節(jié)點(diǎn),所以直接移除它的位置信息,防止發(fā)生偏移。

          克隆偽元素

          克隆完樣式,接下來就是處理偽元素了:

          function clonePseudoElements() {
              const cloneClassName=util.uid();
              [':before', ':after'].forEach(function (element) {
                  clonePseudoElement(element);
              });
          }
          

          分別調(diào)用clonePseudoElement方法處理兩種偽元素:

          function clonePseudoElement(element) {
              // 獲取原節(jié)點(diǎn)偽元素的樣式
              const style=getComputedStyle(original, element);
              // 獲取偽元素的content
              const content=style.getPropertyValue('content');
              // 如果偽元素的內(nèi)容為空就直接返回
              if (content==='' || content==='none') {
                  return;
              }
              // 獲取克隆節(jié)點(diǎn)的類名
              const currentClass=clone.getAttribute('class') || '';
              // 給克隆元素增加一個唯一的類名
              clone.setAttribute('class', `${currentClass} ${cloneClassName}`);
           // 創(chuàng)建一個style標(biāo)簽
              const styleElement=document.createElement('style');
              // 插入偽元素的樣式
              styleElement.appendChild(formatPseudoElementStyle());
              // 將樣式標(biāo)簽添加到克隆節(jié)點(diǎn)內(nèi)
              clone.appendChild(styleElement);
          }
          

          window.getComputedStyle方法是可以獲取元素的偽元素的樣式的,通過第二個參數(shù)指定要獲取的偽元素即可。

          如果偽元素的content為空就不管了,總感覺有點(diǎn)不妥,畢竟我經(jīng)常會用偽元素渲染一些三角形,content都是設(shè)置成空的。

          如果不為空,那么會給克隆的節(jié)點(diǎn)新增一個唯一的類名,并且創(chuàng)建一個style標(biāo)簽添加到克隆節(jié)點(diǎn)內(nèi),這個style標(biāo)簽里會插入偽元素的樣式,通過formatPseudoElementStyle方法獲取偽元素的樣式字符串:

          function formatPseudoElementStyle() {
              const selector=`.${cloneClassName}:${element}`;
              // style為原節(jié)點(diǎn)偽元素的樣式對象
              const cssText=style.cssText
              ? formatCssText()
              : formatCssProperties();
          
              return document.createTextNode(`${selector}{${cssText}}`);
          }
          

          如果樣式對象的cssText有值,那么調(diào)用formatCssText方法:

          function formatCssText() {
              return `${style.cssText} content: ${content};`;
          }
          

          但是前面說了,這個屬性一般都是沒值的,所以會走formatCssProperties方法:

          function formatCssProperties() {
              const styleText=util
                  .asArray(style)
                  .map(formatProperty)
                  .join('; ');
              return `${styleText};`;
          
              function formatProperty(name) {
                  const propertyValue=style.getPropertyValue(name);
                  const propertyPriority=style.getPropertyPriority(name)
                  ? ' !important'
                  : '';
                  return `${name}: ${propertyValue}${propertyPriority}`;
              }
          }
          

          很簡單,遍歷樣式對象,然后拼接成css的樣式字符串。

          克隆輸入框

          對于輸入框的處理很簡單:

          function copyUserInput() {
              if (util.isHTMLTextAreaElement(original)) {
                  clone.innerHTML=original.value;
              }
              if (util.isHTMLInputElement(original)) {
                  clone.setAttribute('value', original.value);
              }
          }
          

          如果是textarea或者input元素,直接將原節(jié)點(diǎn)的值設(shè)置到克隆后的元素上即可。但是我測試發(fā)現(xiàn)克隆輸入框也會把它的值給克隆過去,所以這一步可能沒有必要。

          修復(fù)svg

          最后就是處理svg節(jié)點(diǎn):

          function fixSvg() {
              if (util.isSVGElement(clone)) {
                  clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
                  if (util.isSVGRectElement(clone)) {
                      ['width', 'height'].forEach(function (attribute) {
                          const value=clone.getAttribute(attribute);
                          if (value) {
                              clone.style.setProperty(attribute, value);
                          }
                      });
                  }
              }
          }
          

          給svg節(jié)點(diǎn)添加命名空間,另外對于rect節(jié)點(diǎn),還把寬高的屬性設(shè)置成對應(yīng)的樣式,這個是何原因,我們也不得而知。

          到這里,節(jié)點(diǎn)的克隆部分就結(jié)束了,不得不說,還是有點(diǎn)復(fù)雜的,很多操作其實(shí)我們也沒有看懂為什么要這么做,開發(fā)一個庫就是這樣,要處理很多邊界和異常情況,這個只有遇到了才知道為什么。

          嵌入字體

          節(jié)點(diǎn)克隆完后接下來會處理字體:

          function embedFonts(node) {
              return fontFaces.resolveAll().then(function (cssText) {
                  if (cssText !=='') {
                      const styleNode=document.createElement('style');
                      node.appendChild(styleNode);
                      styleNode.appendChild(document.createTextNode(cssText));
                  }
                  return node;
              });
          }
          

          調(diào)用resolveAll方法,會返回一段css字符串,然后創(chuàng)建一個style標(biāo)簽添加到克隆的節(jié)點(diǎn)內(nèi),接下來看看resolveAll方法都做了什么:

          function resolveAll() {
              return readAll()
                  // ...
          }
          

          又調(diào)用了readAll方法:

          function readAll() {
              return Promise.resolve(util.asArray(document.styleSheets))
                  .then(getCssRules)
                  .then(selectWebFontRules)
                  .then(function (rules) {
                      return rules.map(newWebFont);
                  });
          }
          

          document.styleSheets屬性可以獲取到文檔中所有的style標(biāo)簽和通過link標(biāo)簽引入的樣式,結(jié)果是一個類數(shù)組,數(shù)組的每一項(xiàng)是一個CSSStyleSheet對象。

          function getCssRules(styleSheets) {
              const cssRules=[];
              styleSheets.forEach(function (sheet) {
                  if (
                      Object.prototype.hasOwnProperty.call(
                          Object.getPrototypeOf(sheet),
                          'cssRules'
                      )
                  ) {
                      util.asArray(sheet.cssRules || []).forEach(
                          cssRules.push.bind(cssRules)
                      );
                  }
              });
              return cssRules;
          }
          

          通過CSSStyleSheet對象的cssRules屬性可以獲取到具體的css規(guī)則,cssRules的每一項(xiàng)也就是我們寫的一條css語句:

          function selectWebFontRules(cssRules) {
              return cssRules
                  .filter(function (rule) {
                      return rule.type===CSSRule.FONT_FACE_RULE;
                  })
                  .filter(function (rule) {
                      return inliner.shouldProcess(rule.style.getPropertyValue('src'));
                  });
          }
          

          遍歷所有的css語句,找出其中的@font-face語句,shouldProcess方法會判斷@font-face語句的src屬性是否存在url()值,找出了所有存在的字體規(guī)則后會遍歷它們調(diào)用newWebFont方法:

          function newWebFont(webFontRule) {
              return {
                  resolve: function resolve() {
                      const baseUrl=(webFontRule.parentStyleSheet || {}).href;
                      return inliner.inlineAll(webFontRule.cssText, baseUrl);
                  },
                  src: function () {
                      return webFontRule.style.getPropertyValue('src');
                  },
              };
          }
          

          inlineAll方法會找出@font-face語句中定義的所有字體的url,然后通過XMLHttpRequest發(fā)起請求,將字體文件轉(zhuǎn)換成data:URL形式,然后替換css語句中的url,核心就是使用下面這個正則匹配和替換。

          const URL_REGEX=/url\(['"]?([^'"]+?)['"]?\)/g;
          

          繼續(xù)resolveAll方法:

          function resolveAll() {
              return readAll()
                  .then(function (webFonts) {
                      return Promise.all(
                          webFonts.map(function (webFont) {
                              return webFont.resolve();
                          })
                      );
                  })
                  .then(function (cssStrings) {
                      return cssStrings.join('\n');
                  });
          }
          

          將所有@font-face語句的遠(yuǎn)程字體url都轉(zhuǎn)換成data:URL形式后再將它們拼接成css字符串即可完成嵌入字體的操作。

          說實(shí)話,Promise鏈太長,看著容易暈。

          內(nèi)聯(lián)圖片

          內(nèi)聯(lián)完了字體后接下來就是內(nèi)聯(lián)圖片:

          function inlineImages(node) {
              return images.inlineAll(node).then(function () {
                  return node;
              });
          }
          

          處理圖片的inlineAll方法如下:

          function inlineAll(node) {
              if (!util.isElement(node)) {
                  return Promise.resolve(node);
              }
              return inlineCSSProperty(node).then(function () {
                  // ...
              });
          }
          

          inlineCSSProperty方法會判斷節(jié)點(diǎn)background和 background-image屬性是否設(shè)置了圖片,是的話也會和嵌入字體一樣將遠(yuǎn)程圖片轉(zhuǎn)換成data:URL嵌入:

          function inlineCSSProperty(node) {
              const properties=['background', 'background-image'];
              const inliningTasks=properties.map(function (propertyName) {
                  const value=node.style.getPropertyValue(propertyName);
                  const priority=node.style.getPropertyPriority(propertyName);
                  if (!value) {
                      return Promise.resolve();
                  }
                  // 如果設(shè)置了背景圖片,那么也會調(diào)用inliner.inlineAll方法將遠(yuǎn)程url的形式轉(zhuǎn)換成data:URL形式
                  return inliner.inlineAll(value).then(function (inlinedValue) {
                      // 將樣式設(shè)置成轉(zhuǎn)換后的值
                      node.style.setProperty(propertyName, inlinedValue, priority);
                  });
              });
              return Promise.all(inliningTasks).then(function () {
                  return node;
              });
          }
          

          處理完節(jié)點(diǎn)的背景圖片后:

          function inlineAll(node) {
              return inlineCSSProperty(node).then(function () {
                  if (util.isHTMLImageElement(node)) {
                      return newImage(node).inline();
                  } else {
                      return Promise.all(
                          util.asArray(node.childNodes).map(function (child) {
                              return inlineAll(child);
                          })
                      );
                  }
              });
          }
          

          會檢查節(jié)點(diǎn)是否是圖片節(jié)點(diǎn),是的話會調(diào)用newImage方法處理,這個方法也很簡單,也是發(fā)個請求獲取圖片數(shù)據(jù),然后將它轉(zhuǎn)換成data:URL設(shè)置回圖片的src。

          如果是其他節(jié)點(diǎn),那么就遞歸處理子節(jié)點(diǎn)。

          將svg轉(zhuǎn)換成data:URL

          圖片也處理完了接下來就可以將svg轉(zhuǎn)換成data:URL了:

          function makeSvgDataUri(node) {
              let width=options.width || util.width(node);
              let height=options.height || util.height(node);
          
              return Promise.resolve(node)
                  .then(function (svg) {
                      svg.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
                      return new XMLSerializer().serializeToString(svg);
                  })
                  .then(util.escapeXhtml)
                  .then(function (xhtml) {
                      const foreignObjectSizing=          (util.isDimensionMissing(width)
                             ? ' width="100%"'
                             : ` width="${width}"`) +
                            (util.isDimensionMissing(height)
                             ? ' height="100%"'
                             : ` height="${height}"`);
                      const svgSizing=          (util.isDimensionMissing(width) ? '' : ` width="${width}"`) +
                            (util.isDimensionMissing(height) ? '' : ` height="${height}"`);
                      return `<svg xmlns="http://www.w3.org/2000/svg"${svgSizing}> 
              <foreignObject${foreignObjectSizing}>${xhtml}</foreignObject>
             </svg>`;
                  })
                  .then(function (svg) {
                      return `data:image/svg+xml;charset=utf-8,${svg}`;
                  });
          }
          

          其中的isDimensionMissing方法就是判斷是否是不合法的數(shù)字。

          主要做了四件事。

          一是給節(jié)點(diǎn)添加命名空間,并使用XMLSerializer對象來將DOM節(jié)點(diǎn)序列化成字符串。

          二是轉(zhuǎn)換DOM字符串中的一些字符:

          function escapeXhtml(string) {
              return string.replace(/%/g, '%25').replace(/#/g, '%23').replace(/\n/g, '%0A');
          }
          

          第三步就是拼接svg字符串了,將序列化后的字符串使用foreignObject標(biāo)簽包裹,同時會計算一下DOM節(jié)點(diǎn)的寬高設(shè)置到svg上。

          最后一步是拼接成data:URL的形式。

          恢復(fù)包裝元素

          在最開始的【檢查和包裝元素】步驟會替換掉節(jié)點(diǎn)類型不為1的節(jié)點(diǎn),這一步就是用來恢復(fù)這個操作:

          function restoreWrappers(result) {
              while (restorations.length > 0) {
                  const restoration=restorations.pop();
                  restoration.parent.replaceChild(restoration.child, restoration.wrapper);
              }
              return result;
          }
          

          這一步結(jié)束后將節(jié)點(diǎn)轉(zhuǎn)換成svg的操作就結(jié)束了。

          將svg轉(zhuǎn)換成圖片

          現(xiàn)在我們可以回到draw方法:

          function draw(domNode, options) {
                  options=options || {};
                  return toSvg(domNode, options)
                      .then(util.makeImage)
                      .then(function (image) {
                          // ...
                      });
          }
          

          獲取到了svg的data:URL后會調(diào)用makeImage方法將它轉(zhuǎn)換成圖片,這個方法前面我們已經(jīng)看過了,這里就不重復(fù)說了。

          將圖片通過canvas導(dǎo)出

          繼續(xù)draw方法:

          function draw(domNode, options) {
                  options=options || {};
                  return toSvg(domNode, options)
                      .then(util.makeImage)
                      .then(function (image) {
                          const scale=typeof options.scale !=='number' ? 1 : options.scale;
                          const canvas=newCanvas(domNode, scale);
                          const ctx=canvas.getContext('2d');
                          ctx.msImageSmoothingEnabled=false;// 禁用圖像平滑
                          ctx.imageSmoothingEnabled=false;// 禁用圖像平滑
                          if (image) {
                              ctx.scale(scale, scale);
                              ctx.drawImage(image, 0, 0);
                          }
                          return canvas;
                      });
          }
          

          先調(diào)用newCanvas方法創(chuàng)建一個canvas:

          function newCanvas(node, scale) {
              let width=options.width || util.width(node);
              let height=options.height || util.height(node);
           // 如果寬度高度都沒有,那么默認(rèn)設(shè)置成300
              if (util.isDimensionMissing(width)) {
                  width=util.isDimensionMissing(height) ? 300 : height * 2.0;
              }
              // 如果高度沒有,那么默認(rèn)設(shè)置成寬度的一半
              if (util.isDimensionMissing(height)) {
                  height=width / 2.0;
              }
           // 創(chuàng)建canvas
              const canvas=document.createElement('canvas');
              canvas.width=width * scale;
              canvas.height=height * scale;
           // 設(shè)置背景顏色
              if (options.bgcolor) {
                  const ctx=canvas.getContext('2d');
                  ctx.fillStyle=options.bgcolor;
                  ctx.fillRect(0, 0, canvas.width, canvas.height);
              }
              return canvas;
          }
          

          把svg圖片繪制到canvas上后,就可以通過canvas.toDataURL()方法轉(zhuǎn)換成圖片的data:URL,你可以渲染到頁面,也可以直接進(jìn)行下載。

          總結(jié)

          本文通過源碼詳細(xì)介紹了dom-to-image-more的原理,核心就是克隆節(jié)點(diǎn)和節(jié)點(diǎn)樣式,內(nèi)聯(lián)字體、背景圖片、圖片,然后通過svg的foreignObject標(biāo)簽嵌入克隆后的節(jié)點(diǎn),最后將svg轉(zhuǎn)換成圖片,圖片繪制到canvas上進(jìn)行導(dǎo)出。

          可以看到源碼中大量的Promise,很多不是異步的邏輯也會通過then方法來進(jìn)行管道式調(diào)用,大部分情況會讓代碼很清晰,一眼就知道大概做了什么事情,但是部分地方串聯(lián)了太長,反倒不太容易理解。

          限于篇幅,源碼中其實(shí)還要很多有意思的細(xì)節(jié)沒有介紹,比如為了修改iframe的DOCTYPE和charset,居然寫了三種方式,雖然我覺得第一種就夠了,又比如獲取節(jié)點(diǎn)默認(rèn)樣式的方式,通過iframe創(chuàng)建同樣標(biāo)簽同樣層級的元素,說實(shí)話我是從來沒見過,再比如解析css中的字體的url時用的是如下方法:

          function resolveUrl(url, baseUrl) {
              const doc=document.implementation.createHTMLDocument();
              const base=doc.createElement('base');
              doc.head.appendChild(base);
              const a=doc.createElement('a');
              doc.body.appendChild(a);
              base.href=baseUrl;
              a.href=url;
              return a.href;
          }
          

          base標(biāo)簽我也是從來沒有見過。等等。

          所以看源碼還是挺有意思的一件事,畢竟平時寫業(yè)務(wù)代碼局限性太大了,很多東西都了解不到,強(qiáng)烈推薦各位去閱讀一下。

          天介紹一個根據(jù)html生成圖片的工具h(yuǎn)tml2canvas,主要原理是使用canvas繪制html,再使用canvas生成圖片。

          工具官網(wǎng)

          1. 安裝

          npm install html2canvas --save

          2. 引用

          import html2canvas from 'html2canvas'

          3. 使用

          如:生成id為result_page容器內(nèi)dom的圖片;

          html2canvas(document.querySelector("#result_page"), {scale:1,logging:false}).then(canvas=> {
           self.resultImgSrc=canvas.toDataURL("image/png");
          })
          
          

          注:scale:控制著放大比例,值越大越耗性能,生成的圖片越清晰,如果視口寬度為750px,設(shè)置為1即可;


          主站蜘蛛池模板: 亚洲国产精品一区二区第四页| 一区二区三区四区视频在线| 国产精品免费大片一区二区| 日产一区日产2区| 日日摸夜夜添一区| 香蕉免费看一区二区三区| 一本一道波多野结衣AV一区| 不卡无码人妻一区三区音频| 日本一区中文字幕日本一二三区视频 | 性无码免费一区二区三区在线| 激情综合丝袜美女一区二区| 亚洲一区二区观看播放| 亚洲丰满熟女一区二区v| 中文字幕日本一区| 国产成人一区在线不卡| 精品一区二区91| 精品无码国产一区二区三区麻豆| 久久久精品人妻一区二区三区四 | 99精品国产一区二区三区| 国产乱码精品一区二区三区四川| 亚洲国产AV无码一区二区三区| 国产福利91精品一区二区| 亚洲男女一区二区三区| 91福利一区二区| 国产成人久久精品区一区二区 | 无码人妻精品一区二区三区66 | 天堂一区人妻无码| 中字幕一区二区三区乱码| 中文字幕av人妻少妇一区二区| 91精品一区二区三区久久久久 | 精品少妇一区二区三区在线| 一区二区三区四区在线观看视频| 一区二区三区波多野结衣| 久久久精品日本一区二区三区 | 国产三级一区二区三区 | 色偷偷一区二区无码视频| 无码人妻视频一区二区三区| 精品国产a∨无码一区二区三区| 99热门精品一区二区三区无码 | 国产成人av一区二区三区在线| 日韩美女视频一区|