Hi Bruno,
Thanks a lot for your quick reply.

I am generating 2 separate files USING iText. I am  merging them later.
The first file is always getting generated. But the second file gets
generated MOST OF THE TIMES..but sometimes it gives the error.
I am closing the documents and also not adding any junk.

I am using page event which puts page numbers and some footer labels.

I am enclosing the file which has the code for generating both the files and
also the method which merges.
method, downloadLicencePdfInline  - calls the PDF generation methods
separately and merges
method, generateNoticeOfDecisionPdf - second PDF which GIVES ERROR SOMETIMES
method, generateLicencePdf - first PDF which DOES NOT GIVE ERROR

Regards,
Archana

On Fri, Jul 4, 2008 at 4:13 PM, Bruno Lowagie <[EMAIL PROTECTED]> wrote:

> Archana Nagesh wrote:
> > Hi,
> >
> > I am generating a PDF using iText.
> > In most cases the PDF generation is successful. But sometimes I get the
> > following error (this error is a random one):
> >
> > Rebuild failed: trailer not found; Original message: PDF startxref not
> found
>
> Are these PDFs generated with iText?
>
> If not, then you have PDFs that aren't complete (1).
> These PDFs are invalid and can't be rebuilt.
> Or (2) the PDFs are complete, but plenty of rubbish
> is added at the end (gibberish, stuff that prevents
> the viewer to find the %EOF).
>
> If they are iText generated, (1) could happen when you
> forget to close() the document (or when the process
> generating the PDF closes the stream before document.close()
> is reached). In chapter 17 of my book, I have an anecdote
> from my day job where somebody created a PDF and added some
> HTML to the stream after the PDF was generated, causing
> problem (2) as described above. Fortunately, I didn't have
> to tell me colleague he had made a stupid mistake. He said
> so himself ;-)
>
> br,
> Bruno
>
> -------------------------------------------------------------------------
> Sponsored by: SourceForge.net Community Choice Awards: VOTE NOW!
> Studies have shown that voting for your favorite open source project,
> along with a healthy diet, reduces your potential for chronic lameness
> and boredom. Vote Now at http://www.sourceforge.net/community/cca08
> _______________________________________________
> iText-questions mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/itext-questions
>
> Do you like iText?
> Buy the iText book: http://www.1t3xt.com/docs/book.php
> Or leave a tip: https://tipit.to/itexttipjar
>
     /**
      * Generate the Licence details as a PDF file 
      * In case of errors, add the error message to the context.
      * @param fileNamePath file name including the path       
      */
     public void generateLicencePdf(String fileNamePath) {

         Document document = new Document();

         FacesContext context = FacesContext.getCurrentInstance();

         try {
             PdfWriter writer = PdfWriter.getInstance(document, new 
FileOutputStream(fileNamePath));
             writer.setPageEvent(new FooterForPDF());

             //Generating Licence PDF
             document.open();
             Image jpg = null;
             try {
             //Page header image
             String imageLocation = 
getAppContext().getResource(EcotrackCommonConstants.IMAGES_FOLDER + 
LICENCE_JPG).getFile().getPath();
             jpg = Image.getInstance(imageLocation);
             jpg.scalePercent(25);
             document.add(jpg);
             } catch (BadElementException e) {
             // TODO
             } catch (IOException e) {
             // TODO
             }          

             Paragraph heading =  new Paragraph(HEADING, new 
Font(Font.HELVETICA, 30, Font.BOLD));
             heading.setAlignment(Element.ALIGN_RIGHT);
             document.add(heading);

             Paragraph heading1 =  new Paragraph(HEADING1, new 
Font(Font.HELVETICA, 8, Font.BOLD));
             heading1.setAlignment(Element.ALIGN_RIGHT);
             document.add(heading1);

             Paragraph heading2 =  new Paragraph(HEADING2, new 
Font(Font.HELVETICA, 8, Font.BOLDITALIC));
             heading2.setAlignment(Element.ALIGN_RIGHT);
             document.add(heading2);

             Paragraph heading3 =  new Paragraph(HEADING3, new 
Font(Font.HELVETICA, 12, Font.BOLD));
             heading3.setAlignment(Element.ALIGN_RIGHT);
             document.add(heading3);

             document.add(new Paragraph(" "));
             
             Paragraph permitNumber =  new Paragraph(PERMIT_NUMBER_LABEL + 
getRwlApp().getNewPermit().getPermitRef(), new Font(Font.HELVETICA, 10, 
Font.BOLD));
             document.add(permitNumber);
             
             document.add(new Paragraph(" "));

             Paragraph validDates =  new Paragraph(VALID_FROM_LABEL + 
EcotrackUtils.formatDate(getRwlApp().getNewPermit().getEffectiveDate()) + "  to 
 " + EcotrackUtils.formatDate(getRwlApp().getNewPermit().getExpiryDate()), new 
Font(Font.HELVETICA, 10, Font.BOLD));
             document.add(validDates);

             document.add(new Paragraph(" "));
             
             document.add(new Paragraph(partiesToPermitHeader, new 
Font(Font.HELVETICA, 10, Font.BOLD)));
             
             //Permit Holder details table
             Table permitHoldertable = new Table(3);
             permitHoldertable.setPadding(4);
             permitHoldertable.setSpacing(0);
             int headerwidths[] = {20,25,55};
             permitHoldertable.setWidths(headerwidths);
             permitHoldertable.setWidth(100);
             permitHoldertable.setBorderColor(Color.GRAY);
             permitHoldertable.setBorder(0);
             Paragraph roleColHeader =  new Paragraph(ROLE_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             Cell newCell = new Cell (roleColHeader);
             permitHoldertable.addCell(newCell);
             
             Paragraph nameColHeader =  new Paragraph(NAME_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell (nameColHeader);
             permitHoldertable.addCell(newCell);
             Paragraph addressColHeader =  new Paragraph(ADDRESS_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell (addressColHeader);
             permitHoldertable.addCell(newCell);

             Paragraph roleColValue =  new Paragraph(PRINCIPAL_HOLDER_LABEL, 
new Font(Font.HELVETICA, 9));
             permitHoldertable.addCell(roleColValue);
             Paragraph nameColValue =  new 
Paragraph(getRwlApp().getClient().getTitle() + " " + 
getRwlApp().getClient().getFirstName() + " " + 
getRwlApp().getClient().getOtherNames() + " " + 
getRwlApp().getClient().getSurName(), new Font(Font.HELVETICA, 9));
             permitHoldertable.addCell(nameColValue);
             
             permitHoldertable.addCell(new 
Paragraph(getRwlApp().getClient().getRegAddressLine1() + " " + 
(getRwlApp().getClient().getRegAddressLine2() != 
null?getRwlApp().getClient().getRegAddressLine2():"") + " " +
                            getRwlApp().getClient().getRegSuburb() +  " " + 
getRwlApp().getClient().getRegState() + " " + 
getRwlApp().getClient().getRegPostCode(), new Font(Font.HELVETICA, 9)));

             if (getRwlApp().getClient().isGuardianRequired()) {
                 roleColValue =  new Paragraph(GUARDIAN_LABEL, new 
Font(Font.HELVETICA, 9));
                 permitHoldertable.addCell(roleColValue);
                 nameColValue =  new 
Paragraph(getRwlApp().getGuardian().getTitle() + " " + 
getRwlApp().getGuardian().getFirstName() + " " + 
getRwlApp().getGuardian().getOtherNames() + " " + 
getRwlApp().getGuardian().getSurName(), new Font(Font.HELVETICA, 9));
                 permitHoldertable.addCell(nameColValue);
                 
                 permitHoldertable.addCell(new 
Paragraph(getRwlApp().getGuardian().getRegAddressLine1() + " " + 
(getRwlApp().getGuardian().getRegAddressLine2() != 
null?getRwlApp().getGuardian().getRegAddressLine2():"") + " " +
                                getRwlApp().getGuardian().getRegSuburb() +  " " 
+ getRwlApp().getGuardian().getRegState() + " " + 
getRwlApp().getGuardian().getRegPostCode(), new Font(Font.HELVETICA, 9)));
             }
            
             document.add(permitHoldertable);

             document.add(new Paragraph(" "));
             
             document.add(new Paragraph(activityDetailsHeader, new 
Font(Font.HELVETICA, 10, Font.BOLD)));
             
             //Location Activity details table starts
             List<LocationActivity> locActivityList = 
getRwl().getLocationActivity(getRwlApp().getNewPermit().getPermitId());
             Table activityDetailsTable = new Table(2);
             activityDetailsTable.setPadding(4);
             activityDetailsTable.setSpacing(0);
             activityDetailsTable.setBorderColor(Color.GRAY);
             activityDetailsTable.setBorder(0);
             int headerwidthsForActivityTable[] = {50, 50};
             activityDetailsTable.setWidths(headerwidthsForActivityTable);
             activityDetailsTable.setWidth(100);

             Paragraph locColHeader =  new Paragraph(LOCATIONS_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(locColHeader);
             activityDetailsTable.addCell(newCell);

             Paragraph actColHeader =  new Paragraph(ACTIVITIES_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(actColHeader);
             activityDetailsTable.addCell(newCell);
             
             if (locActivityList != null && locActivityList.size() > 0){
                 for (LocationActivity locActivity: locActivityList){
                     String locSiteName = locActivity.getSiteName();
                     Paragraph colVal1 =  new Paragraph(locSiteName.replace("," 
, " "), new Font(Font.HELVETICA, 9));
                     activityDetailsTable.addCell(colVal1);
                     Paragraph colVal2 =  new 
Paragraph(locActivity.getSiteActivity(), new Font(Font.HELVETICA, 9));
                     activityDetailsTable.addCell(colVal2);
                 }
                 document.add(activityDetailsTable);
             }else{
                 activityDetailsTable.addCell("No Data Found");
             }
              //Location Activity details table ends
             
             document.newPage();
               
             document.add(new Paragraph(" "));
             document.add(new Paragraph(permitDetailsHeader, new 
Font(Font.HELVETICA, 13, Font.BOLD)));
 
             document.add(new Paragraph(" "));            
             document.add(new Paragraph(speciesDetailsHeader, new 
Font(Font.HELVETICA, 10, Font.BOLD)));

             //First Species details table starts
             
             List<PermitSpecies> speciesList = 
getRwl().getSpeciedDetails(getRwlApp().getNewPermit().getPermitId());
             Table speciesListHeaderTable = new Table(2);

             speciesListHeaderTable.setPadding(2);
             speciesListHeaderTable.setSpacing(0);
             speciesListHeaderTable.setBorderColor(Color.GRAY);
             speciesListHeaderTable.setBorder(0);
             
             int headerwidthsForSpeciesHeaderTable[] = {50, 50};
             
speciesListHeaderTable.setWidths(headerwidthsForSpeciesHeaderTable);
             speciesListHeaderTable.setWidth(100);

             Paragraph speciesLocColHeader =  new Paragraph(LOCATION_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(speciesLocColHeader);
             speciesListHeaderTable.addCell(newCell);

             Paragraph speciesActColHeader =  new Paragraph(ACTIVITY_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(speciesActColHeader);
             speciesListHeaderTable.addCell(newCell);
             
             if (speciesList != null && speciesList.size() > 0){
                 String siteName = speciesList.get(0).getSiteName();
                 Paragraph colVal1 =  new Paragraph(siteName.replace("," , " 
"), new Font(Font.HELVETICA, 9));
                 speciesListHeaderTable.addCell(colVal1);
                 Paragraph colVal2 =  new 
Paragraph(speciesList.get(0).getActivityMemo(), new Font(Font.HELVETICA, 9));
                 speciesListHeaderTable.addCell(colVal2);
                 document.add(speciesListHeaderTable);
             }else{
                 speciesListHeaderTable.addCell("No Data Found");
             }
             //First Species details table ends
             
              //Second Species details table starts
             Table speciesListTable = new Table(3);
             
             int headerwidthsForSpeciesTable[] = {68, 12, 20};
             speciesListTable.setPadding(2);
             speciesListTable.setSpacing(0);
             speciesListTable.setBorderColor(Color.GRAY);
             speciesListTable.setBorder(0);
             speciesListTable.setWidths(headerwidthsForSpeciesTable);
             speciesListTable.setWidth(100);
             
             Paragraph speciesSchHeader =  new Paragraph(SCHEDULE_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(speciesSchHeader);
             speciesListTable.addCell(newCell);
             Paragraph speciesCatHeader =  new Paragraph(CATEGORY_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(speciesCatHeader);
             speciesListTable.addCell(newCell);
             Paragraph speciesQtyHeader =  new Paragraph(QUANTITY_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
             newCell = new Cell(speciesQtyHeader);
             speciesListTable.addCell(newCell);
               
             if (speciesList != null && speciesList.size() > 0){               
                 for (PermitSpecies eachSpecies: speciesList){
                     Paragraph colVal1 =  new 
Paragraph(eachSpecies.getSchedule(), new Font(Font.HELVETICA, 9));
                     speciesListTable.addCell(colVal1);
                     colVal1 =  new 
Paragraph(eachSpecies.getCategoryDescription(), new Font(Font.HELVETICA, 9));
                     speciesListTable.addCell(colVal1);
                     colVal1 =  new 
Paragraph(eachSpecies.getQuantityAllowable(), new Font(Font.HELVETICA, 9));
                     speciesListTable.addCell(colVal1);
                 }
                 document.add(speciesListTable);
             }else{
                 speciesListTable.addCell("No Data Found");
             }
              //Second Species details table ends
               
             document.add(new Paragraph(" "));             
             document.add(new Paragraph(conditionsHeader, new 
Font(Font.HELVETICA, 15, Font.BOLD)));
             document.add(new Paragraph(" "));  
             
             //permit condition starts
             List<PermitCondition> permitConditionList = 
getRwl().getPermitCondition(getRwlApp().getNewPermit().getPermitId());
             String prevActMemo = "";
             String prevInterest = "";
             String prevCondDesc = "";

             if (permitConditionList != null && permitConditionList.size() > 0){
                 int i = 0; 
                 for (PermitCondition permCondition: permitConditionList){
                     i++;
                     //Displaying details only if there is a difference in the 
values
                     if (!prevActMemo.equals(permCondition.getActivityMemo())){
                        Paragraph permitCond1 =  new 
Paragraph(permCondition.getActivityMemo(), new Font(Font.HELVETICA, 12, 
Font.BOLD));   
                        document.add(permitCond1);
                     }
                     
                     if (!prevInterest.equals(permCondition.getInterest())){
                         Paragraph permitCond2 =  new 
Paragraph(permCondition.getInterest(), new Font(Font.HELVETICA, 10, 
Font.BOLD));   
                         document.add(permitCond2);
                     }
                     
                     if 
(!prevCondDesc.equals(permCondition.getConditionDescription())){
                         Paragraph permitCond3 =  new 
Paragraph(permCondition.getReportRef() + "    " + 
permCondition.getConditionDescription(), new Font(Font.HELVETICA, 10));   
                         document.add(permitCond3);
                     }              
                     prevActMemo = permCondition.getActivityMemo();
                     prevInterest = permCondition.getInterest();
                     prevCondDesc = permCondition.getConditionDescription();
                 }
             }                 
             //permit condition ends
             
             //Displaying Delegate, EPA name, Date/Time and Receipt Number
             document.add(new Paragraph(" "));
             document.add(new Paragraph(DELEGATE_LABEL, new 
Font(Font.HELVETICA, 9)));
             
             document.add(new Paragraph(getRwlAdminMessages().getEpaOrgName(), 
new Font(Font.HELVETICA, 9)));
             
             DateFormat dateFormat =  new SimpleDateFormat(DATE_TIME_FORMAT);
             
             document.add(new Paragraph(" "));
             document.add(new Paragraph(" "));
             document.add(new Paragraph(" "));
             
             document.add(new Paragraph(ISSUE_LABEL + dateFormat.format(new 
Date()), new Font(Font.HELVETICA, 9)));
             
             document.add(new Paragraph(RECEIPT_NUMBER_LABEL_FOR_LICENCE + 
getRwlApp().getReceipt().getReceiptNum(), new Font(Font.HELVETICA, 9)));
             document.close();

         }
         catch (Exception e) {
             context.addMessage("LicenceFileGenerationError", new 
FacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to generate the licence 
file", e.getMessage()));
             e.printStackTrace();
             return;
         }
     }

    /**
     * Generate the Notice of decision details as a PDF file.
     * In case of errors, add the error message to the context.
     * @param fileNamePath file name including the path 
     *
     */
    public void generateNoticeOfDecisionPdf(String fileNamePath) {

        Document document = new Document();

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) 
context.getExternalContext().getResponse();

        try {            
            PdfWriter writer = PdfWriter.getInstance(document, new 
FileOutputStream(fileNamePath));
            writer.setPageEvent(new FooterForPDF());

            //Generating Licence PDF
            document.open();
            
            //Generating Notice of Decision PDF
            String imageLocation = 
getAppContext().getResource(EcotrackCommonConstants.IMAGES_FOLDER + 
ND_BMP).getFile().getPath();
            Image jpg = Image.getInstance(imageLocation);
            jpg.scalePercent(30);
            document.add(jpg);
            
            Paragraph headingND =  new Paragraph(HEADING_ND, new 
Font(Font.HELVETICA, 15, Font.BOLD));
            headingND.setAlignment(Element.ALIGN_CENTER);
            document.add(headingND);
            
            Paragraph NDLabel1 =  new Paragraph(ND_LABEL1, new 
Font(Font.HELVETICA, 9, Font.ITALIC));
            NDLabel1.setAlignment(Element.ALIGN_LEFT);
            document.add(NDLabel1);
            
            document.add(new Paragraph(" "));
            
            //Permit Holder Details
            Paragraph permitHolderDetails = null;
            permitHolderDetails =  new 
Paragraph(getRwlApp().getClient().getTitle() + " " + 
getRwlApp().getClient().getFirstName() + " " + 
getRwlApp().getClient().getOtherNames() + " " + 
getRwlApp().getClient().getSurName(), new Font(Font.HELVETICA, 10));
      
            document.add(permitHolderDetails);
            document.add(new 
Paragraph(getRwlApp().getClient().getPostAddressLine1() + " " + 
(getRwlApp().getClient().getPostAddressLine2() != 
null?getRwlApp().getClient().getPostAddressLine2():""), new 
Font(Font.HELVETICA, 10)));
            document.add(new Paragraph(getRwlApp().getClient().getPostSuburb() 
+ " " + getRwlApp().getClient().getPostState() + " " + 
getRwlApp().getClient().getPostPostCode(), new Font(Font.HELVETICA, 10)));
            
            Paragraph ourRef = new Paragraph(OUR_REF + 
getRwlApp().getProject().getProjectRef(), new Font(Font.HELVETICA, 10));
            ourRef.setAlignment(Element.ALIGN_RIGHT);
            document.add(ourRef);
                         
            Paragraph stLabel = new Paragraph(DEAR_LABEL + 
getRwlApp().getClient().getTitle() + " " + 
getRwlApp().getClient().getSurName(), new Font(Font.HELVETICA, 10));
            document.add(stLabel);

            Paragraph NDLabel2 =  new Paragraph(ND_LABEL2, new 
Font(Font.HELVETICA, 10, Font.BOLD));
            document.add(NDLabel2);
            
            document.add(new Phrase(" "));
            
            DateFormat dateFormat =  new SimpleDateFormat(DATE_FORMAT);
            Paragraph NDLabel3 =  new Paragraph(ND_LABEL3_1 + 
dateFormat.format(getRwlApp().getApplicationDate()) + ND_LABEL3_2, new 
Font(Font.HELVETICA, 10));
            document.add(NDLabel3);
            
            //table starts
            Table legTable = new Table(3);
            legTable.setPadding(2);
            legTable.setSpacing(0);
            
            int headerwidthsForlegTable[] = {50, 30, 20};
            legTable.setWidths(headerwidthsForlegTable);
            legTable.setWidth(100);
            legTable.setBorderColor(Color.GRAY);
            legTable.setBorder(0);
              
            LegislativeDetails legDetails = 
getRwl().getLegislativeDetails(getRwlApp().getNewPermit().getPermitId());
            if (legDetails != null){
                Paragraph legHeader1 =  new Paragraph(PERMIT_APPLIED_FOR,  new 
Font(Font.HELVETICA, 9, Font.BOLD));
                Cell newCell = new Cell(legHeader1);
                legTable.addCell(newCell);

                Paragraph legHeader2 =  new 
Paragraph(PERMIT_NUMBER_HEADER_LABEL, new Font(Font.HELVETICA, 9, Font.BOLD));
                newCell = new Cell(legHeader2);
                legTable.addCell(newCell);
                
                Paragraph legHeader3 =  new Paragraph(DECISION_LABEL, new 
Font(Font.HELVETICA, 9, Font.BOLD));
                newCell = new Cell(legHeader3);
                legTable.addCell(newCell);

                Paragraph colValue =  new Paragraph(legDetails.getPermType(), 
new Font(Font.HELVETICA, 9));
                legTable.addCell(colValue);
                colValue =  new Paragraph(legDetails.getPermitRef(), new 
Font(Font.HELVETICA, 9));
                legTable.addCell(colValue);
                colValue =  new Paragraph(legDetails.getPermitDecision(), new 
Font(Font.HELVETICA, 9));
                legTable.addCell(colValue);
                document.add(legTable);
            }
            //table ends
            
            Paragraph NDLabel4 =  new Paragraph(ND_LABEL4, new 
Font(Font.HELVETICA, 10));
            document.add(NDLabel4);
            
            document.add(new Paragraph(" "));
            
            Paragraph NDLabel5 =  new Paragraph(ND_LABEL5, new 
Font(Font.HELVETICA, 10));
            document.add(NDLabel5);
                        
            document.add(new Paragraph(" "));
            
            Paragraph delegateLabel =  new Paragraph(DELEGATE_LABEL, new 
Font(Font.HELVETICA, 10));
            document.add(delegateLabel);
            
            document.add(new Paragraph(getRwlAdminMessages().getEpaOrgName(), 
new Font(Font.HELVETICA, 10)));
            
            Paragraph enquiriesLabel =  new Paragraph(ENQUIRIES_LABEL, new 
Font(Font.HELVETICA, 10, Font.BOLD));
            enquiriesLabel.setAlignment(Element.ALIGN_RIGHT);
            document.add(enquiriesLabel);
            Paragraph enquiriesLabel1 =  new Paragraph(EPA_ECSU, new 
Font(Font.HELVETICA, 10));
            enquiriesLabel1.setAlignment(Element.ALIGN_RIGHT);
            document.add(enquiriesLabel1);
            
            Paragraph post1 = new 
Paragraph(getRwlAdminMessages().getEpaPostAddress(), new Font(Font.HELVETICA, 
10));
            post1.setAlignment(Element.ALIGN_RIGHT);
            document.add(post1);
            
            Paragraph post2 = new 
Paragraph(getRwlAdminMessages().getEpaRegAddress1(), new Font(Font.HELVETICA, 
10));
            post2.setAlignment(Element.ALIGN_RIGHT);
            document.add(post2);
            
            Paragraph post3 = new 
Paragraph(getRwlAdminMessages().getEpaRegAddress2(), new Font(Font.HELVETICA, 
10));
            post3.setAlignment(Element.ALIGN_RIGHT);
            document.add(post3);
            
            Paragraph phoneNumberPara = new Paragraph(phoneNumber_label + 
phoneNumber, new Font(Font.HELVETICA, 10));
            phoneNumberPara.setAlignment(Element.ALIGN_RIGHT);
            document.add(phoneNumberPara);
            
            Paragraph faxNumberPara = new Paragraph(faxNumber_label + faxNumber 
, new Font(Font.HELVETICA, 10));
            faxNumberPara.setAlignment(Element.ALIGN_RIGHT);
            document.add(faxNumberPara);
            
            dateFormat =  new SimpleDateFormat(DATE_TIME_FORMAT);
            Paragraph issueLabel = new Paragraph(ISSUE_LABEL + 
dateFormat.format(new Date()), new Font(Font.HELVETICA, 10));
            issueLabel.setAlignment(Element.ALIGN_LEFT);
            document.add(issueLabel);       
            
            document.add(new Paragraph(RECEIPT_NUMBER_LABEL_FOR_LICENCE + 
getRwlApp().getReceipt().getReceiptNum(), new Font(Font.HELVETICA, 10)));
            document.close();
        }
        catch (Exception e) {
            context.addMessage("NoticeOfDecisionFileGenerationError", new 
FacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to generate the notice of 
decision file", e.getMessage()));
            e.printStackTrace();
            return;
        }
    }

    /**
     * Merges the Licence PDF file and Notice of Decision and sends the file to
     * the browser using the method, downloadFile
     * In case of errors, add the error message to the context.
     */
    public void downloadLicencePdfInline() {

        String fileNamePath = "";
        String file = EcotrackCommonConstants.TEMP_PDFS_FOLDER + 
EcotrackCommonConstants.README_FILE;
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) 
context.getExternalContext().getResponse();

        File licencePdfFile = null;
        File noticePdfFile = null;
        String fileNamePath1 = "";
        String fileNamePath2 = "";
        
        try {
            
            fileNamePath =  
getAppContext().getResource(file).getFile().getPath();

            String uploadDir = fileNamePath.substring(0, 
fileNamePath.indexOf(EcotrackCommonConstants.README_FILE));
            // create full file path and a name that includes receipt number 
and "_licence" to indicate licence file.
            fileNamePath1 = uploadDir  + 
getRwlApp().getReceipt().getReceiptNum() + "_licence" + 
EcotrackCommonConstants.RELATED_DOCUMENT_FILE_EXTENSION;
            
            generateLicencePdf(fileNamePath1);
            
            licencePdfFile = new File(fileNamePath1);
            
            // create full file path and a name that includes receipt number 
and "_ND" to indicate Notice of decision file.
            fileNamePath2 = uploadDir  + 
getRwlApp().getReceipt().getReceiptNum() + "_ND" + 
EcotrackCommonConstants.RELATED_DOCUMENT_FILE_EXTENSION;
            
            generateNoticeOfDecisionPdf(fileNamePath2);
            
            noticePdfFile = new File(fileNamePath2);
            // create full file path and a name that includes receipt number 
and "_merge" to indicate merged file.
            fileNamePath = uploadDir  + 
getRwlApp().getReceipt().getReceiptNum() + "_merge" + 
EcotrackCommonConstants.RELATED_DOCUMENT_FILE_EXTENSION;

            List<InputStream> pdfs = new ArrayList<InputStream>();
            FileInputStream fis1 = new FileInputStream(licencePdfFile);
            FileInputStream fis2 = new FileInputStream(noticePdfFile);
            
            pdfs.add(fis1);
            pdfs.add(fis2);
            OutputStream output = new FileOutputStream(fileNamePath);
            MergePDF.concatPDFs(pdfs, output, false);
            File pdfFile = new File(fileNamePath);

            // Download merged file.
            try {
                EcotrackUtils.downloadFile(response, pdfFile);
            }
            catch (IOException e) {
                context.addMessage("FileIOError", new 
FacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to download the file", 
e.getMessage()));
                e.printStackTrace();
                return;
            }
            fis1.close();
            fis2.close();
        }
        catch (Exception e) {
            context.addMessage("FileMergeError", new 
FacesMessage(FacesMessage.SEVERITY_ERROR, "Unable to merge the licence and 
notice of decision files", e.getMessage()));
            e.printStackTrace();
            return;
        }
        
        //Delete the merged file
        try {
            File pdfFile = new File(fileNamePath);
            pdfFile.delete();
            licencePdfFile.delete();
            noticePdfFile.delete();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // Prevent other JSF lifecycle phases eventually being invoked.
        // Otherwise you can get the following exception:
        // java.lang.IllegalStateException: Cannot forward after response has 
been committed.
        context.responseComplete();
    }
-------------------------------------------------------------------------
Sponsored by: SourceForge.net Community Choice Awards: VOTE NOW!
Studies have shown that voting for your favorite open source project,
along with a healthy diet, reduces your potential for chronic lameness
and boredom. Vote Now at http://www.sourceforge.net/community/cca08
_______________________________________________
iText-questions mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/itext-questions

Do you like iText?
Buy the iText book: http://www.1t3xt.com/docs/book.php
Or leave a tip: https://tipit.to/itexttipjar

Reply via email to