Example usage for com.itextpdf.text Document isOpen

List of usage examples for com.itextpdf.text Document isOpen

Introduction

In this page you can find the example usage for com.itextpdf.text Document isOpen.

Prototype

public boolean isOpen() 

Source Link

Document

Checks if the document is open.

Usage

From source file:beans.ManagedBeanReportes.java

public void inventario() throws DocumentException, IOException {
    FacesContext facexcontext = FacesContext.getCurrentInstance();
    ValueExpression vex = facexcontext.getApplication().getExpressionFactory()
            .createValueExpression(facexcontext.getELContext(), "#{managedBeanLogin}", ManagedBeanLogin.class);
    ManagedBeanLogin beanLogin = (ManagedBeanLogin) vex.getValue(facexcontext.getELContext());

    FacesContext context = FacesContext.getCurrentInstance();

    Document document = new Document(PageSize.A4, 25, 25, 75, 25);//int marginLeft,   int marginRight,   int marginTop,   int marginBottom

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    writer.setPageEvent(new ManagedBeanReportes.Watermark(""));
    if (!document.isOpen()) {
        document.open();/*from   www . ja va 2s . c  om*/
    }

    try {

        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        //String imageUrl1 = extContext.getRealPath("//resources//images/logo0002.png");
        //Image welladigital = Image.getInstance(imageUrl1);
        //welladigital.setAbsolutePosition(377f, 760f);
        //welladigital.scalePercent(40);
        //document.add(welladigital);

        //crear tabla PARA NOMBRE DEL AO
        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100);
        table.setTotalWidth(450f);
        // table.setTotalWidth(540f);
        table.setLockedWidth(true);
        float[] headerWidths = { 120, 20, 310 };
        table.setWidths(headerWidths);
        table.getDefaultCell();

        SimpleDateFormat formato = new SimpleDateFormat("EEEE dd MMMM YYYY");
        StringBuilder cadena = new StringBuilder(formato.format(fecha_inicio));

        Chunk underline = new Chunk("FECHA DE INVENTARIO:" + cadena.toString().toUpperCase(), bigFont12);
        underline.setUnderline(0.2f, -2f); //0.1 thick, -2 y-location
        PdfPCell table5 = new PdfPCell(new Paragraph(underline));
        table5.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
        table5.setColspan(3);
        table5.setBorder(Rectangle.NO_BORDER);
        table.addCell(table5);

        document.add(table);

        document.add(new Paragraph("\n", pequeFont));

        PdfPCell table2 = new PdfPCell();

        table2 = new PdfPCell(
                new Paragraph(beanLogin.getObjetoEmpleado().getTienda().getNombreTienda(), pequeFont));
        table2.setHorizontalAlignment(Paragraph.ALIGN_CENTER);
        table2.setColspan(3);
        table2.setBorder(Rectangle.NO_BORDER);
        table = new PdfPTable(3);
        table.setWidthPercentage(100);
        table.setTotalWidth(450f);
        table.setLockedWidth(true);
        table.setWidths(headerWidths);
        table.getDefaultCell();
        table.addCell(table2);
        document.add(table);

        document.add(new Paragraph("\n", pequeFont));

        document.add(traerSubtabla(beanLogin.getObjetoEmpleado().getTienda()));
        formato = new SimpleDateFormat("yyyy-MM-dd");
        cadena = new StringBuilder(formato.format(fecha_inicio));

        //document.add(traerSubtabla02(cadena.toString()));
        document.add(new Paragraph("\n", pequeFont));
        ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
        String ctxPath = ((ServletContext) ctx.getContext()).getContextPath();
        document.close();
        formato = new SimpleDateFormat("dd_MM_yyyy");
        cadena = new StringBuilder(formato.format(fecha_inicio));
        String fileName = cadena.toString();

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

    } catch (Exception de) {
        de.printStackTrace();
    }
}

From source file:com.algoboss.erp.util.report.PDFExporter.java

License:Apache License

