通过第三方组件iText将HTML代码直接输出到PDF,实现代码如下:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
public class FirstDoc {
public static void main(String[] args)
throws IOException, DocumentException {
String inputFile = "d:/test.html";
String url = new File(inputFile).toURI().toURL().toString();
String outputFile = "d:/test.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
}
}