How to merge two pdf documents into a single report in JasperReports?
Asked Answered
I

5

10

I am new to JasperReports. I can create a simple PDF document with Javabean datasource. In my project I have created two separate pdf document with separate javabean datasource. Now I want to merge both documents into a single document. Can anyone tell me how to merge both documents into single document using JasperReports?

Impend answered 19/4, 2010 at 8:7 Comment(0)
D
31

unfortunately the solution is build a sub report and use the 2 different DataSource or what ever connection you used

but there is an easy way to get over with this question :D just simple no new reports ..... Voilà

ok lets do it

JasperPrint jp1 = JasperFillManager.fillReport(url.openStream(), parameters,
                    new JRBeanCollectionDataSource(inspBean));
JasperPrint jp2 = JasperFillManager.fillReport(url.openStream(), parameters,
                    new JRBeanCollectionDataSource(inspBean));

ok we have over 2 records ..lets take our first record jp1 and add jp2 content into it

List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
    JRPrintPage object = (JRPrintPage)pages.get(j);
    jp1.addPage(object);

}
JasperViewer.viewReport(jp1,false);

This work like a charm .. with couple of loops you can merge any number of report together .. without creating new reports

http://lnhomez.blogspot.com/2011/11/merge-multiple-jasper-reports-in-to.html

Deryl answered 26/11, 2011 at 12:53 Comment(4)
+1 Easy and elegant solution, after I got stumped with subreports panning over each other and whatnot.Gewgaw
This is a nice solution (Thanks Lahiru) as we have a requirement where two different language notifications are to be sent to customers and customer might opt either both or single language. What @lahiru suggested perfects fits our basket.Altheaalthee
I think this can be the solution for the below problem also ??#29975390Retract
Nice, but and about the number of pages or table of contents? Would be possible to fill with the right content?Unicameral
S
2

You can use use a list of JasperPrint like this:

List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();

jasperPrintList.add(JasperFillManager.fillReport("Report_file1.jasper", getReportMap(1), new JREmptyDataSource()));
jasperPrintList.add(JasperFillManager.fillReport("Report_file2.jasper", getReportMap(2), new JREmptyDataSource()));
jasperPrintList.add(JasperFillManager.fillReport("Report_file3.jasper", getReportMap(3), new JREmptyDataSource()));

JRPdfExporter exporter = new JRPdfExporter();

exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("Report_PDF.pdf"));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setCreatingBatchModeBookmarks(true);
exporter.setConfiguration(configuration);

exporter.exportReport();
Salim answered 9/7, 2019 at 14:35 Comment(0)
P
1

You can use subreports for this. You dont have to recreate your current reports. Create a master report, with 0 margins. Add all your reports to this as subreport and put condition that if datasource is available for this, only then print this report. Now put all your individual datasources into one map data source and pass this datasource to master report. Configute all subreports to the key in the map.

Pylon answered 20/10, 2010 at 9:51 Comment(1)
This is viable only if you have a fixed number of subreports, if you need to dinamically append reports sub-report is not a option.Braithwaite
A
0

Multiple Pages in one JasperPrint

Sample Code:

DefaultTableModel dtm = new DefaultTableModel(new Object[0][3], new String[]{"Id","Name","Family"});
String[] fields= new String[3];    
boolean firstFlag=true;
JasperPrint jp1 =null;
JasperPrint jp2 =null;
for (int i=0 ; i<=pagesCount ; i++)
{
   fields[0]= "id";
   fields[1]= "name";
   fields[2]= "family";
   dtm.insertRow(0, fields); 
   try
   {
      Map<String, Object> params = new HashMap<String, Object>();                
      if (firstFlag)
      {
         jp1 = JasperFillManager.fillReport(getClass().getResourceAsStream(reportsource), params, new JRTableModelDataSource(dtm));                
         firstFlag=false;                            
      }else
      {
         jp2 = JasperFillManager.fillReport(getClass().getResourceAsStream(reportsource), params, new JRTableModelDataSource(dtm));
         jp1.addPage(jp2.getPages().get(0));
      }     
   }catch (Exception e) 
   {
      System.out.println(e.fillInStackTrace().getMessage());
   }
}
JasperViewer.viewReport(jp1,false);
Achieve answered 22/1, 2018 at 16:28 Comment(0)
S
0

Lahiru Nirmal's answer was simple and to the point. Here's a somewhat expanded version that also copies styles and other things (not all of which I'm positive are crucial).

Note that all of the pages are of the same size.

public static JasperPrint createJasperReport(String name, JasperPrint pattern)
{
    JasperPrint newPrint = new JasperPrint();
    newPrint.setBottomMargin(pattern.getBottomMargin());
    newPrint.setLeftMargin(pattern.getLeftMargin());
    newPrint.setTopMargin(pattern.getTopMargin());
    newPrint.setRightMargin(pattern.getRightMargin());
    newPrint.setLocaleCode(pattern.getLocaleCode());
    newPrint.setName(name);
    newPrint.setOrientation(pattern.getOrientationValue());
    newPrint.setPageHeight(pattern.getPageHeight());
    newPrint.setPageWidth(pattern.getPageWidth());
    newPrint.setTimeZoneId(pattern.getTimeZoneId());

    return newPrint;
}

public static void addJasperPrint(JasperPrint base, JasperPrint add)
{
    for (JRStyle style : add.getStyles())
    {
        String styleName = style.getName();
        if (!base.getStylesMap().containsKey(styleName))
        {
            try
            {
                base.addStyle(style);
            }
            catch (JRException e)
            {
                logger.log(Level.WARNING, "Couldn't add a style", e);
            }
        }
        else
            logger.log(Level.FINE, "Dropping duplicate style: " + styleName);
    }

    for (JRPrintPage page : add.getPages())
        base.addPage(page);

    if (add.hasProperties())
    {
        JRPropertiesMap propMap = add.getPropertiesMap();
        for (String propName : propMap.getPropertyNames())
        {
            String propValue = propMap.getProperty(propName);
            base.setProperty(propName, propValue);
        }
    }

    if (add.hasParts())
    {
        PrintParts parts = add.getParts();
        Iterator<Entry<Integer, PrintPart>> partsIterator = parts.partsIterator();
        while (partsIterator.hasNext())
        {
            Entry<Integer, PrintPart> partsEntry = partsIterator.next();
            base.addPart(partsEntry.getKey(), partsEntry.getValue());
        }
    }

    List<PrintBookmark> bookmarks = add.getBookmarks();
    if (bookmarks != null)
        for (PrintBookmark bookmark : bookmarks)
            base.addBookmark(bookmark);
}

Then, to use it:

JasperPrint combinedPrint = createJasperReport("Multiple Reports",
    print1);
for (JasperPrint addPrint : new JasperPrint[] { print1, print2, print3 })
    addJasperPrint(combinedPrint, addPrint);

// Now do whatever it was you'd do with the JasperPrint.
String combinedXml = JasperExportManager.exportReportToXml(combinedPrint);

I see JasperReports now has a newer "Report Book" feature that might be a better solution, but I haven't used one yet.

Sharpshooter answered 23/5, 2018 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.