整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          java將html轉為pdf


          html轉為pdf的組件有很多,但是還沒有哪一款能達到這個效果,其只要原因是wkhtmltopdf使用webkit網頁渲染引擎開發的用來將 html轉成 pdf的工具,可以跟多種腳本語言進行集成來轉換文檔。但是就使用簡便性來說還是itext等組件占據優勢,如果你要轉換格式有比較高的要求,那么wkhtmltopdf絕對是不二之選!

          下載路徑

          官網地址 wkhtmltopdf.org/

          github地址 github.com/wkhtmltopdf…

          使用方法

          1. windows直接使用:只要在windows命令行中輸入c:\wkhtmltopdf.exe my.oschina.net/papio/blog/… c:\blog.pdf 就可以把這篇文章轉成pdf,并保存到C盤根目錄。
          2. java調用:java中調用wkhtmltopdf的命令Runtime.getRuntime().exec("c:\wkhtmltopdf.exe my.oschina.net/papio/blog/… c:\blog.pdf")就可以實現轉換。

          java調用demo

          public class HtmlToPdfInterceptor extends Thread { private InputStream is; public HtmlToPdfInterceptor(InputStream is){ this.is = is; } public void run(){ try{ InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line.toString()); //輸出內容 } }catch (IOException e){ e.printStackTrace(); } }}public class HtmlToPdf { //wkhtmltopdf在系統中的路徑 private static final String toPdfTool = "D:\wkhtmltopdf\bin\wkhtmltopdf.exe"; /** * html轉pdf * @param srcPath html路徑,可以是硬盤上的路徑,也可以是網絡路徑 * @param destPath pdf保存路徑 * @return 轉換成功返回true */ public static boolean convert(String srcPath, String destPath){ File file = new File(destPath); File parent = file.getParentFile(); //如果pdf保存路徑不存在,則創建路徑 if(!parent.exists()){ parent.mkdirs(); } StringBuilder cmd = new StringBuilder(); cmd.append(toPdfTool); cmd.append(" "); cmd.append(" --header-line");//頁眉下面的線 cmd.append(" --header-center 這里是頁眉這里是頁眉這里是頁眉這里是頁眉 ");//頁眉中間內容 //cmd.append(" --margin-top 30mm ");//設置頁面上邊距 (default 10mm) cmd.append(" --header-spacing 10 ");//(設置頁眉和內容的距離,默認0) cmd.append(srcPath); cmd.append(" "); cmd.append(destPath); boolean result = true; try{ Process proc = Runtime.getRuntime().exec(cmd.toString()); HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream()); HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream()); error.start(); output.start(); proc.waitFor(); }catch(Exception e){ result = false; e.printStackTrace(); } return result; } public static void main(String[] args) { HtmlToPdf.convert("https://my.oschina.net/papio/blog/835645", "d:/wkhtmltopdf.pdf"); }}復制代碼

          wkhtmltopdf 參數詳解

          wkhtmltopdf [OPTIONS]... <input file> [More input files] <output file>常規選項 --allow <path> 允許加載從指定的文件夾中的文件或文件(可重復) --book* 設置一會打印一本書的時候,通常設置的選項 --collate 打印多份副本時整理 --cookie <name> <value> 設置一個額外的cookie(可重復) --cookie-jar <path> 讀取和寫入的Cookie,并在提供的cookie jar文件 --copies <number> 復印打印成pdf文件數(默認為1) --cover* <url> 使用HTML文件作為封面。它會帶頁眉和頁腳的TOC之前插入 --custom-header <name> <value> 設置一個附加的HTTP頭(可重復) --debug-javascript 顯示的javascript調試輸出 --default-header* 添加一個缺省的頭部,與頁面的左邊的名稱,頁面數到右邊,例如: --header-left '[webpage]' --header-right '[page]/[toPage]' --header-line --disable-external-links* 禁止生成鏈接到遠程網頁 --disable-internal-links* 禁止使用本地鏈接 --disable-javascript 禁止讓網頁執行JavaScript --disable-pdf-compression* 禁止在PDF對象使用無損壓縮 --disable-smart-shrinking* 禁止使用WebKit的智能戰略收縮,使像素/ DPI比沒有不變 --disallow-local-file-access 禁止允許轉換的本地文件讀取其他本地文件,除非explecitily允許用 --allow --dpi <dpi> 顯式更改DPI(這對基于X11的系統沒有任何影響) --enable-plugins 啟用已安裝的插件(如Flash --encoding <encoding> 設置默認的文字編碼 --extended-help 顯示更廣泛的幫助,詳細介紹了不常見的命令開關 --forms* 打開HTML表單字段轉換為PDF表單域 --grayscale PDF格式將在灰階產生 --help Display help --htmldoc 輸出程序HTML幫助 --ignore-load-errors 忽略claimes加載過程中已經遇到了一個錯誤頁面 --lowquality 產生低品質的PDF/ PS。有用縮小結果文檔的空間 --manpage 輸出程序手冊頁 --margin-bottom <unitreal> 設置頁面下邊距 (default 10mm) --margin-left <unitreal> 將左邊頁邊距 (default 10mm) --margin-right <unitreal> 設置頁面右邊距 (default 10mm) --margin-top <unitreal> 設置頁面上邊距 (default 10mm) --minimum-font-size <int> 最小字體大小 (default 5) --no-background 不打印背景 --orientation <orientation> 設置方向為橫向或縱向 --page-height <unitreal> 頁面高度 (default unit millimeter) --page-offset* <offset> 設置起始頁碼 (default 1) --page-size <size> 設置紙張大小: A4, Letter, etc. --page-width <unitreal> 頁面寬度 (default unit millimeter) --password <password> HTTP驗證密碼 --post <name> <value> Add an additional post field (repeatable) --post-file <name> <path> Post an aditional file (repeatable) --print-media-type* 使用的打印介質類型,而不是屏幕 --proxy <proxy> 使用代理 --quiet Be less verbose --read-args-from-stdin 讀取標準輸入的命令行參數 --readme 輸出程序自述 --redirect-delay <msec> 等待幾毫秒為JS-重定向(default 200) --replace* <name> <value> 替換名稱,值的頁眉和頁腳(可重復) --stop-slow-scripts 停止運行緩慢的JavaScripts --title <text> 生成的PDF文件的標題(第一個文檔的標題使用,如果沒有指定) --toc* 插入的內容的表中的文件的開頭 --use-xserver* 使用X服務器(一些插件和其他的東西沒有X11可能無法正常工作) --user-style-sheet <url> 指定用戶的樣式表,加載在每一頁中 --username <username> HTTP認證的用戶名 --version 輸出版本信息退出 --zoom <float> 使用這個縮放因子 (default 1) 頁眉和頁腳選項--header-center* <text> (設置在中心位置的頁眉內容) --header-font-name* <name> (default Arial) (設置頁眉的字體名稱)--header-font-size* <size> (設置頁眉的字體大小)--header-html* <url> (添加一個HTML頁眉,后面是網址)--header-left* <text> (左對齊的頁眉文本)--header-line* (顯示一條線在頁眉下)--header-right* <text> (右對齊頁眉文本)--header-spacing* <real> (設置頁眉和內容的距離,默認0)--footer-center* <text> (設置在中心位置的頁腳內容) --footer-font-name* <name> (設置頁腳的字體名稱) --footer-font-size* <size> (設置頁腳的字體大小default 11)--footer-html* <url> (添加一個HTML頁腳,后面是網址)--footer-left* <text> (左對齊的頁腳文本)--footer-line* 顯示一條線在頁腳內容上)--footer-right* <text> (右對齊頁腳文本)--footer-spacing* <real> (設置頁腳和內容的距離)./wkhtmltopdf --footer-right '[page]/[topage]' http://www.baidu.com baidu.pdf./wkhtmltopdf --header-center '報表' --header-line --margin-top 2cm --header-line http://192.168.212.139/oma/ oma.pdf表內容選項中 --toc-depth* <level> Set the depth of the toc (default 3) --toc-disable-back-links* Do not link from section header to toc --toc-disable-links* Do not link from toc to sections --toc-font-name* <name> Set the font used for the toc (default Arial) --toc-header-font-name* <name> The font of the toc header (if unset use --toc-font-name) --toc-header-font-size* <size> The font size of the toc header (default 15) --toc-header-text* <text> The header text of the toc (default Table Of Contents) --toc-l1-font-size* <size> Set the font size on level 1 of the toc (default 12) --toc-l1-indentation* <num> Set indentation on level 1 of the toc (default 0) --toc-l2-font-size* <size> Set the font size on level 2 of the toc (default 10) --toc-l2-indentation* <num> Set indentation on level 2 of the toc (default 20) --toc-l3-font-size* <size> Set the font size on level 3 of the toc (default 8) --toc-l3-indentation* <num> Set indentation on level 3 of the toc (default 40) --toc-l4-font-size* <size> Set the font size on level 4 of the toc (default 6) --toc-l4-indentation* <num> Set indentation on level 4 of the toc (default 60) --toc-l5-font-size* <size> Set the font size on level 5 of the toc (default 4) --toc-l5-indentation* <num> Set indentation on level 5 of the toc (default 80) --toc-l6-font-size* <size> Set the font size on level 6 of the toc (default 2) --toc-l6-indentation* <num> Set indentation on level 6 of the toc (default 100) --toc-l7-font-size* <size> Set the font size on level 7 of the toc (default 0) --toc-l7-indentation* <num> Set indentation on level 7 of the toc (default 120) --toc-no-dots* Do not use dots, in the toc輪廓選項 --dump-outline <file> 轉儲目錄到一個文件 --outline 顯示目錄(文章中h1,h2來定) --outline-depth <level> 設置目錄的深度(默認為4)頁腳和頁眉 * [page] 由當前正在打印的頁的數目代替 * [frompage] 由要打印的第一頁的數量取代 * [topage] 由最后一頁要打印的數量取代 * [webpage] 通過正在打印的頁面的URL替換 * [section] 由當前節的名稱替換 * [subsection] 由當前小節的名稱替換 * [date] 由當前日期系統的本地格式取代 * [time] 由當前時間,系統的本地格式取代
          作者:曹元
          鏈接:https://juejin.im/post/6856547881873047559
          來源:掘金
          著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

          TML常用標簽有:a標簽、table標簽、img標簽、form標簽和input標簽。

          a標簽

          作用

          1. 跳轉到外部網頁
          2. 跳轉到內部錨點
          3. 跳轉到郵箱或電話等

          屬性

          (一)href

          href是hyper reference的縮寫,超鏈接的意思。

          用于指定鏈接目標的ur地址,(必須屬性)當為標簽應用href屬性時,它就具有了超鏈接的功能;
          href=“#”表示這是一個空鏈接;
          如果href里面地址是—個文件或者壓縮包,會下載這個文件。

          <a href="https://google.com">超鏈接到google網站的主頁</a>
           <a href="https://google.com">超鏈接到google的主頁</a>
           <a href="//google.com">超鏈接到google的主頁</a>

          展現形式:

          點擊此鏈接,即可到達google的主頁

          a標簽href的取值:

          1、上述代碼中的網址的取值(推薦使用第三行的代碼)

          <a href="//google.com">超鏈接到google的主頁</a>

          由于此方式能夠自動補齊相關的網絡地址,前面兩種寫錯就會報錯,所以推薦使用。

          2、路徑

          • /a/b/c 或者是a/b/c

          當前路徑下的a里面的b,b里面的c

          • index.html 以及./index.html

          在當前目錄下尋找index.html文件

          3、偽協議

          • javascript:代碼;(冒號與分號一定要寫)
          <a href="javascript:;">點擊后無任何點擊或刷新等動作的反應</a>
          • 錨點鏈接
          <a href="#要跳轉的元素的id"></a>

          點擊鏈接的時候,會跳轉到指定元素所在的位置。

          • mailto:郵箱
          <a href="mailto:abcdefg@163.com ">發郵件給我</a>
          • tel:手機號
          <a href="tel:12345678901">打電話給我</a>

          (二)targe

          用于指定鏈接頁面的打開方式

          a的target取值

          1、內置名字

          _blank 在空白頁打開

          _self 在當前頁面打開

          _parent 在父級窗口打開

          _top 在最頂級的窗口打開

          <a href="//google.com" target="_blank">超鏈接到google網站的主頁在空白頁打開</a>

          2、程序員的命名

          window:name(在xxx頁面打開)

          iframe的name(iframe現在已經很少使用了,是指內嵌窗口)


          (三)download

          下載頁面,但目前很少用,有的瀏覽器不支持,尤其是手機瀏覽器可能不支持。

          table標簽

          1、table標簽的語法:

          thead:表頭

          tbody:表的內容,用于定義

          tfoot:表的腳部

          tr:table row,表格里的行

          th:表格的表頭部分,其中的文本內容字體加粗居中顯示

          td:table data,表格數據,用于定義表格中的單元格

          <!DOCTYPE html>
          <html lang="zh-CN">
            <head>
              <meta charset="UTF-8" />
              <meta name="viewport" content="width=device-width, initial-scale=1.0" />
              <meta http-equiv="X-UA-Compatible" content="ie=edge" />
              <title>Document</title>
            </head>
            <body>
              <table>
                <thead>
                  <tr>
                    <th></th>
                    <th>小紅</th>
                    <th>小黃</th>
                    <th>小藍</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <th>數學</th>
                    <td>90</td>
                    <td>60</td>
                    <td>80</td>
                  </tr>
                  <tr>
                    <th>語文</th>
                    <td>88</td>
                    <td>95</td>
                    <td>97</td>
                  </tr>
                  <tr>
                    <th>英語</th>
                    <td>88</td>
                    <td>95</td>
                    <td>97</td>
                  </tr>
                </tbody>
                <tfoot>
                  <tr>
                    <th>總分</th>
                    <td>266</td>
                    <td>250</td>
                    <td>274</td>
                  </tr>
                </tfoot>
              </table>
            </body>
          </html>
          



          第一行的th標簽為空

          2、table的樣式

          table-layout:auto;自動計算每一行的寬高

          table-layout:fixed;通過列表的寬度來決定平均寬度

          border-collapse:collapse; 合并邊框(默認邊框與邊框之間不合并)

          border-spacing:0;邊框為0.(邊框與邊框之間的距離)。

          img標簽(圖片)

          作用:發出get請求,展示一張圖片。

          <img src="1.JPG" alt="頭像" width="400" />

          當前路徑下的1.jpg,確定寬度為400,只寫寬度高度會自適應

          屬性

          alt:alternate的縮寫,替換的意思。替換文本,圖像不能顯示的文字。

          路徑錯誤顯示alt內容

          title:提示文本。鼠標放到圖像上,顯示的文字。

          響應

          max-width:100% 所有的圖片在手機上都自適應寬度,寬度最大為100%。

          事件

          onload/onerror 監聽圖片是否加載成功,加載成功時用onload,不成功是用onerror事件。確保在onerror事件能夠補救。

          <body>
           <img id="xxx" src="dog.jpg" alt="一只小狗">
          <script>
          xxx.onload = function () {
          console.log("圖片加載成功");
           };
          xxx.onerror = function () {
          console.log("圖片加載失敗");
          xxx.src = "/404.jpg";
           };
          </script>
          </body>

          監聽成功時,打印出成功

          監聽失敗時,先打印出監聽失敗并且開始執行加載失敗是的挽救圖片。404.jpg文件執行

          感想:

          • a標簽的默認樣式可以設置清除,href屬性可以有好多種取值,a標簽的意義也不僅僅是跳轉到一個網址,還可以發郵件打電話。
          • 給img標簽設置寬度和高度時,不能讓圖片變形
          • table標簽必須按照thead,tbody,tfoot的結構去寫,先劃分好結構,再往里填充內容,即使tfoot寫在前面,也會顯示在頁面的尾部

          本文為作者本人的原創文章,著作權歸作者本人和饑人谷所有,轉載務必注明來源。

          spose.Words無需Microsoft Word也可在任何平臺上滿足Word文檔的一切操作需求。本文將與大家分享如何將word和圖像轉換為PDF

          將HTML轉換為PDF

          要將HTML轉換為PDF,只需調用Document.Save方法并指定擴展名為“.PDF”即可。如果要從外部源加載圖像和CSS等,可以使用IResourceSavingCallback。下面的代碼示例演示將HTML轉換為PDF并從外部源加載圖像。

          // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
          public class ImageLoadingWithCredentialsHandler : IResourceLoadingCallback
          {
           public ImageLoadingWithCredentialsHandler()
           {
           mWebClient = new WebClient();
           }
           public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
           {
           if (args.ResourceType == ResourceType.Image)
           {
           Uri uri = new Uri(args.Uri);
           if (uri.Host == "www.aspose.com")
           mWebClient.Credentials = new NetworkCredential("User1", "akjdlsfkjs");
           else
           mWebClient.Credentials = new NetworkCredential("SomeOtherUserID", "wiurlnlvs");
           // Download the bytes from the location referenced by the URI.
           byte[] imageBytes = mWebClient.DownloadData(args.Uri);
           args.SetData(imageBytes);
           return ResourceLoadingAction.UserProvided;
           }
           else
           {
           return ResourceLoadingAction.Default;
           }
           }
           private WebClient mWebClient;
          }
          

          在Base64編碼中將字體導出為HTML

          使用Aspose.Words我們可以檢查字體資源是否應該以base 64編碼嵌入到HTML中。默認情況下,該值為false,字體將寫入單獨的文件。如果此選項設置為true,則字體將嵌入到Base64編碼的文檔CSS中。 該屬性僅影響HTML格式,不會影響EPUB和MHTML。這是HtmlSaveOptions.ExportFontResources選項的擴展,ExportFontsAsBase64僅在此屬性設置為true時才有效。下面的示例演示如何使用Base64編碼將字體導出為HTML。

          // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
          // The path to the documents directory.
          string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
          string fileName = "Document.doc";
          Document doc = new Document(dataDir + fileName);
          HtmlSaveOptions saveOptions = new HtmlSaveOptions();
          saveOptions.ExportFontResources = true;
          saveOptions.ExportFontsAsBase64 = true; 
          dataDir = dataDir + "ExportFontsAsBase64_out.html";
          doc.Save(dataDir, saveOptions);
          

          使用HtmlSaveOptions屬性

          使用Aspose.Words,我們可以指定一個文件夾,在將文檔導出為HTML時,可以保存圖像,字體和外部CSS等所有資源。默認值為空字符串。ResourceFolder是指定應寫入所有資源的文件夾的最簡單方法。我們可以使用FontsFolder等單獨的屬性將字體保存到指定的文件夾,使用ImagesFolder將圖像保存到指定的文件夾。

          使用ResourceFolderAlias屬性,我們還可以指定用于構造寫入HTML文檔的所有資源的URI的文件夾的名稱,這是指定應如何構造所有資源文件的URI的最簡單方法。可以通過ImagesFolderAlias和FontsFolderAliasproperties分別為圖像和字體指定相同的信息。 但是,CSS沒有單獨的屬性。 FontsFolder,FontsFolderAlias,ImagesFolder,ImagesFolderAlias和CssStyleSheetFileName屬性的行為不會更改。請注意,CssStyleSheetFileName屬性用于指定文件夾名稱和文件名。

          指定相對路徑時,FontsFolder和ImagesFolder相對于代碼程序集所在的文件夾,ResourceFolder和CssStyleSheetFileName相對于HTML文檔所在的輸出文件夾。在下面的示例中,ResourceFolder指定此路徑相對于輸出文件夾的相對路徑,其中保存HTML文檔,http://example.com/resources 別名用于構造所有資源的URL。

          // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
          // The path to the documents directory.
          string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
          string fileName = "Document.doc";
          Document doc = new Document(dataDir + fileName);
          HtmlSaveOptions saveOptions = new HtmlSaveOptions();
          saveOptions.CssStyleSheetType = CssStyleSheetType.External;
          saveOptions.ExportFontResources = true;
          saveOptions.ResourceFolder = dataDir + @"\Resources";
          saveOptions.ResourceFolderAlias = "http://example.com/resources";
          doc.Save(dataDir + "ExportResourcesUsingHtmlSaveOptions.html", saveOptions);
          

          如何將文檔轉換為MHTML和電子郵件

          Aspose.Words可以以MHTML(Web Archive)格式保存任何文檔。這使得Aspose.Words和Aspose.Email一起使用可以生成和發送內容豐富的電子郵件。例如,你可以將預定義的DOC,OOXML或RTF文檔加載到Aspose.Words中,用數據填充之后另存為MHTML,然后使用Aspose.Email發送電子郵件。 下面的代碼示例演示了如何使用Aspose.Email將Aspose.Words中的文檔保存為MHTML和電子郵件。

          // For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
          // The path to the documents directory.
          string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
          // Load the document into Aspose.Words.
          Document doc = new Document(dataDir + "Test File (docx).docx");
          // Save into a memory stream in MHTML format.
          Stream stream = new MemoryStream();
          doc.Save(stream, SaveFormat.Mhtml);
          // Rewind the stream to the beginning so Aspose.Email can read it.
          stream.Position = 0;
          // Create an Aspose.Network MIME email message from the stream.
          MailMessage message = MailMessage.Load(stream, new MhtmlLoadOptions());
          message.From = "your_from@email.com";
          message.To = "your_to@email.com";
          message.Subject = "Aspose.Words + Aspose.Email MHTML Test Message";
          // Send the message using Aspose.Email
          SmtpClient client = new SmtpClient();
          client.Host = "your_smtp.com";
          client.Send(message);
          

          點擊“了解更多”下載產品最新版

          ↓↓↓


          主站蜘蛛池模板: 欧美日韩国产免费一区二区三区| 国产中的精品一区的| 精品成人av一区二区三区| 99久久精品费精品国产一区二区| 无码人妻一区二区三区免费n鬼沢| 精品国产免费一区二区| 亚洲码一区二区三区| 精品视频一区二区三区免费| 中文字幕在线一区| 久久亚洲综合色一区二区三区| 夜色阁亚洲一区二区三区| 无码人妻一区二区三区在线水卜樱 | 亚洲人成人一区二区三区| 国产视频一区在线观看| 亚洲AV色香蕉一区二区| 国产福利微拍精品一区二区| 国产福利91精品一区二区三区 | 国产一区在线mmai| 亚洲男女一区二区三区| 内射一区二区精品视频在线观看| 精品国产AV无码一区二区三区 | 欧洲精品一区二区三区在线观看| 一区二区不卡视频在线观看| 国产一区二区高清在线播放| 国产乱码一区二区三区| 国产成人免费一区二区三区| 日韩精品电影一区亚洲| 国产无线乱码一区二三区| 亚洲欧美国产国产综合一区| 99精品国产一区二区三区不卡 | 久久亚洲日韩精品一区二区三区| 精品国产一区二区三区无码| 一区二区不卡久久精品| 亚洲电影国产一区| 国产在线一区观看| 亚洲一区二区三区电影| 国产福利电影一区二区三区,免费久久久久久久精 | 一本一道波多野结衣AV一区 | 2021国产精品视频一区| 狠狠色成人一区二区三区| 精品无码国产一区二区三区51安|