Java Html 转Pdf
1。下载iText-2[1].0.8.jar,core-renderer.jar两个包
2。代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
public class WordToPdf {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String inputFile = "D:\\test.html";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "D:\\test.pdf";
System.out.println(url);
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/SIMSUN.TTC",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/D:/z/temp/");
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
public class WordToPdf {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String inputFile = "D:\\test.html";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "D:\\test.pdf";
System.out.println(url);
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/SIMSUN.TTC",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/D:/z/temp/");
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
每种功能的实现方法有很多,希望各位可以交流不同的思想和方法。可以加QQ412546724。呵呵