怎么在线把一个HTML页面转换成一个PDF文档

如何在线把一个HTML页面转换成一个PDF文档?

我们在工作或者学习当中,经常想用到一个功能,就是想把一个HTML页面转换成一个PDF文档。我们一般的做法就是把这个HTML页面拷贝到Office的Word文档里面;然后通过Word的自带的工具把Word转换成一个PDF文档;但是有的时候,我们需要在我们的程序中把一个HTML页面或者一段能渲染程HTML页面的代码转换成PDF页面,这个时候,我们应该这么做呢?在这里可以给大家推荐一个在线的网站,https://pdfcrowd.com/html-to-pdf-api/,在这个网站上,大家可以免费注册一个账号,这个试用账号可以生成100份PDF的文档。API调用的方式非常简单,

Step1.用自己的邮箱注册一个用户账号(比如:henryzhu),被注册的邮箱将会收到一个唯一标示用户的值(比如,096c8a2953b993db5b02341274393623)。

Step2.去https://pdfcrowd.com/static/clients/java/pdfcrowd-2.6-java.zip下载一个jar包

Step3.创建一个Eclipse的项目,把Step2中的下载下来的包添加到Build Path中,然后运行下面的实例代码。

import com.pdfcrowd.*;
import java.io.*;

public class PdfcrowdTest {
    public static void main(String[] args) {
        try 
        {
            FileOutputStream fileStream;     
 
            // create an API client instance
            Client client = new Client("henryzhu", "096c8a2953b993db5b02341274393623");

            // convert a web page and save the PDF to a file
            fileStream = new FileOutputStream("google_com.pdf");
            client.convertURI("http://www.google.com/", fileStream);
            fileStream.close();

            // convert an HTML string and store the PDF into a byte array
            ByteArrayOutputStream memStream  = new ByteArrayOutputStream();
            String html = "<head></head><body>My HTML Layout</body>";
            client.convertHtml(html, memStream);

            // convert an HTML file
            fileStream = new FileOutputStream("file.pdf");
            client.convertFile("e:/pdftest/file.html", fileStream);
            fileStream.close();

            // retrieve the number of tokens in your account
            Integer ntokens = client.numTokens();
        }
        catch(PdfcrowdError why) {
            System.err.println(why.getMessage());
        }
        catch(IOException exc) {
            // handle the exception
        }
    }
}