Как создать PDF-отчет в веб-приложении Java с использованием списков? - PullRequest
0 голосов
/ 12 июня 2019

Я создаю отчеты со списками и параметрами, без базы данных, без запросов. Я работаю с JasperSoft Studio 6 (jasperreports-6.5.1.jar, iText-2.1.7.js2.jar), Eclipse, JSP, Java 7 и Tomcat 7.

Я могу создать простой список, подобный этому:

Sample.java

public class Sample {
    private String value;
    public Sample(String value) {this.value = value;}
    public String getValue() {return value;}
}

SampleServlet.java

public class SampleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            InputStream jrxml = getServletContext().getResourceAsStream("WEB-INF/pdf/Sample.jrxml");
            JasperReport report = JasperCompileManager.compileReport(jrxml);
            List<Sample> list = Arrays.asList(new Sample("One"), new Sample("Two"), new Sample("Three"));
            JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(list);
            JasperPrint print = JasperFillManager.fillReport(report, null, source);
            response.setContentType("application/pdf");
            ServletOutputStream output = response.getOutputStream();
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setExporterInput(new SimpleExporterInput(print));
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(output));
            exporter.exportReport();
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
}

Sample.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.5.1.final using JasperReports Library version 6.5.1  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Blank_A4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ec148bc4-3203-4f96-94ac-2c16820bcfb3">
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="value" class="java.lang.String"/>
    <detail>
        <band height="32" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="555" height="32" uuid="c0ccbbff-6099-4565-91f2-53e78f7b97be"/>
                <textFieldExpression><![CDATA[$F{value}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Выводит PDF со списком (каждая строка может быть отдельной страницей):

One

Two

Three

Но мне нужно добавить туда подсписки (подотчеты) ...

List<Sample> list = Arrays.asList(new Sample("One:"), new Sample("Two:"), new Sample("Three:"));
List<List<SubSample>> sublists = Arrays.asList(
    Arrays.asList(new SubSample("First"), new SubSample("Single"), new SubSample("Solo")),
    Arrays.asList(new SubSample("Second"), new SubSample("Double"), new SubSample("Duo")),
    Arrays.asList(new SubSample("Third"), new SubSample("Triple"), new SubSample("Trio"))
);

... который должен вывести PDF как этот (каждая группа может быть отдельной страницей):

One:
First
Single
Solo

Two:
Second
Double
Duo

Three:
Third
Triple
Trio

Как мне этого добиться?

1 Ответ

0 голосов
/ 18 июня 2019

Я понял.Все сделано в основном отчете, вы ничего не делаете с вложенным отчетом.

В этом случае изменения:

  • Копия Sample.java в виде SubSample.java и Sample.jrxml as SubSample.jrxml ;
  • В Sample.java новое поле List<SubSample> sublist ;
  • В SampleServlet.java заполнено новое поле и новый параметр subreport , заданный в качестве пути для скомпилированного SubSample.jrxml (.jasper);
  • В Sample.jrxml новое поле java.util.List подсписок и новый параметр java.lang.String подотчет ;
  • И вторая полоса детализации с новым элементом подотчета, для которого Expression установлено как $ P {subreport} и Data Source Expression как new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource ($ F {sublist}) .

Результат:

SubSample.java

Copy of the original Sample.java

SubSample.jrxml

Copy of the original Sample.jrxml (with a different uuid)

Sample.java

public class Sample {
    private String value;
    private List<SubSample> sublist;
    public Sample(String value) {this.value = value;}
    public String getValue() {return value;}
    public List<SubSample> getSublist() {return sublist;}
    public void setSublist(List<SubSample> sublist) {this.sublist = sublist;}
}

Sample.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.5.1.final using JasperReports Library version 6.5.1  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Blank_A4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="17771092-9052-49a8-8301-28b1bdf97288">
    <parameter name="subreport" class="java.lang.String"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="value" class="java.lang.String"/>
    <field name="sublist" class="java.util.List"/>
    <detail>
        <band height="32" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="555" height="32" uuid="c0ccbbff-6099-4565-91f2-53e78f7b97be"/>
                <textFieldExpression><![CDATA[$F{value}]]></textFieldExpression>
            </textField>
        </band>
        <band height="32">
            <subreport>
                <reportElement x="0" y="0" width="555" height="32" uuid="e51bd9df-f1c5-4776-9438-8854461bad2a"/>
                <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{sublist})]]></dataSourceExpression>
                <subreportExpression><![CDATA[$P{subreport}]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

SampleServlet.java

public class SampleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            InputStream jrxml = getServletContext().getResourceAsStream("WEB-INF/pdf/Sample.jrxml");
            JasperReport report = JasperCompileManager.compileReport(jrxml);

            String subjrxml = getServletContext().getRealPath("WEB-INF/pdf/SubSample.jrxml");
            String subreport = JasperCompileManager.compileReportToFile(subjrxml);
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("subreport", subreport);
            List<Sample> list = Arrays.asList(new Sample("One:"), new Sample("Two:"), new Sample("Three:"));
            List<List<SubSample>> sublists = Arrays.asList(
                Arrays.asList(new SubSample("First"), new SubSample("Single"), new SubSample("Solo")),
                Arrays.asList(new SubSample("Second"), new SubSample("Double"), new SubSample("Duo")),
                Arrays.asList(new SubSample("Third"), new SubSample("Triple"), new SubSample("Trio"))
            );
            for (int i = 0; i < list.size(); i++)
                list.get(i).setSublist(sublists.get(i));
            JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(list);
            JasperPrint print = JasperFillManager.fillReport(report, parameters, source);

            response.setContentType("application/pdf");
            ServletOutputStream output = response.getOutputStream();
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setExporterInput(new SimpleExporterInput(print));
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(output));
            exporter.exportReport();
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
}

Вывод PDF:

One:
First
Single
Solo

Two:
Second
Double
Duo

Three:
Third
Triple
Trio

Благодаря этим ресурсам .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...