Tools for turning HTML to PDF--wkhtmltopdf

Source: Internet
Author: User
Tags html form html header http authentication sha1 wkhtmltopdf

: http://wkhtmltopdf.org/downloads.html

After installation, you need to add after the system environment variable variable named "Path":;D: \wkhtmltopdf\bin is the directory you installed. Reboot the computer after installation.

Test use effect
Input directly in cmd: Wkhtmltopdf http://www.baidu.com/D:website1.pdf

Where the temp file is, where your CSS will be, or you can directly use a relative path, referencing a CSS style from another file, the simplest is to write the CSS style directly in the HTML page that you want to convert to PDF. If there is no style, it is your style path is not written right, check it!

Troubleshoot paging problems
Wkhtmltopdf is very useful, but it is also somewhat unsatisfactory. is when an HTML page is a long I need to be paged in the specified place. Wkhtmltopdf developers did not take this into account at the time of development,
Wkhtmltopdf a good way to do that is to add one after that Div's style: page-break-inside:avoid; it's OK.
For example

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

Note: The HTML table cannot be used with THEAD, two headers appear after a page break
solve Chinese garbled problems

Place the fonts under WINDOWS, such as C:\WINDOWS\Fonts\simsun. TTF, or Msyh. TTF, or MSYHBD. TTF is copied to the Linux system/usr/share/fonts. Remember to change the extension to. Ttc
For example, c:\windows\fonts\simsun.ttf,copy a font file under WINDOWS to/usr/share/fonts/simsun. TTC under

In a PHP environment, the system invoke command is used:

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

Called in Java:

