Html turn turn pdf tools --wkhtmltopdf

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

After installing the required system environment variables in the variable named "Path" adding:; D: \ wkhtmltopdf \ bin is your installation directory. Installed after the restart the computer.

Use test results
Directly in the cmd, enter: wkhtmltopdf D:website1.pdf

Where temporary files, where you have to css, or you just use relative paths, references css styles in other documents may also be the easiest it is to write directly css styles to turn into a pdf of html page. If there is no style, that is your style path did not write right, check in on it!

To solve the paging problem
wkhtmltopdf good use, but also some less than satisfactory. That is, when a html page pagination how long I need to do it in that specific place? wkhtmltopdf developers during development is not without this in mind,
wkhtmltopdf there is a good way is to add a div after the style: page-break-inside: avoid; ok.
E.g

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

NOTE: table html can not be used in thead, two feed header appears after use
Solve the problem of Chinese garbled

The font under windows, such as c: \ WINDOWS \ Fonts \ simsun.TTF, or msyh.TTF, or msyhbd.TTF copied to the Linux system / usr / under share / fonts can be. Remember to change the extension .TTC
For example: the font file c under Windows: \ WINDOWS \ Fonts \ simsun.ttf, Copy next to /usr/share/fonts/SIMSUN.TTC

PHP environment, the use of system calls:

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

Java call:

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

Appendix: Parameter Description Chinese

