java html 转化pdf文件格式_java编程将HTML文件转换成PDF文件(转)

packagesamples;importjava.awt.Insets;;importjava.io.BufferedInputStream;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.StringReader;importjava.net.MalformedURLException;importjava.net.URL;importjava.security.InvalidParameterException;importorg.zefer.pd4ml.PD4Constants;importorg.zefer.pd4ml.PD4ML;public classGettingStarted2 {protected int topValue = 10;protected int leftValue = 20;protected int rightValue = 10;protected int bottomValue = 10;protected int userSpaceWidth = 1300;public static voidmain(String[] args) {try{

GettingStarted2 jt= newGettingStarted2();

String html= readFile("c:/sample.htm", "UTF-8");

jt.doConversion2(html,"c:/pd4ml.pdf");

}catch(Exception e) {

e.printStackTrace();

}

}public voiddoConversion2( String htmlDocument, String outputPath )throwsInvalidParameterException, MalformedURLException, IOException {

PD4ML pd4ml= newPD4ML();

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(newInsets(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("c:/windows/fonts", true);

ByteArrayOutputStream baos= newByteArrayOutputStream();//actual document conversion from HTML string to byte array

pd4ml.render(newStringReader(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= newFile(outputPath);

java.io.FileOutputStream fos= newjava.io.FileOutputStream(output);

fos.write( baos.toByteArray() );

fos.close();

System.out.println( outputPath+ "\ndone.");

}private final static String readFile( String path, String encoding ) throwsIOException {

File f= newFile( path );

FileInputStream is= newFileInputStream(f);

BufferedInputStream bis= newBufferedInputStream(is);

ByteArrayOutputStream fos= newByteArrayOutputStream();byte buffer[] = new byte[2048];intread;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();returnfos.toString(encoding);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值