Runtime. GetRuntime (). EXEC ("Wkhtmltopdf ' Http://www.hywtest.com/xt/bill/MTIzNDU2Nzg5"/data/users/ Mtizndu2nzg5/downloadfile//20170607043855515.pdf ' ");

Appendix: Chinese Parameter explanation

linux:wkhtmltopdf [OPTIONS] ... [More input files]
Windows:wkhtmltopdf.exe [OPTIONS] ... [More input files]
General Options
–allow allows you to load files or files from a specified folder (repeatable)
–book* set the options that are typically set when you print a book
–collate when printing multiple copies
–cookie setting an extra cookie (repeatable)
–cookie-jar Read and write the cookie, and in the cookie jar file provided
–copies copy Printed as PDF file (default = 1)
–cover* uses HTML files as cover pages. It will be inserted before the TOC with headers and footers
–custom-header setting an additional HTTP header (repeatable)
–debug-javascript display of JavaScript debug output
–default-header* adds a default header, with the name of the left side of the page, the number of pages to the right, for example: –header-left ' [webpage] ' –header-right ' [Page]/[topage] ' – Header-line
–disable-external-links* prohibit build link to remote Web page
–disable-internal-links* prohibit use of local links
–disable-javascript disable JavaScript for Web page execution
–disable-pdf-compression* prohibit lossless compression on PDF objects
–disable-smart-shrinking* prohibit the use of WebKit's smart strategy contraction, so that the pixel/DPI ratio does not change
–disallow-local-file-access Disallow local files that are converted to be read by other local files unless explecitily allows –allow
–dpi explicitly changing dpi (this has no effect on X11-based systems)
–enable-plugins enable installed plugins (such as Flash
–encoding Setting the default text encoding
–EXTENDED-HELP displays a wider range of help, detailing unusual command switches
–forms* opening an HTML form field to PDF form fields
–grayscale PDF format will be generated in gray scale
Help Display Help
–htmldoc Output Program HTML Help
–ignore-load-errors Ignore claimes The loading process has encountered an error page
–lowquality produces low-quality pdf/ps. Useful space to narrow the resulting document
–manpage Output Program manual page
–margin-bottom setting the bottom margin of the page (default 10mm)
–margin-left the left margin (default 10mm)
–margin-right Set page right margin (default 10mm)
–margin-top Setting page top margin (default 10mm)
–minimum-font-size Minimum font size (default 5)
–no-background not print background
–orientation setting orientation to Landscape or portrait
–page-height page height (default unit millimeter)
–page-offset* Set Start page (default 1)
–page-size Set the paper size: A4, letter, etc.
–page-width page width (default unit millimeter)
–password HTTP Authentication Password
–post Add an additional post field (repeatable)
–post-file post an aditional file (repeatable)
–print-media-type* the type of print media used, not the screen
–proxy using proxies
–quiet is less verbose
–read-args-from-stdin to read command-line arguments for standard input
–readme Output Program Readme
–redirect-delay Wait a few milliseconds for js-redirection (default 200)
–replace* Replace name, value of header and footer (repeatable)
–stop-slow-scripts stop slow-running javascripts
–title the title of the generated PDF file (the title of the first document is used, if not specified)
–toc* the beginning of the file in the inserted content table
–use-xserver* using X server (some plugins and other things without X11 may not work properly)
–user-style-sheet the style sheet for the specified user, loaded on each page
–username user name for HTTP authentication
–version Output Version Information exit
–zoom using this scaling factor (default 1)
Header and Footer options
–header-center* (Sets the header content in the central location)
–header-font-name* (default Arial) (sets the font name for the header)
–header-font-size* (Sets the font size of the header)
–header-html* (add an HTML header, followed by a URL)
–header-left* (left-aligned header text)
–header-line* (show a line under the header)
–header-right* (right-aligned header text)
–header-spacing* (set the distance between header and content, default 0)
–footer-center* (Sets the footer content in the central location)
–footer-font-name* (Sets the font name for the footer)
–footer-font-size* (Sets the font size of the footer default 11)
–footer-html* (add an HTML footer, followed by a URL)
–footer-left* (left-aligned footer text)
–footer-line* display a line on the footer content)
–footer-right* (right-justified footer text)
–footer-spacing* (sets the distance between footer and content)
./wkhtmltopdf–footer-right ' [page]/[topage] ' http://www.baidu.com baidu.pdf
./wkhtmltopdf–header-center ' reports ' –header-line–margin-top 2cm–header-line http://192.168.212.139/oma/oma.pdf
In table content options
–toc-depth* Set The depth of the TOC (default 3)
–toc-disable-back-links* do not link from the header to TOC
–toc-disable-links* don't 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* don't use dots, in the TOC
Outline Options
–dump-outline Dump directory to a file
–outline Display directory (H1,H2 in the article)
–outline-depth setting the depth of the directory (default is 4)
Footer and Header
* [Page] is replaced by the number of pages currently being printed
* [FromPage] Replaced by the number of first pages to be printed
* [ToPage] replaced by the number to be printed on the last page
* [webpage] is replaced by the URL of the page being printed
* [section] is replaced by the name of the current stanza
* [subsection] is replaced by the name of the current section
* [Date] is replaced by the local format of the current date system
* [TIME] is replaced by the local format of the system
./wkhtmltopdf–footer-right ' [page]/[topage] ' http://www.baidu.com baidu.pdf
./wkhtmltopdf–header-center ' reports ' –outline–header-line–margin-top 2cm–header-line http://www.hao123.com/hao123.pdf
./wkhtmltopdf–header-left ' [webpage] ' –footer-center ' Test ([page]/[topage]) ' http://www.baidu.com baidu.pdf

Wkhtmltopdf consists of two tools: Wkhtmltopdf and Wkhtmltoimage.

Enter a URL address to automatically save the page as a PDF document or as a picture.

Command:

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

PDF Timestamp Digital signature

The

Tsa:time Stamp Authority, which is issued by the Timestamp service center, has a legally valid electronic voucher that uniquely corresponds to the electronic data, which contains the electronic data "fingerprint", the time of generation, the timestamp service center information, and so on.

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 server address * @param tsa_accnt TSA Account number * @param TSA_PASSW ts A password * @param cert_path certificate path * @param CERT_PASSW Certificate Password */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 timestamp signature * @param infilepath unsigned file path * @param outfilepath signed file path * @throws Excepti On */public void signpdf (String infilepath,string outfilepath) throws Exception {Pdfreader reader = new Pd        Freader (Infilepath);        FileOutputStream fout = new FileOutputStream (Outfilepath);        Pdfstamper stp = pdfstamper.createsignature (reader, Fout, ' + ');        Pdfsignatureappearance SAP = Stp.getsignatureappearance ();        Sap.setcrypto (NULL, This.signerKeystore.getChain (), NULL, pdfsignatureappearance.self_signed);        Sap.setvisiblesignature (New Rectangle (1, N, a), 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.S            Ignerkeystore.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:\\ project \\paperless\\lipsum.pdf"; String out_file = "e:\\ Project \\paperless\\test_siGned.pdf ";        String Cert_path = "e:\\ project \\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 ();} 1234567891011121314151617/** * 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 St    atic 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 is done once- 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 Cover Straddle Chapter

A picture of a chapter cut into equal parts by the number of pages, merged together

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.*;/** * Cover Straddle Chapter * Created by Zhangzhenhua on 2016/11/2. */public class Pdfstampercheckmark {/** * cut picture * @param imgpath Original image path * @param n number of cut copies * @return ite  Xtpdf 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) {//last remainder subimg = img.getsubimage (i * SW, 0, W-I*SW, h);            }else {//front n-1 block evenly cut 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; }/** * Cover straddle * * @param infilepath PDF Path * @param outfilepath output PDF Path * @param picpath Chapter Picture path * @throws IOException * @throws documentexception */public static void Stampercheckmarkpdf (String inf Ilepath,string outfilepath,string Picpath) throws IOException, documentexception {pdfreader reader = new PdfReader        (Infilepath)///select PDF Pdfstamper stamp = new Pdfstamper (reader, New FileOutputStream (Outfilepath));//PDF After the seal is added        Rectangle pageSize = reader.getpagesize (1);//Get First pagefloat height = pagesize.getheight ();        Float width = pagesize.getwidth ();        int nums = Reader.getnumberofpages ();  image[] NImage = subimages (picpath,nums);//Generate straddle Chapter cut picture for (int n=1;n<=nums;n++) {Pdfcontentbyte over =            Stamp.getovercontent (n);//Set on the first page print stamp image img = nimage[n-1];//Select picture//Img.setalignment (1);// Img.scaleabsolute (200,200);//Control picture size img.setabsoluteposition (Width-img.getwidth (), height/2-img.getheight ()/        2);//Control Picture Position Over.addimage (IMG);    } stamp.close (); } public static void Main (string[] args) throws IOException, documentexception {String Infilepath = "e:\\ Project \\pa        Perless\\page.pdf ";        String outfilepaht = "e:\\ project \\paperless\\page_pic.pdf";        String Picpath = "e:\\ Project \\paperless\\ official seal. PNG";    Stampercheckmarkpdf (Infilepath,outfilepaht,picpath); }}

  

Tools for turning HTML to PDF--wkhtmltopdf

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.