第一步,下载jar包以及建对应的文件夹。注意pd4ml的jar要选择pro版本。然后建一个pd4fonts.properties
里面对应的字体。
SimSun = simsun.ttf
前面为变量名,后面要对应你下载好的字体。网上都有各种字体下载。相应步骤做完了,做完后的文件夹如图格式都有了!
注意要引入图片中对应的jar下面的三个jar包到项目中去。
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 Test {
protected int topValue = 10;
protected int leftValue = 20;
protected int rightValue = 10;
protected int bottomValue = 10;
protected int userSpaceWidth = 1300;
/**
* @param args
*/
public static void main(String[] args) {
try {
Test jt = new Test();
//此处填写你的html文件
String html = readFile("/Users/wangchen/Desktop/370fx2.html", "UTF-8");
//此处填写你下载的地方
jt.doConversion2(html, "/Users/wangchen/Desktop/370fx2.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doConversion2(String htmlDocument, String outputPath)
throws InvalidParameterException, MalformedURLException,
IOException {
PD4ML pd4ml = new PD4ML();
pd4ml.enableDebugInfo();
pd4ml.setHtmlWidth(userSpaceWidth);
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue,
rightValue));
String classPath = Test.class.getResource("/")+"fonts";
pd4ml.useTTF(classPath, true);
pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pd4ml.render(new StringReader(htmlDocument), baos);
baos.close();
File output = new File(outputPath);
java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
fos.write(baos.toByteArray());
fos.close();
}
private final static String readFile(String path, String encoding)
throws IOException {
File f = new File(path);
FileInputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream fos = new ByteArrayOutputStream();
byte buffer[] = new byte[2048];
int read;
do {
read = is.read(buffer, 0, buffer.length);
if (read > 0) {
fos.write(buffer, 0, read);
}
} while (read > -1);
fos.close();
bis.close();
is.close();
return fos.toString(encoding);
}
}
如上你就可以下载将html转为pdf了。任意文本也可以转为pdf,经测试,可用
附件如下:https://pan.baidu.com/s/1wSvBM6Kti4IpI9IlDaycew