java Html 转换成PDF

jopen 10年前

最近在搞一个关于html转换为pdf的需求,网上找了很多,但是如果批量处理就会出现问题,最后找到了PD4ML,解决了我的问题

package fonts;  import java.awt.Dimension;  import java.awt.Insets;  import java.io.ByteArrayOutputStream;  import java.io.FileOutputStream;  import java.io.IOException;  import java.net.URL;  import org.zefer.pd4ml.PD4Constants;  import org.zefer.pd4ml.PD4ML;  public class TextHtml {      protected Dimension format = PD4Constants.A4;      protected boolean landscapeValue = false;      protected int topValue = 5;      protected int leftValue = 10;      protected int rightValue = 10;      protected int bottomValue = 10;      protected String unitsValue = "mm";      protected String proxyHost = "";      protected int proxyPort = 0;      protected int userSpaceWidth = 1100;   public static void main(String[] args) throws Exception {      TextHtml converter = new TextHtml();      //for (int i = 0; i < 7000; i++) {        converter.generatePDF_2(0);           // }      }        public void generatePDF_2(int i) throws Exception {            ByteArrayOutputStream ba = new ByteArrayOutputStream();          PD4ML pd4ml = new PD4ML();          pd4ml.setPageSize(new java.awt.Dimension(450, 450));          pd4ml.setPageInsets(new java.awt.Insets(5, 5, 5, 5));          pd4ml.enableImgSplit(false);          pd4ml.useTTF("java:fonts", true);          try {              pd4ml.setPageSize(landscapeValue ? pd4ml .changePageOrientation(format) : format);          } catch (Exception e) {              e.printStackTrace();          }          if (unitsValue.equals("mm")) {              pd4ml.setPageInsetsMM(new Insets(topValue, leftValue,              bottomValue, rightValue));          } else {              pd4ml.setPageInsets(new Insets(topValue, leftValue,              bottomValue, rightValue));          }          pd4ml.setHtmlWidth(userSpaceWidth);          String urlstring = "file:///D:/债权转让及受让协议--魏然2014-08-16.html";          URL url = new URL(urlstring);          pd4ml.render(urlstring, ba);          try {              FileOutputStream out = new FileOutputStream("d:\\demo\\pdf\\"+3311+".pdf");                ba.writeTo(out);              out.flush();              out.close();              ba.close();          } catch (IOException e) {              e.printStackTrace();          }      }    }

需要在src目录下创建fonts文件夹,并且在文件夹中建立pd4fonts.properties ,配置文件中的内容如下

#this is an autogenerated file. please remove manually any references to copyrighted fonts #Fri Oct 23 19:43:12 CEST 2009 KaiTi_GB2312=STZHONGS.TTF

STZHONGS.TTF 需要到C:\Windows\Fonts找到放到同级目录下

原文地址:http://www.geek521.com/?p=7774