Example usage for com.lowagie.text Document close

List of usage examples for com.lowagie.text Document close

Introduction

In this page you can find the example usage for com.lowagie.text Document close.

Prototype

boolean close

To view the source code for com.lowagie.text Document close.

Click Source Link

Document

Has the document already been closed?

Usage

From source file:com.orange.atk.results.logger.documentGenerator.PDFGenerator.java

License:Apache License

public void dumpInStreamactionlogger(boolean isParseErrorHappened, ActionsLogger actionlog, DocumentLogger dl) {
    long endTime = new Date().getTime();
    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = null;//  ww w. j  av  a2  s .co m
    Vector VectAction = actionlog.getActions();
    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to the outputStream
    try {
        writer = PdfWriter.getInstance(document, outputStream);
    } catch (DocumentException e1) {
        e1.printStackTrace();
        return;
    }
    writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
    // step 3: we open the document
    document.open();
    // step 4: we add a paragraph to the document
    Paragraph pLoggedMsg = new Paragraph();
    // logged messages

    for (int i = 0; i < VectAction.size(); i++) {
        Action action = (Action) VectAction.get(i);
        SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ssSSS");
        SimpleDateFormat spf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss SSS");
        String dateString = spf.format(action.getStartTime());
        pLoggedMsg.add("[" + dateString + "]  : " + action.getActionName());

        pLoggedMsg.add(Chunk.NEWLINE);

    }

    Paragraph pLastLogguedLines = new Paragraph();
    int startIndex = VectAction.size() > 5 ? VectAction.size() - 5 : 0;
    for (int i = startIndex; i < VectAction.size(); i++) {
        Action action = (Action) VectAction.get(i);
        // SimpleDateFormat formatter = new SimpleDateFormat("H:mm:ssSSS");
        SimpleDateFormat spf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss SSS");
        String dateString = spf.format(action.getStartTime());
        pLastLogguedLines.add("[" + dateString + "]  : " + action.getActionName());

        pLastLogguedLines.add(Chunk.NEWLINE);

    }

    document.addTitle("REPORT");
    document.addCreationDate();

    HeaderFooter headerPage = new HeaderFooter(new Phrase("Execution report"), false);
    HeaderFooter footerPage = new HeaderFooter(new Phrase(" - "), new Phrase(" - "));
    headerPage.setAlignment(Element.ALIGN_CENTER);
    footerPage.setAlignment(Element.ALIGN_CENTER);
    document.setHeader(headerPage);
    document.setFooter(footerPage);

    // Chapter 1 : Summary
    // Section 1 : Informations

    Chunk c = new Chunk("Summary");
    c.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c.setFont(FONT_PAR_TITLE);

    Paragraph title1 = new Paragraph(c);
    title1.setAlignment("CENTER");
    title1.setLeading(20);
    Chapter chapter1 = new Chapter(title1, 1);
    chapter1.setNumberDepth(0);

    Paragraph title11 = new Paragraph("Informations");
    Section section1 = chapter1.addSection(title11);
    Paragraph pSum = new Paragraph();
    pSum.add("Author : " + author);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Group : " + group);
    pSum.add(Chunk.NEWLINE);
    pSum.add("Script : " + script);
    pSum.add(Chunk.NEWLINE);
    SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy - hh:mm aaa");
    String dateString = formatter.format(endTime);
    pSum.add("Date : " + dateString);
    pSum.add(Chunk.NEWLINE);
    pSum.setIndentationLeft(20);
    section1.add(pSum);
    section1.add(new Paragraph(Chunk.NEXTPAGE));

    Chunk c11 = new Chunk("Executive summary");
    c11.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c11.setFont(FONT_PAR_TITLE);
    Paragraph title12 = new Paragraph(c11);
    Section section12 = chapter1.addSection(title12);
    Paragraph pExecSum = new Paragraph();
    // pExecSum.add("Value : ");
    // pExecSum.add(Chunk.NEWLINE);
    // pExecSum.add(table);
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.add("Last logged lines : ");
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.add(pLastLogguedLines);
    pExecSum.add(Chunk.NEWLINE);
    pExecSum.setIndentationLeft(20);

    section12.add(pExecSum);

    try {
        document.add(chapter1);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    // Chapter 2 : Log information
    Chunk c2 = new Chunk("Log information");
    c2.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c2.setFont(FONT_PAR_TITLE);
    Paragraph title2 = new Paragraph(c2);
    title2.setAlignment("CENTER");
    title2.setLeading(20);
    Chapter chapter2 = new Chapter(title2, 1);
    chapter2.setNumberDepth(0);

    Section section2 = chapter2.addSection("Log");
    // Add log information
    section2.add(pLoggedMsg);
    section2.add(Chunk.NEWLINE);

    // section2.add(table);
    try {
        document.add(chapter2);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    if (isParseErrorHappened) {
        document.close();
        return;
    }

    // Add generated pictures
    Chunk c3 = new Chunk("Graphics");
    c3.setBackground(ORANGE_COLOR, 200, 3f, 200f, 3f);
    c3.setFont(FONT_PAR_TITLE);
    Paragraph p3 = new Paragraph(c3);
    p3.setAlignment("CENTER");
    p3.setLeading(20);
    Chapter chapter3 = new Chapter(p3, 1);
    chapter3.setNumberDepth(0);

    // add current graph
    Map<String, PlotList> mapint = dl.getMapint();
    Set<String> cles = mapint.keySet();
    Iterator<String> it = cles.iterator();
    while (it.hasNext()) {
        String cle = (String) it.next();
        Paragraph pCPUimg = new Paragraph(cle);
        Section section31 = chapter3.addSection(pCPUimg);
        if (new File(dl.getPNGpath(cle)).exists()) {
            Image jpg1 = null;
            try {
                jpg1 = Image.getInstance(dl.getPNGpath(cle));
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (jpg1 == null) {
                Logger.getLogger(this.getClass()).warn("Error when Creating image jpg1 is null");
                return;
            }
            // jpg1.setRotationDegrees(270);
            jpg1.scalePercent(75);
            jpg1.setAlignment(Element.ALIGN_CENTER);
            section31.add(jpg1);
        }
        section31.add(new Paragraph(Chunk.NEXTPAGE));
    }

    try {
        document.add(chapter3);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.newPage();

    document.close();
    createHTMLFileactionlog(actionlog, dl);
}

From source file:com.prime.location.billing.InvoicedBillingManager.java

/**
 * Print invoice//www.  j a  va2s.  c  o  m
 */
public void printInvoice() {
    try { //catch better your exceptions, this is just an example
        FacesContext context = FacesContext.getCurrentInstance();

        Document pdf = new Document(PageSize.A4, 5f, 5f, 75f, 45f);

        String fileName = "PDFFile";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(pdf, baos);
        TableHeader event = new TableHeader();
        event.setHeader("Header Here");
        writer.setPageEvent(event);

        if (!pdf.isOpen()) {
            pdf.open();
        }

        PdfPCell cell;

        PdfPTable header = new PdfPTable(new float[] { 1, 2, 1 });
        cell = new PdfPCell(new Paragraph("INVOICE",
                FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC, Color.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);
        header.setTotalWidth(527);
        header.setLockedWidth(true);

        cell = new PdfPCell(new Phrase("Agency: " + selectedAgency.getDescription()));
        cell.setColspan(2);
        cell.setBorder(Rectangle.NO_BORDER);
        header.addCell(cell);

        cell = new PdfPCell(new Phrase("Invoice#: " + selectedInvoice.getId()));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        cell = new PdfPCell(
                new Phrase("Date: " + DateUtility.dateTimeFormat(selectedInvoice.getInvoiceDate())));
        cell.setColspan(3);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        header.addCell(cell);

        pdf.add(header);

        PdfPTable table = new PdfPTable(new float[] { 1, 3, 2, 1 });
        table.setSpacingBefore(15f);

        table.setTotalWidth(527);
        table.setLockedWidth(true);
        //table.setWidths(new int[]{3, 1, 1});

        table.getDefaultCell().setBackgroundColor(Color.LIGHT_GRAY);

        table.addCell("Date");
        table.addCell("Name");
        table.addCell("Service");
        table.addCell("Rate");

        table.getDefaultCell().setBackgroundColor(null);

        cell = new PdfPCell(new Phrase("Total(US$): "));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setColspan(3);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(selectedInvoice.getAmount())));
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBackgroundColor(Color.LIGHT_GRAY);
        table.addCell(cell);

        // There are three special rows
        table.setHeaderRows(2);
        // One of them is a footer
        table.setFooterRows(1);
        Font f = FontFactory.getFont(FontFactory.HELVETICA, 10);
        //add remaining
        for (AgencyBilling billing : selectedInvoice.getBillings()) {
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.getDefaultCell().setIndent(2);
            table.getDefaultCell().setFixedHeight(20);

            table.addCell(new Phrase(DateUtility.dateFormat(billing.getBillingDate()), f));
            table.addCell(new Phrase(billing.getPerson().getName(), f));
            table.addCell(new Phrase(billing.getTariff().getTariffType().getDescription(), f));
            cell = new PdfPCell(new Phrase(new DecimalFormat("###,###.###").format(billing.getRate()), f));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            table.addCell(cell);

        }

        pdf.add(table);

        writer.getAcroForm().setNeedAppearances(true);

        //document.add(new Phrase(TEXT));
        //Keep modifying your pdf file (add pages and more)
        pdf.close();

        writePDFToResponse(context.getExternalContext(), baos, fileName);

        context.responseComplete();

    } catch (Exception e) {
        //e.printStackTrace();          
    }
}

From source file:com.pureinfo.srm.patent.action.PatentPrintPdfAction.java

License:Open Source License

/**
 * @see com.pureinfo.ark.interaction.ActionBase#executeAction()
 *///w  w w.ja v  a  2  s . c  o  m
public ActionForward executeAction() throws PureException {
    int nYear = request.getRequiredInt("year", "");

    Rectangle rectPageSize = new Rectangle(PageSize.A4);
    rectPageSize.setBackgroundColor(Color.WHITE);
    rectPageSize.setBorderColor(Color.BLACK);
    rectPageSize = rectPageSize.rotate();
    Document doc = new Document(rectPageSize, 10, 10, 10, 10);
    doc.addTitle(nYear + "");
    doc.addAuthor("PureInfo");
    try {
        BaseFont bfontTitle = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontTitle = new Font(bfontTitle, 18, Font.NORMAL);
        Paragraph paraTitle = new Paragraph(nYear + "",
                fontTitle);
        paraTitle.setAlignment(ElementTags.ALIGN_CENTER);

        BaseFont bfontContent = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontContent = new Font(bfontContent, 10, Font.NORMAL);

        FileFactory fileFactory = FileFactory.getInstance();
        String sPath = fileFactory.lookupPathConfigByFlag(FileFactory.FLAG_DOWNLOADTEMP, true).getLocalPath();

        FileUtil.insurePathExists(sPath);
        PdfWriter.getInstance(doc, new FileOutputStream(new File(sPath, "patent.pdf")));

        doc.open();
        doc.add(paraTitle);
        doc.add(new Paragraph("   "));

        String[] arrTitles = new String[] { "", "", "", "", "", "",
                "", "", "" };
        PdfPTable pTable = new PdfPTable(arrTitles.length);
        pTable.setWidths(new int[] { 5, 10, 9, 9, 20, 15, 12, 10, 10 });

        for (int i = 0; i < arrTitles.length; i++) {
            PdfPCell pCell = new PdfPCell();
            Paragraph para = new Paragraph(arrTitles[i], fontContent);
            para.setAlignment(ElementTags.ALIGN_CENTER);

            pCell.addElement(para);
            pTable.addCell(pCell);
        }

        /**
         * 
         */
        IPatentMgr mgr = (IPatentMgr) ArkContentHelper.getContentMgrOf(Patent.class);
        List patents = mgr.findAllAuthorizedOf(nYear);
        int i = 0;
        for (Iterator iter = patents.iterator(); iter.hasNext(); i++) {
            Patent patent = (Patent) iter.next();
            this.addPatentCell(pTable, String.valueOf(i + 1), fontContent);
            this.addPatentCell(pTable, patent.getPatentSid(), fontContent);
            this.addPatentCell(pTable, ForceConstants.DATE_FORMAT.format(patent.getApplyDate()), fontContent);
            this.addPatentCell(pTable, patent.getWarrantDate() == null ? ""
                    : ForceConstants.DATE_FORMAT.format(patent.getWarrantDate()), fontContent);
            this.addPatentCell(pTable, patent.getName(), fontContent);
            this.addPatentCell(pTable, patent.getAllAuthosName(), fontContent);
            this.addPatentCell(pTable, patent.getRightPerson(), fontContent);
            this.addPatentCell(pTable, getCollegeName(patent), fontContent);
            this.addPatentCell(pTable, patent.getPatentTypeName(), fontContent);
        }

        doc.add(pTable);
        doc.close();

    } catch (DocumentException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace(System.err);
    } catch (IOException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace(System.err);
    }

    List list = new ArrayList();
    list.add(new Pair("/download/patent.pdf", ""));
    request.setAttribute("forward", list);
    return mapping.findForward("success");
}

From source file:com.qcadoo.mes.workPlans.controller.WorkPlansController.java

License:Open Source License

private void printImageToPdf(final Entity attachment, HttpServletResponse response) {
    Document document = new Document();
    try {/*  www.ja v  a 2 s  . c  o  m*/
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();

        document.setPageSize(PageSize.A4);
        pdfHelper.addMetaData(document);
        pdfHelper.addImage(document, attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT));
        document.close();
    } catch (Exception e) {
        LOG.error("Problem with printing document - " + e.getMessage());
        document.close();
        e.printStackTrace();
    }

}

From source file:com.qcadoo.plugins.qcadooExport.internal.ExportToPDFController.java

License:Open Source License

@Monitorable(threshold = 500)
@ResponseBody// w  w  w  .  j av a 2 s.co  m
@RequestMapping(value = { CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generatePdf(@PathVariable(PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier,
        @PathVariable(VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body,
        final Locale locale) {
    try {
        changeMaxResults(body);
        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);
        GridComponent grid = (GridComponent) state.getComponentByReference("grid");
        Document document = new Document(PageSize.A4.rotate());
        String date = DateFormat.getDateInstance().format(new Date());
        File file = fileService.createExportFile("export_" + grid.getName() + "_" + date + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);

        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));

        document.setMargins(40, 40, 60, 60);

        document.addTitle("export.pdf");
        pdfHelper.addMetaData(document);
        writer.createXmpMetadata();
        document.open();

        String title = translationService.translate(
                pluginIdentifier + "." + viewName + ".window.mainTab." + grid.getName() + ".header", locale);

        Date generationDate = new Date();

        pdfHelper.addDocumentHeader(document, "", title,
                translationService.translate("qcadooReport.commons.generatedBy.label", locale), generationDate);

        int columns = 0;
        List<String> exportToPDFTableHeader = new ArrayList<String>();
        for (String name : grid.getColumnNames().values()) {
            exportToPDFTableHeader.add(name);
            columns++;
        }
        PdfPTable table = pdfHelper.createTableWithHeader(columns, exportToPDFTableHeader, false);

        List<Map<String, String>> rows;
        if (grid.getSelectedEntitiesIds().isEmpty()) {
            rows = grid.getColumnValuesOfAllRecords();
        } else {
            rows = grid.getColumnValuesOfSelectedRecords();
        }

        for (Map<String, String> row : rows) {
            for (String value : row.values()) {
                table.addCell(new Phrase(value, FontUtils.getDejavuRegular7Dark()));
            }
        }
        document.add(table);
        document.close();

        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", true, false);
        return crudService.renderView(state);
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.qcadoo.report.api.pdf.PdfDocumentService.java

License:Open Source License

private void generate(final Entity entity, final Locale locale, final String filename, final Rectangle pageSize)
        throws IOException, DocumentException {
    Document document = new Document(pageSize);
    try {//w  w  w. ja v  a  2  s  .  c o  m
        FileOutputStream fileOutputStream = new FileOutputStream(
                fileService.createReportFile(filename + "." + ReportService.ReportType.PDF.getExtension()));
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        buildPdfMetadata(document, locale);
        writer.createXmpMetadata();
        document.open();
        buildPdfContent(document, entity, locale);
        document.close();
    } catch (DocumentException e) {
        LOG.error("Problem with generating document - " + e.getMessage());
        document.close();
        throw e;
    }
}

From source file:com.qcadoo.report.api.pdf.PdfDocumentWithWriterService.java

License:Open Source License

private void generate(final Entity entity, final Locale locale, final String filename, final Rectangle pageSize)
        throws IOException, DocumentException {
    Document document = new Document(pageSize);
    try {//from w  w  w.  j  a va 2s  .  co  m
        FileOutputStream fileOutputStream = new FileOutputStream(
                fileService.createReportFile(filename + "." + ReportService.ReportType.PDF.getExtension()));
        PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
        writer.setPageEvent(new PdfPageNumbering(footerResolver.resolveFooter(locale)));
        document.setMargins(40, 40, 60, 60);
        buildPdfMetadata(document, locale);
        writer.createXmpMetadata();
        document.open();
        buildPdfContent(writer, document, entity, locale);
        document.close();
    } catch (DocumentException e) {
        LOG.error("Problem with generating document - " + e.getMessage());
        document.close();
        throw e;
    }
}

From source file:com.rapidminer.gui.actions.export.ImageExporter.java

License:Open Source License

private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException {
    Component component = printableComponent.getExportComponent();
    int width = component.getWidth();
    int height = component.getHeight();
    try (FileOutputStream fs = new FileOutputStream(outputFile)) {
        switch (formatName) {
        case PDF:
            // create pdf document with slightly increased width and height
            // (otherwise the image gets cut off)
            Document document = new Document(new Rectangle(width + 5, height + 5));
            PdfWriter writer = PdfWriter.getInstance(document, fs);
            document.open();// w w w .j  a va 2s. co m
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
            component.print(g2);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
            document.close();
            break;
        case SVG:
            exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height)));
            break;
        case EPS:
            exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height)));
            break;
        default:
            // cannot happen
            break;
        }
    } catch (Exception e) {
        throw new ImageExportException(
                I18N.getMessage(I18N.getUserErrorMessagesBundle(), "error.image_export.export_failed"), e);
    }
}

