我是 JasperReports 的新手,发现自己对它很迷茫。我在 JSF 中有一个 Web 应用程序,我想用它来打印 PDF。我已经构建了报告,并且能够成功编译并使用我的所有参数填充它。然而,我迷失了实际的输出部分。我希望将其以 PDF 格式打印到打印机上。我不在乎在屏幕上看到它,直接打印到打印机将是理想的(从服务器将是理想的,但客户端也很好,因为我们可以设置客户端根据需要进行打印(这是一个内部应用程序)) .
最佳答案
I'd like it go to a printer as a PDF. I don't care about ever seeing it on screen, straight to printer would be the ideal
你无法使用纯 HTML/CSS/JS 来做到这一点。由于 JSF 基本上只是一个 HTML/CSS/JS 代码生成器,因此它无法为您带来任何魔力。最接近的是 JavaScript 的 window.print()
,但这仍然会向用户显示打印机设置等(基本上,它的作用与 Ctrl+P
相同)。
你最好的选择是创建一个 Applet它使用 the javax.print
API然后通过 HTML <applet>
将该 Applet 嵌入到您的 JSF 页面中或<object>
标签。
如果您可以直接在屏幕上看到它并将打印作业委托(delegate)给最终用户本身,那么您可以通过 JSF 将 PDF 文件发送到屏幕,如下所示:
public void sendPdf() throws IOException {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Content-Disposition", "inline; filename=\"filename.pdf\"");
yourJasperReportsClass.writePdfTo(externalContext.getResponseOutputStream());
facesContext.responseComplete();
}
我从未使用过 JasperReports,所以 yourJasperReportsClass.writePdfTo()
虽然只是随意猜测,但暗示应该已经足够清楚了。您基本上需要指示它将 PDF 写入响应正文。
更新:根据注释,该打印机实际上连接到服务器,而不是客户端,并且您实际上想让服务器将其打印到其打印机。在这种情况下,只需使用 the javax.print
API 。在该文档的底部,您可以找到一些代码示例。以下是相关性摘录:
Using the API
A typical application using the Java Print Service API performs these steps to process a print request:
- Chooses a DocFlavor.
- Creates a set of attributes.
- Locates a print service that can handle the print request as specified by the DocFlavor and the attribute set.
- Creates a Doc object encapsulating the DocFlavor and the actual print data, which can take many forms including: a Postscript file, a JPEG image, a URL, or plain text.
- Gets a print job, represented by DocPrintJob, from the print service.
- Calls the print method of the print job.
The following code sample demonstrates a typical use of the Java Print Service API: locating printers that can print five double-sided copies of a Postscript document on size A4 paper, creating a print job from one of the returned print services, and calling print.
FileInputStream psStream; try { psStream = new FileInputStream("file.ps"); } catch (FileNotFoundException ffne) { } if (psStream == null) { return; } DocFlavor psInFormat = DocFlavor.INPUT_STREAM.POSTSCRIPT; Doc myDoc = new SimpleDoc(psStream, psInFormat, null); PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); aset.add(new Copies(5)); aset.add(MediaSize.A4); aset.add(Sides.DUPLEX); PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset); > if (services.length > 0) { DocPrintJob job = services[0].createPrintJob(); try { job.print(myDoc, aset); } catch (PrintException pe) { } }
如果上述代码由 JSF 托管 bean 调用,则无关紧要。毕竟只是Java。您可能只想修改 DocFlavor
和其他设置。
关于java - 从 JasperReports 打印 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7999792/