java Html 轉換成PDF
最近在搞一個關于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找到放到同級目錄下
- 本文附件下載:
- pd4ml_demo.jar (602.1 KB)
- ss_css2.jar (146.3 KB)
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!