From source file:com.safetys.framework.jmesa.view.pdfp.PdfPViewExporter.java

License:Apache License

public void export() throws Exception {
    com.lowagie.text.Document document = new com.lowagie.text.Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);
    document.open();// w w w.j  a va2 s. co m
    PdfPView pdfView = (PdfPView) getView();
    document.add(pdfView.getTableCaption());
    document.add(pdfView.render());
    document.close();
    HttpServletResponse response = getResponse();
    responseHeaders(response);
    ServletOutputStream out = response.getOutputStream();
    baos.writeTo(out);
    out.flush();
}

From source file:com.sapienter.jbilling.server.invoice.PaperInvoiceBatchBL.java

License:Open Source License

/**
 * Takes a list of invoices and replaces the individual PDF files for one
 * single PDF in the destination directory.
 * @param destination/*from   w ww  .j a va2s . com*/
 * @param prefix
 * @param entityId
 * @param invoices
 * @throws PdfFormatException
 * @throws IOException
 */
public void compileInvoiceFiles(String destination, String prefix, Integer entityId, Integer[] invoices)
        throws DocumentException, IOException {

    String filePrefix = Util.getSysProp("base_dir") + "invoices/" + entityId + "-";
    String outFile = destination + prefix + "-batch.pdf";

    int pageOffset = 0;
    ArrayList master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    for (int f = 0; f < invoices.length; f++) {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(filePrefix + invoices[f] + "-invoice.pdf");
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int numberOfPages = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0)
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            master.addAll(bookmarks);
        }
        pageOffset += numberOfPages;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, new FileOutputStream(outFile));
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < numberOfPages;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        PRAcroForm form = reader.getAcroForm();
        if (form != null)
            writer.copyAcroForm(reader);

        //release and delete 
        writer.freeReader(reader);
        reader.close();
        File file = new File(filePrefix + invoices[f] + "-invoice.pdf");
        file.delete();
    }
    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    if (document != null) {
        document.close();
    } else {
        LOG.warn("document == null");
    }

    LOG.debug("PDF batch file is ready " + outFile);
}