wkhtmltox 使用 和 freemaker 靜態頁面部分功能

來源:互聯網
上載者:User

標籤:

真正關注部落格園的時間不算長,參加工作的時間也很短,僅作為筆記記錄工作,便於自己對技術的積累和鞏固,有不對的地方大家直接抨擊點評.

在工作中,遇到了這樣的一個問題,原型展示的是下載功能,其實背景程式的處理過程是這樣的; 將要下載下來的內容從html 轉換成pdf 我使用了wkhtmltox 它; 再用流把轉換好的pdf 下載下來; 首先說下 html 是通過freemaker 靜態化來產生的 這中間就設計到了 ftl模板的載入,和 freemaker頁面標籤的使用;

一 ,首先載入 模板所在位置; 自己在resources下建立了 pageTemplate包這個包下放所有的靜態模板ftl, 這個目錄下的所有東西都會編譯到classes檔案下,所以我們需要手動的去擷取項目的絕對路徑 通過這個方法擷取項目目錄

new DefaultResourceLoader().getResource("").getFile().getAbsolutePath();

返回結果類似如下這個結構    D:\project\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ost.web\WEB-INF\classes

在通過手動拼裝到 pageTemplate 和 模板名稱 需要設定的內容裝到map裡面 (具體代碼略過,有需要的聯絡); 

通過設定檔 配置 產生路徑 Global.getConfig("generate.certificatePath"); 這個方法會將設定檔中的html 產生位置傳遞進來;

二,Ftl 中使用到的簡單標籤取值

1,對象中的屬性和 c 標籤一致 通過${對象.屬性} or ${對象.對象.屬性}

2, list 的取值遍曆  : <#list orderDetail.products as prod>切記不能少這個閉合標籤</#list>  List裡面還有list需要繼續

3, 同時 還有if 的判斷 : 

性 別:

   <#if sex=="F">

       女

   <#elseif sex=="M">

       男

   <#else>

       其他

   </#if>

   <br/>

    

   成 績:${score}分<br/>

    

   級 別:

   <#if (score >= 90) > <#-- 此處不加括弧,則系統認為 “score >” 將scroe作為了條件 -->

       非常優秀

   <#elseif (score >= 80 && score < 90)>

       優秀

   <#elseif (score >= 70 && score < 80)>

       良好

   <#elseif (score >= 60 && score < 70)>

       一般

   <#else>

       差勁

   </#if>

   <br/>

三,接下來 wkhtmltox 的使用了

1, http://wkhtmltopdf.org/ 下載應用,解壓,安裝

2,現今大多項目是部署在 linux 上的 wkhtmltox 很好的做到了這一點同樣相容 win 和linux

3,使用 參數1, htmlpath (html產生路徑); 參數2, pafPath (轉成pdf儲存路徑)當然html不使用freemarker 同樣可以使用;

4,同樣在java程式中需要將 wkhtmltopdf 直接放入自己的項目中的classes適應不同的服務;

5,調用的是 他的可執行檔;

6,需要手動的添加介面方法 ;

public class HtmlToPdf {

   

    // wkhtmltopdf在系統中的路徑

    private static String toPdfTool = "";

   

    public static String getWkPath() {

        toPdfTool = "";

        if(ConverterUtil.isEmpty(toPdfTool)){

            try {

                toPdfTool += SpringContextHolder.getApplicationContext().getResource("/WEB-INF/classes/wkhtmltox/bin").getFile().getAbsolutePath();

            } catch (IOException e) {

                e.printStackTrace();

            }

            toPdfTool += (File.separator + "wkhtmltopdf");

            if (!SystemPath.isLinuxOS()) {

                toPdfTool += ".exe";

            }

        }

        return toPdfTool;

    }

   

    /**

     * html轉pdf

     *

     * @param htmlPath html路徑,可以是硬碟上的路徑,也可以是網路路徑

     * @param pafPath pdf儲存路徑

     * @return 轉換成功返回true

     *

     */

    public static boolean convert(String htmlPath,String pafPath){

        File file = new File(pafPath);

        File parent = file.getParentFile();

        // 如果pdf儲存路徑不存在則建立路徑

        if(!parent.exists()){

            parent.mkdirs();

        }

       

        StringBuilder cmd = new StringBuilder();

        cmd.append(getWkPath());

        cmd.append(" ");

        cmd.append("--page-size A4");// 參數

        cmd.append(" ");

        cmd.append(htmlPath);

        cmd.append(" ");

        cmd.append(pafPath);

       

        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;

       

    }

}

 

介面方法

* 當調用wkhtmltopdf時,用於擷取wkhtmltopdf返回的內容

 *

 */

 

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();

        } 

    }

 

}

四, Linux下 wkhtmltox 的使用存在問題

1,轉換出來的pdf中文可能會顯示方塊,需要將linux 下安裝中文字型;

linux命令=>   yum install fonts-chinese.noarch及緩衝 fc-cache-fv

2,同時wkhtmltox 是每次部署的許可權也會存在問題;

linux命令=>  

用#ls   -l   wkhtmltox命令看看,如果顯示類似如: 
-rw-rw-rw-     1   root   root     .... 
則表示任何使用者都沒有可執行許可權(即使是root使用者).

 

解決方案: 
#chmod   a+x   wkhtmltox 

PS:用字串來設定檔案存取權限。其中讀用 r 表示,寫用 w 表示,執行用 x 表示;所有者用 u 表示,組使用者用 g 表示,其他使用者用 o 表示,所有使用者用 a 表示。例子:
chmod a+r,u+w,u+x,g+w a.txt

wkhtmltox 使用 和 freemaker 靜態頁面部分功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.