轉 Html轉pdf的工具——wkhtmltopdf


下載地址:http://wkhtmltopdf.org/downloads.html

安裝好以后需要在系統環境變量變量名為”Path”的后添加:;D:\wkhtmltopdf\bin 也就是你安裝的目錄。安裝好以后重啟電腦。

測試使用效果
直接在cmd里輸入:wkhtmltopdf http://www.baidu.com/ D:website1.pdf

臨時文件在哪兒,你的css就得在哪兒,或者你直接使用相對路徑,引用其他文件中的css樣式也可以的,最簡單的就是把css樣式直接寫在要轉成pdf的html頁面中。如果存在樣式沒有,那就是你的樣式路徑沒有寫對,在檢查一下就可以了!

解決分頁問題
wkhtmltopdf 很好用,但也有些不盡人意。就是當一個html頁面很長我需要在指定的地方分頁那怎么辦呢? wkhtmltopdf 開發者在開發的時候並不是沒有考慮到這一點,
wkhtmltopdf 有個很好的方法,就是在那個div的樣式后添加一個:page-break-inside:avoid;就ok了。
例如

div{ width:800px; min-height:1362px;margin:auto;page-break-inside:avoid;}

注:html的table中不能用thead,用了后換頁會出現兩個表頭
解決中文亂碼問題

將 windows下的字體,例如 c:\WINDOWS\Fonts\simsun.TTF,或者msyh.TTF,或者msyhbd.TTF復制到 Linux系統 /usr/share/fonts 下即可。記住要將擴展名改為了.TTC
例如:將Windows下的字體文件 c:\WINDOWS\Fonts\simsun.ttf,Copy到 /usr/share/fonts/SIMSUN.TTC下

PHP環境中,采用系統調用命令 :

exec("wkhtmltopdf 'http://www.hywtest.com/xt/bill/MTIzNDU2Nzg5' '/data/users/MTIzNDU2Nzg5/downloadfile//20170607043855515.pdf'");

Java中調用:

Runtime.getRuntime().exec("wkhtmltopdf 'http://www.hywtest.com/xt/bill/MTIzNDU2Nzg5' '/data/users/MTIzNDU2Nzg5/downloadfile//20170607043855515.pdf'");

附錄:中文參數詳解

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

 

 

wkhtmltopdf 包含兩個工具:wkhtmltopdf 和 wkhtmltoimage 。

輸入一個 URL 地址,自動將網頁保存成一個 PDF 文檔或者是一個圖片。

命令:

D:\Tools\wkhtmltopdf>wkhtmltoimage http://www.oschina.net/ oschina.jpg

 

PDF時間戳數字簽名

由時間戳服務中心(TSA:Time Stamp Authority)頒發的具有法律效力的電子憑證, 時間戳與電子數據唯一對應,其中包含電子數據 “指紋”、產生時間、時間戳服務中心信息等。

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.*;
import java.security.MessageDigest;
import java.security.SignatureException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.HashMap;

/**
 * Created by zhangzhenhua on 2016/11/1.
 */
public class PDFSigner {

    //tsa

    private SignerKeystore signerKeystore;
    private TSAClient tsaClient;

    private PDFSigner(){}

