第一种:wkhtmltopdf
下载文件,并装好
//软件所在位置
private static String toImageTool = "E:\\wkhtmltopdf\\bin\\wkhtmltoimage.exe";
//链接
private static String toImageUrl = "http://www.baidu.com/";
//新文件生成位置
private static String outImageFile = "d:/out.jpg";
public static void main(String[] args) throws Exception{
String commond = toImageTool +" " + toImageUrl + " " + outImageFile;
System.out.println(commond);
Runtime.getRuntime().exec(commond);
Process proc = Runtime.getRuntime().exec(commond.toString());
HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
error.start();
output.start();
proc.waitFor();
}
颜色有点失真,几乎不影响
第二种:Spire.PDF for JAVA
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;
public class HtmltoPDF {
public static void main(String[] args) {
//定义需要转换的HTML
String url = "https://www.e-iceblue.cn/";
String fileName = "Result.pdf";
//设置插件本地地址
String pluginPath = "D:/Qt/plugins_32";
HtmlConverter.setPluginPath(pluginPath);
//转换到PDF并设置PDF尺寸
HtmlConverter.convert(url, fileName, true, 1000000, new Size(600f, 900f), new PdfMargins(0));
}
}
我的链接里有图片,会丢失,不可直接用,需要其他的配置(还不会)才能正常使用。