linux:wkhtmltopdf [OPTIONS]… [More input files]
windows:wkhtmltopdf.exe [OPTIONS]… [More input files]
General Options
-allow allow loading from the specified folder or file in the file (repeat)
-book * Set a print a book, options are usually set
Finishing When printing multiple copies -collate
-cookie set up an extra cookie (repeatable)
-cookie-jar reads and writes Cookie, and provide the cookie jar file
-copies number of copies printed as pdf file (default is 1)
-cover * use HTML file as the cover. TOC it will take before inserting headers and footers
-custom-header provided an additional HTTP header (repeat)
-debug-javascript javascript debugging output display
-default-header * add a default header, the left of the page with the name, number of pages to the right, for example: -header-left '[webpage]' -header-right '[page] / [toPage]' - header-line
-disable-external-links * prohibited to create a link to a remote web page
-disable-internal-links * prohibit the use of a local link
-disable-javascript page prohibits the implementation of JavaScript
-disable-pdf-compression * prohibit the use of lossless compression in PDF object
-disable-smart-shrinking * prohibit the use of smart strategic contraction of WebKit, the pixel / DPI ratio is not constant
-disallow-local-file-access ban to allow local file conversion read other local files unless explecitily allows -allow
-dpi explicitly change the DPI (This has no effect on the system based on the X11)
-enable-plugins enable installed plug-ins (like Flash
-encoding set the default text encoding
-extended-help show more extensive help, detailing the unusual command switch
-forms * Open the HTML form fields into PDF form fields
-grayscale PDF format will result in gray scale
–help Display help
-htmldoc output HTML Help program
-ignore-load-errors ignored claimes the loading process has encountered an error page
-lowquality produce low-quality PDF / PS. Space useful to narrow down the results document
-manpage output program manual page
Under -margin-bottom margin settings page (default 10mm)
-margin-left to left margin (default 10mm)
-margin-right Sets the right page margin (default 10mm)
-margin-top margin on the Settings page (default 10mm)
-minimum-font-size minimum font size (default 5)
-no-background does not print background
-orientation portrait or landscape orientation is provided
-page-height page height (default unit millimeter)
-page-offset * set the starting page number (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 * print media type used, instead of the screen
-proxy use a proxy
–quiet Be less verbose
-read-args-from-stdin standard input read command line arguments
-readme output README
-redirect-delay wait a few milliseconds JS- redirection (default 200)
Alternatively -replace * name, header and footer values ​​(repeat)
-stop-slow-scripts stop running slow JavaScripts
-title title generated PDF file (the title of the first document to use, if not specified)
Beginning -toc * file table of contents is inserted in
-use-xserver * use the X server (some plug-ins and other things not X11 may not work correctly)
-user-style-sheet specified user style sheet loaded on every page
-username HTTP authentication username
-version output version information Exit
-zoom using that scale (default 1)
Header and footer options
-header-center * (disposed at the center position of the header content)
-header-font-name * (default Arial) (set the header font name)
-header-font-size * (Set the header font size)
-header-html * (add an HTML header, followed by a URL)
-header-left * (left-aligned text in the header)
-header-line * (display line in the header)
-header-right * (right-aligned header text)
-header-spacing * (provided from the header and content, default 0)
-footer-center * (set at the center position of the footer content)
-footer-font-name * (Set footer font name)
-footer-font-size * (Set footer font size default 11)
-footer-html * (add an HTML footer, followed by a URL)
-footer-left * (left-aligned footer text)
-footer-line * displayed on a line footer)
-footer-right * (right-aligned footer text)
-footer-spacing * (set distance footer and content)
./wkhtmltopdf –footer-right ‘[page]/[topage]’ baidu.pdf
./wkhtmltopdf -header-center 'Report' -header-line -margin-top 2cm -header-linehttp://192.168.212.139/oma/ oma.pdf
Table of contents options
–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
Outline options
-dump-outline dump directory to a file
-outline show catalog (article h1, h2 to set)
-outline-depth setting depth directory (default 4)
Headers and Footers
* [Page] replaced by the current number of pages being printed
* [Frompage] replaced by a first number of pages to be printed
* [Topage] substituted by the number of the last page to be printed
* [Webpage] by replacing the URL of the page being printed
* [Section] replaced by the name of the current section
* [Subsection] replaced by the name of the current measure
* [Date] is replaced by the native format of the current system date
* [Time], is replaced by the current time of the local system format
./wkhtmltopdf –footer-right ‘[page]/[topage]’ baidu.pdf
./wkhtmltopdf -header-center 'Report' -outline -header-line -margin-top 2cm -header-linehttp://www.hao123.com/ hao123.pdf
./wkhtmltopdf -header-left '[webpage]' -footer-center 'test ([page] / [toPage])' baidu.pdf

 

 

wkhtmltopdf contains two tools: wkhtmltopdf and wkhtmltoimage.

Enter a URL address, automatically save the page into a PDF document or a picture.

command:

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

 

PDF digital signature timestamp

By the time stamp authority: issued (TSA Time Stamp Authority) electronic documents legally binding, timestamp and unique to electronic data, which includes electronic data "fingerprint" generated time stamp authority information.

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 tsa password
           * @Param cert_path certification 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 time stamp signature
           * @Param infilePath unsigned file path
           * @Param outfilePath file path after the signature
     * @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: \\ projects \\ paperless \\ lipsum.pdf";
                 String OUT_FILE = "E: \\ projects \\ paperless \\ test_signed.pdf";

                 String CERT_PATH = "E: \\ projects \\ 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 cover Jifeng

The chapter number of pages cut into equal parts of the picture, combined

 

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 Jifeng
 * Created by zhangzhenhua on 2016/11/2.
 */
public class PDFStamperCheckMark {

    /**
           * Cutting Pictures
           * @Param imgPath original image path
           * @Param n cutting the number of copies
           * @Return itextPdf of 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) {// the last remaining portion
                 subImg = img.getSubimage(i * sw, 0, w-i*sw, h);
                         } Else {// n-1 before the cutting block uniform
                 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 Jifeng
     *
           * @Param infilePath original PDF path
           * @Param outFilePath PDF output path
           * @Param picPath chapter image path
     * @throws IOException
     * @throws DocumentException
     */
    public static void stamperCheckMarkPDF(String infilePath,String outFilePath,String picPath) throws IOException, DocumentException {
                 PdfReader reader = new PdfReader (infilePath); // select the required seal pdf
                 PdfStamper stamp = new PdfStamper (reader, new FileOutputStream (outFilePath)); // after the addition was complete seal pdf

                 Rectangle pageSize = reader.getPageSize (1); // get the first page
        float height = pageSize.getHeight();
        float width  = pageSize.getWidth();

        int nums = reader.getNumberOfPages();
                 Image [] nImage = subImages (picPath, nums); // cut image generating Jifeng


        for(int n=1;n<=nums;n++){
                         PdfContentByte over = stamp.getOverContent (n); // provided on the first few pages printed stamp
                         Image img = nImage [n-1]; // Select Image
//            img.setAlignment(1);
 // img.scaleAbsolute (200,200); // control image size
                         img.setAbsolutePosition (width-img.getWidth (), height / 2-img.getHeight () / 2); // image position control
            over.addImage(img);
        }
        stamp.close();
    }



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

 

  

 

Intelligent Recommendation

WKHTMLTOPDF will turn a URL page to PDF

Share a tool for quickly transferring URL pages into a PDF file WKHTMLTOPDF We need to answer three questions What is WKHTMLTOPDF? Official website address: https://wkhtmltopdf.org/ According to the o...

Use WKHTMLTOPDF to turn the webpage to PDF

Use WKHTMLTOPDF to turn the webpage to PDF The webpage is saved as a PDF. The method I used before is the function of the browser's own. Use the shortcut key Ctrl + P or right -click on the browser to...

pdf turn Picture Tools

Guide package: Code:  ...

html pdf turn

1.html2canvas and jdPdf.debug.js The principle is to use html canvas to capture images into a PDF, and then write by jsPdf.debug.js Cons: Interface Control unfriendly, if you want to make changes to h...

More Recommendation

java html to turn pdf

Recently, a demand to turn html pdf. Used itext, pd4ml, not ideal, there is not a style issue, page size is a problem. Or font problems. The solution is through wkhtmltopdf tool available for download...

C # will turn html pdf

      ...

HTML turn PDF

HTML turn PDF Package HTML to PDF Method Calling method...

HTML turn PDF or Image

1. The last written to the HTML file according to the URL URL is converted to an HTML file link:Jump link. 2. This time turns HTML to PDF or Image Use WKHTMLTOPDF tools this time Download link:click t...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top