@Override
public void export(FacesContext context, DataTable table, String filename, boolean pageOnly,
        boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor) throws IOException {
    try {//from www . j a  v  a  2  s .c o  m
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        if (preProcessor != null) {
            preProcessor.invoke(context.getELContext(), new Object[] { document });
        }

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

        document.add(exportPDFTable(context, table, pageOnly, selectionOnly, encodingType));

        if (postProcessor != null) {
            postProcessor.invoke(context.getELContext(), new Object[] { document });
        }

        document.close();

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

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.algoboss.erp.util.report.PDFExporter.java

License:Apache License

public void export(FacesContext context, DataTable table, String filename, String encodingType)
        throws IOException {
    try {//from w ww  . j  a  v a2 s.c  o  m
        Document document = new Document(PageSize.A4, 25f, 25f, 25f, 25f);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        if (!document.isOpen()) {
            document.open();
        }
        document.addAuthor("Algo Boss");
        document.addCreator("Real's HowTo");
        document.addSubject("Thanks for your support");
        document.addCreationDate();
        document.addTitle(filename);
        //document.setMargins(1f, 1f, 1f, 1f);
        //document.setPageSize(PageSize.A4);
        document.add(exportPDFTable(context, table, false, false, false, encodingType));
        //document.setMargins(1f, 1f, 1f, 1f);
        //document.setPageSize(PageSize.A4);

        document.close();

        //writePDFToResponse(context.getExternalContext(), baos, filename);
        writePDFToResponseNew(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.algoboss.erp.util.report.PDFExporter2.java

License:Apache License

public void export(FacesContext context, DataTable table, String filename, String encodingType)
        throws IOException {
    try {//from  ww  w  . j ava2 s.co m
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        if (!document.isOpen()) {
            document.open();
        }
        document.setMargins(1f, 1f, 1f, 1f);
        document.setPageSize(PageSize.A4);
        document.add(exportPDFTable(context, table, false, false, true, encodingType));
        document.setMargins(1f, 1f, 1f, 1f);
        document.setPageSize(PageSize.A4);

        document.close();

        //writePDFToResponse(context.getExternalContext(), baos, filename);
        writePDFToResponseNew(context.getExternalContext(), baos, filename);

    } catch (DocumentException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.dexter.fms.mbean.ReportsMBean.java

@SuppressWarnings("unchecked")
public void createPDF(int type, String filename, int pageType) {
    try {/*ww  w  .j ava 2  s .com*/
        FacesContext context = FacesContext.getCurrentInstance();
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FMS");
        document.addCreationDate();
        document.addCreator("FMS");
        document.addSubject("Report");
        document.addTitle(getReport_title());

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put("partner", dashBean.getUser().getPartner());
        GeneralDAO gDAO = new GeneralDAO();
        Object pSettingsObj = gDAO.search("PartnerSetting", params);
        PartnerSetting setting = null;
        if (pSettingsObj != null) {
            Vector<PartnerSetting> pSettingsList = (Vector<PartnerSetting>) pSettingsObj;
            for (PartnerSetting e : pSettingsList) {
                setting = e;
            }
        }
        gDAO.destroy();

        PdfPCell c = null;
        if (setting != null && setting.getLogo() != null) {
            Image logoImg = Image.getInstance(setting.getLogo());
            logoImg.scaleToFit(212, 51);
            c = new PdfPCell(logoImg);
        } else
            c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(getReport_title(), font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (getReport_start_dt() != null && getReport_end_dt() != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("From " + getReport_start_dt() + " to " + getReport_end_dt(), font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = exportPDFTable(type);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();
        String fileName = filename + ".pdf";

        writeFileToResponse(context.getExternalContext(), baos, fileName, "application/pdf");

        context.responseComplete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dexter.fuelcard.mbean.UtilMBean.java

public byte[] createInvoicePDF(int pageType, String title, String dateperiod, String amount, String chargeType,
        String chargeAmount, String total) {
    try {//  www  . j  a va 2s.c o m
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FUELCARD");
        document.addCreationDate();
        document.addCreator("FUELCARD");
        document.addSubject("Invoice");
        document.addTitle(title);

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        PdfPCell c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(title, font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (dateperiod != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("For " + dateperiod, font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = new PdfPTable(4);
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
        }
        font = new Font(helvetica, 8, Font.BOLDITALIC);

        pdfTable.addCell(new Paragraph("Charge Type", font)); // % per transaction or flat per license
        pdfTable.addCell(new Paragraph("Charge Amount", font)); // the amount of the charge setting

        if (chargeType.equalsIgnoreCase("Percent-Per-Tran")) {
            pdfTable.addCell(new Paragraph("Total Amount", font)); // the amount of the charge setting
        } else {
            pdfTable.addCell(new Paragraph("Total License", font)); // the amount of the charge setting
        }
        //pdfTable.addCell(new Paragraph("Description", font)); // the 
        pdfTable.addCell(new Paragraph("Amount Due", font));

        font = new Font(helvetica, 8, Font.NORMAL);
        pdfTable.addCell(new Paragraph(chargeType, font));
        pdfTable.addCell(new Paragraph(chargeAmount, font));
        pdfTable.addCell(new Paragraph(total, font));
        pdfTable.addCell(new Paragraph(amount, font));

        pdfTable.setWidthPercentage(100);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();

        return baos.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java

License:Open Source License

/**
 * The <code>MultiPageExecutor</code> method creates multi page searchable pdf using IText.
 * // ww w. j a  va  2s. c om
 * @param batchInstanceThread {@link BatchInstanceThread} thread instance of batch
 * @param imageHtmlMap {@link Map} map containing image url with corresponding hocr
 * @param isColoredPDF true for colored image pdf else otherwise
 * @param isSearchablePDF true for searchable pdf else otherwise
 * @param pdfFilePath {@link String} path where new pdf has to be created
 * @param widthOfLine Integer for line width to be used
 */
public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final Map<String, HocrPage> imageHtmlMap,
        final boolean isColoredPDF, final boolean isSearchablePDF, final String pdfFilePath,
        final int widthOfLine, final String[] pages) {
    if (imageHtmlMap != null && !imageHtmlMap.isEmpty()) {
        this.pages = new String[pages.length];
        this.pages = pages.clone();
        batchInstanceThread.add(new AbstractRunnable() {

            @Override
            public void run() {
                String pdf = pdfFilePath;
                Document document = null;
                PdfWriter writer = null;
                FileOutputStream fileOutputStream = null;
                boolean isPdfSearchable = isSearchablePDF;
                boolean isColoredImage = isColoredPDF;
                LOGGER.info("is searchable pdf: " + isPdfSearchable + ", is Colored Image: " + isColoredImage);
                try {
                    document = new Document(PageSize.LETTER, 0, 0, 0, 0);
                    fileOutputStream = new FileOutputStream(pdf);
                    writer = PdfWriter.getInstance(document, fileOutputStream);
                    document.open();
                    Set<String> imageSet = imageHtmlMap.keySet();
                    for (String imageUrl : imageSet) {
                        HocrPage hocrPage = imageHtmlMap.get(imageUrl);
                        String newImageUrl = getCompressedImage(isColoredImage, imageUrl);
                        LOGGER.info("New Image URL: " + newImageUrl);
                        addImageToPdf(writer, hocrPage, newImageUrl, isPdfSearchable, widthOfLine);
                        document.newPage();
                        (new File(newImageUrl)).delete();
                    }
                } catch (FileNotFoundException fileNotFoundException) {
                    LOGGER.error("Error occurred while creating pdf " + pdf + " : "
                            + fileNotFoundException.toString());
                } catch (DocumentException documentException) {
                    LOGGER.error(
                            "Error occurred while creating pdf " + pdf + " : " + documentException.toString());
                } finally {
                    if (document != null && document.isOpen()) {
                        document.close();
                    }
                    // Closing pdf writer
                    if (null != writer) {
                        writer.close();
                    }

                    // Closing file output stream of pdf
                    if (null != fileOutputStream) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException ioException) {
                            LOGGER.error("Error occurred while closing stream for pdf " + pdf + " : "
                                    + ioException.toString());
                        }
                    }
                }
            }
        });
    }
}

From source file:com.github.ossdevs.jhocr.converter.HocrPageProcessor.java

License:Open Source License

/**
 * This method will process the {@link com.itextpdf.text.Document} fitting the image into the documents page.
 *
 * @param document  will be processed./* w ww . j  av  a  2 s . c o  m*/
 * @param pdfWriter will be used to process the {@link com.itextpdf.text.Document}
 */
public boolean process(Document document, PdfWriter pdfWriter) {
    try {

        if (initialized) {
            document.setPageSize(getImageRectangle());

            if (!document.isOpen()) {
                document.open();
            } else {
                document.newPage();
            }

            PdfContentByte cb = pdfWriter.getDirectContentUnder();

            /**
             * This will fit the image into the documents page using the width and height from the image and fitting it into x0 and y0 of the page.
             */
            getImage().scaleToFit(getImageRectangle().getWidth(), getImageRectangle().getHeight());
            getImage().setAbsolutePosition(0, 0);

            pdfWriter.getDirectContent().addImage(getImage());

            for (HocrLine hocrLine : getHocrPage().getLines()) {
                processHocrLine(cb, hocrLine);
            }
        }

        return true;

    } catch (DocumentException e) {
        logger.error("Document could not be processed.", e);
        return false;
    }
}

From source file:com.iox.rms.mbean.UserBean.java

@SuppressWarnings("deprecation")
private byte[] generateInvoiceForCustomerPurchase(CustomerProduct cp) {
    byte[] data = null;

    if (cp != null) {
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {//w  w w . j  av  a 2 s .c om
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            writer.setPageEvent(new HeaderFooter());
            writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
            if (!document.isOpen()) {
                document.open();
            }
            document.setPageSize(PageSize.A4);
            document.addAuthor("AutoLife");
            document.addCreationDate();
            document.addCreator("AutoLife");
            document.addSubject("Invoice");
            document.addTitle("Purchase Invoice");

            PdfPTable headerTable = new PdfPTable(3);

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance()
                    .getExternalContext().getContext();
            String logo = servletContext.getRealPath("") + File.separator + "images" + File.separator
                    + "sattrak-logo.png";
            PdfPCell c = new PdfPCell(Image.getInstance(logo));
            c.setBorder(0);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);

            BaseFont helvetica = null;
            try {
                helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
            } catch (Exception e) {
            }
            Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);
            c = new PdfPCell(new Paragraph("INVOICE", font));
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            font = new Font(helvetica, 10, Font.NORMAL | Font.BOLD);
            c = new PdfPCell(new Paragraph("TRANSACTION REF. NO.: " + cp.getPurchaseTranRef(), font));
            c.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
            c.setBorder(0);
            headerTable.addCell(c);

            document.add(headerTable);

            font = new Font(helvetica, 12, Font.NORMAL | Font.BOLD);
            Paragraph p = new Paragraph("DETAILS", font);
            p.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(p);

            PdfPTable pdfTable = new PdfPTable(3);

            font = new Font(helvetica, 8, Font.BOLDITALIC);
            pdfTable.addCell(new Paragraph("INITIATED DATE", font));
            pdfTable.addCell(new Paragraph("PRODUCT", font));
            pdfTable.addCell(new Paragraph("AMOUNT", font));
            font = new Font(helvetica, 8, Font.NORMAL);
            pdfTable.addCell(
                    new Paragraph(cp.getPurchaseTransaction().getTranInitDate().toLocaleString(), font));
            pdfTable.addCell(new Paragraph(cp.getProductBooked().getDetails(), font));
            pdfTable.addCell(new Paragraph("" + cp.getPurchasedAmount(), font));
            document.add(pdfTable);

            document.close();

            data = baos.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    return data;
}

From source file:GeMSE.Popups.PopupMenuType.java

License:Open Source License

private void SaveAsPDF(java.awt.event.ActionEvent e, File file) {
    Document document = new Document(new Rectangle(_component.getSize().width, _component.getSize().height));
    try {/* w ww.ja  v  a 2  s .co m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(_component.getSize().width,
                _component.getSize().height);
        Graphics graphics = new PdfGraphics2D(template, _component.getSize().width,
                _component.getSize().height);
        _component.print(graphics);
        graphics.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (DocumentException | FileNotFoundException e2) {
    } finally {
        if (document.isOpen())
            document.close();
    }
}