资源简介
采用pd4ml的jar 将html转为pdf,压缩包中包含所需的三个jar包,代码html2Pdf.java以及pom文件
代码片段和文件信息
package com.ccssoft;
import java.awt.Insets;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.security.InvalidParameterException;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
public class Html2PdfUtil {
protected int topValue = 10;
protected int leftValue = 20;
protected int rightValue = 10;
protected int bottomValue = 10;
protected int userSpaceWidth = 1300;
public static void main(String[] args) {
try {
Html2PdfUtil jt = new Html2PdfUtil();
String html = readFile(“C:\\Users\\ll\\Desktop\\a.html“ “UTF-8“);
jt.doConversion2(html “C:\\Users\\ll\\Desktop\\a14.pdf“);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doConversion2(String htmlDocument String outputPath) throws InvalidParameterException MalformedURLException IOException {
PD4ML pd4ml = new PD4ML();
// PD4ML.getVersion(); // 静态方法查看pd4ml版本
// pd4ml.enableDebugInfo(); // 开启转换调试信息
pd4ml.setHtmlWidth(userSpaceWidth); // set frame width of “virtual web browser“
// choose target paper format
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
// define PDF page margins
pd4ml.setPageInsetsMM(new Insets(topValue leftValue bottomValue rightValue));
// source HTML document also may have margins could be suppressed this way
// (PD4ML *Pro* feature):
pd4ml.addstyle(“BODY {margin: 0}“ true);
// If built-in basic PDF fonts are not sufficient or
// if you need to output non-Latin texts TTF embedding feature should help
// (PD4ML *Pro*)
pd4ml.useTTF(“java:fonts“ true);
// 设置字体:
pd4ml.setDefaultTTFs(“Helvetica Neue“ “Helvetica Neue“ “Helvetica Neue“);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// actual document conversion from HTML string to byte array
pd4ml.render(new StringReader(htmlDocument) baos);
// if the HTML has relative references to images etc
// use render() method with baseDirectory parameter instead
baos.close();
System.out.println(“resulting PDF size: “ + baos.size() + “ bytes“);
// in Web scenarios it is a good idea to send the size with
// “Content-length“ HTTP header
File output = new File(outputPath);
java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
fos.write(baos.toByteArray());
fos.close();
System.out.println(outputPath + “\ndone.“);
}
private final static String readFile(String path String encoding) throws IOException {
File f = new File(path);
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 3592 2020-08-13 18:53 htmlToPdf\Html2PdfUtil.java
文件 26762315 2019-04-17 12:22 htmlToPdf\fonts-1.0.0.jar
文件 558097 2017-01-12 00:10 htmlToPdf\pd4ml-1.0.0.jar
文件 590 2020-08-13 18:55 htmlToPdf\pom需要引入的jar.txt
文件 149846 2011-04-18 12:41 htmlToPdf\ss_css2-0.9.3.jar
目录 0 2020-08-13 18:57 htmlToPdf\
评论
共有 条评论