javahtml⽣成PDF,并打印
import java.io.File;
import java.io.FileOutputStream;
fer.pd4ml.PD4Constants;
fer.pd4ml.PD4ML;
fer.pd4ml.PD4PageMark;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
pdf转html
import javax.print.attribute.HashPrintRequestAttributeSet;
public void createPDF(String printHtml, File pdffile) throws InvalidParameterException, IOException{
StringBuffer html = new StringBuffer();
html.append("<style>")
.append(" .pageBreak{page-break-after: always; }")
.append("</style>");
html.append(printHtml);
html.append("<pd4ml:page.break>");
StringReader strReader = new StringReader(getHtml(html).toString());
FileOutputStream fos = new FileOutputStream(pdffile);
PD4ML pd4ml = new PD4ML();
pd4ml.setPageInsets(new Insets(5, 5, 5, 5));
pd4ml.setHtmlWidth(700);
pd4ml.setPageSize(PD4Constants.A4);
pd4ml.useTTF("file:"+Property("ofbiz.home")+"/hot-deploy/heluoexam/webapp/exam/fonts", true);
PD4PageMark footer = new PD4PageMark();
footer.setHtmlTemplate("<div style=\"font-family:宋体;font-size:8px;text-align:center;width:100%\">第 $[page] 页共 $[total] 页</div>");
footer.setAreaHeight(-1);
pd4ml.setPageFooter(footer);
}
public StringBuffer getHtml(Object in){
StringBuffer html = new StringBuffer();
html.append("<html>")
.append("<head>")
.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
.append("<style>")
.append("BODY {PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5; FONT-STYLE: normal; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; COLOR: #333; FONT-SIZE: 13px; FONT-WEIGHT: normal; PADDING-TOP: 0px}"        .append("table{border:1px solid #000;}")
.append("table td{border:1px solid #000;}")
.append("</style>")
.append("</head>")
.append("<body>");
html.append(in);
html.append("</body></html>");
return html;
}
private void PrintPDF(File pdFile) {
HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
/
/设置打印格式,如未确定类型,选择autosense
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
//查所有的可⽤的打印服务
//    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
//定位默认的打印服务
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//显⽰打印对话框
//    PrintService service = ServiceUI.printDialog(null, 200, 200, printService,defaultService, flavor, pras);
if(defaultService != null){
try {
DocPrintJob job = atePrintJob();//创建打印作业
FileInputStream fis = new FileInputStream(pdFile);//构造待打印的⽂件流
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
} catch (Exception e){
e.printStackTrace();
}
}
}