我正在尝试将xhtml文件转换为pdf 使用简单的html文件成功完成了
但是,当集成<ui:composition template="/template/index1.xhtml">
和<ui:define name="pageContent">
那样:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>JSF2 - download PDF after button click</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"
integrity="sha256-c9vxcXyAG4paArQG3xk6DjyW/9aHxai2ef9RpMWO44A="
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
</h:head>
<h:body>
<ui:composition template="/template/index1.xhtml">
<ui:define name="pageContent">
<div id="content2"
style="background: #fff; border-bottom: 1px solid #ffffff;">
SARIA</div>
<button class="btn btn-info" id="downloadPDF">Download PDF</button>
<script>
$('#downloadPDF').click(
function() {
domtoimage.toPng(
document.getElementById('content2')).then(
function(blob) {
var pdf = new jsPDF('l', 'pt', [
$('#content2').width(),
$('#content2').height() ]);
pdf.addImage(blob, 'PNG', 0, 0, $(
'#content2').width(), $(
'#content2').height());
pdf.save("test.pdf");
that.options.api.optionsChanged();
});
});
</script>
</ui:define>
</ui:composition>
</h:body>
</html>
您能告诉我我错过了什么吗?非常感谢。
答案 0 :(得分:0)
只需尝试以下代码:
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ec.getRequest();
try
{
ITextRenderer renderer = new ITextRenderer();
SharedContext scontext=renderer.getSharedContext();
scontext.setDotsPerPixel(14);
renderer.setDocument(url);
renderer.getFontResolver().addFont("C:\\WINDOWS\\FONTS\\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);
renderer.layout();
HttpServletResponse response = (HttpServletResponse) ec.getResponse();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=\""+ fileName + ".pdf\"");
OutputStream os = response.getOutputStream();
renderer.createPDF(os);
os.close();
}
catch(Exception e)
{
e.printStackTrace();
}
fc.responseComplete();
和
<p:commandButton value="Print" action="#{manageBean.createPDFOfSurveyResult()}" ajax="false" onclick="this.form.target='_blank'"/>
希望获得帮助