Set output file name for PDF exporter

2019-06-10 23:14发布

问题:

I am using JasperReports 5.6
I generate pdf using PDFCreator.
My pdf is generated successfully, but i can't set name to that PDF file.

PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.ISO_A4);
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName("PDFCreator", null));   
JRPrintServiceExporter exporter = new JRPrintServiceExporter(); 
exporter.setExporterInput(new SimpleExporterInput(tempFileName));
SimplePrintServiceExporterConfiguration configuration = new SimplePrintServiceExporterConfiguration();
configuration.setPrintRequestAttributeSet(printRequestAttributeSet);
configuration.setPrintServiceAttributeSet(printServiceAttributeSet);
configuration.setDisplayPageDialog(false);
configuration.setDisplayPrintDialog(false);
exporter.setConfiguration(configuration);   
exporter.exportReport();

My pdf name are set using that PDFCreator tool
I want to pass the name to that pdf file.
Since exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "d:/adc.pdf"); method is now deprecated.
Please tell me solution how to set that out file name

回答1:

I don't think there's a way to pass a file name to PDFCreator, because the whole idea is that it is a virtual printer. So to the program that sending the document, it could be being printed on a physical printer somewhere, hence an output file name would be irrelevant.

Whenever I need to output reports as PDFs I use JasperExportManager, which is a much simpler solution. The exportReportToPdfFile method accepts the output file path as a string. Example:

JasperPrint filledReport = JasperFillManager.fillReport("report.jrxml", params);
JasperExportManager.exportReportToPdfFile(filledReport, "report.pdf");

Alternatively, you can keep your code largely the same but change your JRPrintServiceExporter to a JRPdfExporter. The new way to set the output format (now that setParameter is deprecated) is to construct an ExporterOutput and then call setExporterOutput on your exporter.