    /**
     *
     * @param tsa_url   tsa服務器地址
     * @param tsa_accnt tsa賬戶號
     * @param tsa_passw tsa密碼
     * @param cert_path 證書路徑
     * @param cert_passw    證書密碼
     */
    public PDFSigner(String tsa_url,String tsa_accnt,String tsa_passw,String cert_path,String cert_passw)  {

        tsaClient = new TSAClientBouncyCastle(tsa_url, tsa_accnt, tsa_passw);
        try {
            signerKeystore =  new SignerKeystorePKCS12(new FileInputStream(cert_path), cert_passw);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * TSA時間戳簽名
     * @param infilePath    未簽名的文件路徑
     * @param outfilePath   簽名后的文件路徑
     * @throws Exception
     */
    public void signPDF(String infilePath,String outfilePath) throws Exception {
        PdfReader reader = new PdfReader(infilePath);
        FileOutputStream fout = new FileOutputStream(outfilePath);
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stp.getSignatureAppearance();

        sap.setCrypto(null,  this.signerKeystore.getChain(), null, PdfSignatureAppearance.SELF_SIGNED);

        sap.setVisibleSignature(new Rectangle(100, 100, 300, 200), 1, "Signature");

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);

        int contentEstimated = 15000;
        HashMap exc = new HashMap();
        exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(this.signerKeystore.getPrivateKey(),  this.signerKeystore.getChain(), null, "SHA1", null, false);
        InputStream data = sap.getRangeStream();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        byte buf[] = new byte[8192];
        int n;
        while ((n = data.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        Calendar cal = Calendar.getInstance();
        byte[] ocsp = null;
        if ( this.signerKeystore.getChain().length >= 2) {
            String url = PdfPKCS7.getOCSPURL((X509Certificate) this.signerKeystore.getChain()[0]);
            if (url != null && url.length() > 0)
                ocsp = new OcspClientBouncyCastle((X509Certificate) this.signerKeystore.getChain()[0], (X509Certificate) this.signerKeystore.getChain()[1], url).getEncoded();
        }
        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
        sgn.update(sh, 0, sh.length);

        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, this.tsaClient, ocsp);

        if (contentEstimated + 2 < encodedSig.length)
            throw new Exception("Not enough space");

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        sap.close(dic2);
    }


    public static void main(String[] args) {

        //test
        String TSA_URL    = "http://tsa.safelayer.com:8093";
        String TSA_ACCNT  = "";
        String TSA_PASSW  = "";
        String IN_FILE = "E:\\項目\\paperless\\lipsum.pdf";
        String OUT_FILE = "E:\\項目\\paperless\\test_signed.pdf";

        String CERT_PATH  = "E:\\項目\\paperless\\bfnsh.pfx";

        String CERT_PASSW = "123456";
        PDFSigner signer = new PDFSigner(TSA_URL,TSA_ACCNT,TSA_PASSW,CERT_PATH,CERT_PASSW);
        try {
            signer.signPDF(IN_FILE,OUT_FILE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

  

import java.security.PrivateKey;
import java.security.Provider;
import java.security.cert.Certificate;

/**
 * Created by zhangzhenhua on 2016/10/28.
 */
public interface SignerKeystore {

    public PrivateKey getPrivateKey() ;

    public Certificate[] getChain() ;

    public Provider getProvider();

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17



/**
 * Created by hmt on 2016/10/28.
 */

import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.cert.Certificate;

/**

 * SignerKeystore implementation using PKCS#12 file (.pfx etc)

 */

public class SignerKeystorePKCS12 implements SignerKeystore {

    private static Provider prov = null;

    private KeyStore ks;

    private String alias;

    private String pwd;



    private PrivateKey key;

    private Certificate[] chain;



    public SignerKeystorePKCS12(InputStream inp, String passw) throws Exception {

        // This should be done once only for the provider...

        if (prov == null) {

            prov = new org.bouncycastle.jce.provider.BouncyCastleProvider();

            Security.addProvider(prov);

        }



        this.ks = KeyStore.getInstance("pkcs12", prov);

        this.pwd = passw;

        this.ks.load(inp, pwd.toCharArray());

        this.alias = (String)ks.aliases().nextElement();

        this.key   = (PrivateKey)ks.getKey(alias, pwd.toCharArray());

        this.chain = ks.getCertificateChain(alias);

    }



    public PrivateKey getPrivateKey() {

        return key;

    }



    public Certificate[] getChain() {

        return chain;

    }



    public Provider getProvider() {

        return ks.getProvider();

    }

}

  

PDF蓋騎縫章

把章按頁數切割成等份的圖片,合並在一起

 

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 蓋騎縫章
 * Created by zhangzhenhua on 2016/11/2.
 */
public class PDFStamperCheckMark {

    /**
     * 切割圖片
     * @param imgPath  原始圖片路徑
     * @param n 切割份數
     * @return  itextPdf的Image[]
     * @throws IOException
     * @throws BadElementException
     */
    public static Image[] subImages(String imgPath,int n) throws IOException, BadElementException {
        Image[] nImage = new Image[n];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedImage img = ImageIO.read(new File(imgPath));
        int h = img.getHeight();
        int w = img.getWidth();

        int sw = w/n;
        for(int i=0;i<n;i++){
            BufferedImage subImg;
            if(i==n-1){//最后剩余部分
                 subImg = img.getSubimage(i * sw, 0, w-i*sw, h);
            }else {//前n-1塊均勻切
                 subImg = img.getSubimage(i * sw, 0, sw, h);
            }

            ImageIO.write(subImg,imgPath.substring(imgPath.lastIndexOf('.')+1),out);
            nImage[i] = Image.getInstance(out.toByteArray());
            out.flush();
            out.reset();
        }
        return nImage;
    }

    /**
     *  蓋騎縫章
     *
     * @param infilePath    原PDF路徑
     * @param outFilePath    輸出PDF路徑
     * @param picPath    章圖片路徑
     * @throws IOException
     * @throws DocumentException
     */
    public static void stamperCheckMarkPDF(String infilePath,String outFilePath,String picPath) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(infilePath);//選擇需要印章的pdf
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outFilePath));//加完印章后的pdf

        Rectangle pageSize = reader.getPageSize(1);//獲得第一頁
        float height = pageSize.getHeight();
        float width  = pageSize.getWidth();

        int nums = reader.getNumberOfPages();
        Image[] nImage =  subImages(picPath,nums);//生成騎縫章切割圖片


        for(int n=1;n<=nums;n++){
            PdfContentByte over = stamp.getOverContent(n);//設置在第幾頁打印印章
            Image img = nImage[n-1];//選擇圖片
//            img.setAlignment(1);
//            img.scaleAbsolute(200,200);//控制圖片大小
            img.setAbsolutePosition(width-img.getWidth(),height/2-img.getHeight()/2);//控制圖片位置
            over.addImage(img);
        }
        stamp.close();
    }



    public static void main(String[] args) throws IOException, DocumentException {
        String infilePath = "E:\\項目\\paperless\\page.pdf";
        String outfilePaht = "E:\\項目\\paperless\\page_pic.pdf";
        String picPath = "E:\\項目\\paperless\\公章.png";
        stamperCheckMarkPDF(infilePath,outfilePaht,picPath);
    }
}

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM