直接上代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
/**
*
* @date 2016年6月4日下午6:01:57
* @author 赵
*
*/
public class ConvertHtmlToPdfWithFly {
public void convert() {
FileOutputStream os = null;
try {
ITextRenderer renderer = new ITextRenderer();
os = new FileOutputStream("D:\\4.pdf");
String path = "D:\\7l3ra1b9ho8np.html";
renderer.setDocument(new File(path).toURI().toURL().toString());
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/SimSun.ttc", BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (os != null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意事项:
html文件的顶层的宽度最好设置为80%,这样输出成A4时效果比较好