Example usage for com.itextpdf.text Document close

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

Introduction

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

Prototype

boolean close

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

Click Source Link

Document

Has the document already been closed?

Usage

From source file:com.devox.GUI.PDF.ExportarAPDF.java

public void crearApto(File file) {
    try {//from   w  w w  .  j  av  a 2  s .  c o m
        Document document = new Document(PageSize.A4);
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina event = new CabeceraPieDePagina();
        w.setPageEvent(event);
        document.setMargins(50, 50, 100, 220);
        document.newPage();
        document.add(setUpInformationTarimas());
        //            PdfPTable t = createTable();
        //            addProductos(model, t);
        //            document.add(t);
        //
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
        Log.print(ex);
    }
}

From source file:com.devox.GUI.PDF.ExportarAPDF.java

public void crearTarimas(File file) {
    try {/*from w  w  w  .  j  av  a 2 s .c  o m*/
        Document document = new Document(PageSize.A4.rotate());
        file.createNewFile();
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        setLogo();
        CabeceraPieDePagina2 event = new CabeceraPieDePagina2();
        w.setPageEvent(event);
        document.setMargins(50, 50, 100, 50);
        document.newPage();
        document.add(setUpInformationTarimas());
        PdfPTable t = createTableTarimas();
        addProductosTarimas(t);
        document.add(t);
        //
        document.close();
    } catch (Exception ex) {
        Log.print(ex);
        Log.print(ex);
    }
}

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

@SuppressWarnings("unchecked")
public void createPDF(int type, String filename, int pageType) {
    try {/*from  w w w . ja  v  a 2  s.  co  m*/
        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 {// w  w w .  ja va2s .c  om
        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.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

public InputStream generateBlockTitleToPDF(InputStream inputStream) throws IOException, DocumentException {

    File tmpDir = com.google.common.io.Files.createTempDir();
    File blockTitleFile = new File(tmpDir, inputStream.toString());

    ResourceBundle bundle = ResourceBundle.getBundle(BASE_NAME, pLocale);

    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(blockTitleFile));
    document.open();/*from  w w w .  java2s . c o m*/

    // Main paragraph
    Paragraph preface = new Paragraph();
    generateHeader(preface, bundle);
    generateTable(preface, bundle);
    addEmptyLine(preface, 1);
    if (!instanceAttributes.isEmpty()) {
        generateAttribute(preface, bundle);
        addEmptyLine(preface, 1);
    }
    if (workflow != null) {
        generateLyfeCycleState(preface, bundle);
    }

    document.add(preface);

    addMetaData(document);

    document.close();

    tmpDir.deleteOnExit();

    // Merge the pdf generated with the pdf given in the input stream
    //TODO: use PdfStamper to insert into the existing pdf.
    return mergePdfDocuments(new FileInputStream(blockTitleFile), inputStream);

}

From source file:com.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

public static InputStream mergePdfDocuments(InputStream input1, InputStream input2) {

    try {//from www.  ja  va  2  s  .co m
        File tmpDir = com.google.common.io.Files.createTempDir();
        File tmpCopyFile = new File(tmpDir, TEMP_FILE_NAME);
        InputStream[] files = { input1, input2 };

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, new FileOutputStream(tmpCopyFile));
        doc.open();
        PdfReader pdfReader;

        int n;
        // TODO check for resources to be closed
        for (InputStream file : files) {
            pdfReader = new PdfReader(file);
            n = pdfReader.getNumberOfPages();
            for (int page = 0; page < n;) {
                copy.addPage(copy.getImportedPage(pdfReader, ++page));
            }
        }

        doc.close();

        tmpDir.deleteOnExit();

        return new FileInputStream(tmpCopyFile);
    } catch (Exception e) {
        LOGGER.log(Level.INFO, null, e);
    }

    return null;
}

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

License:Open Source License

/**
 * This method creates multi page pdf using IText.
 * /* w w  w.java 2 s . c om*/
 * @param batchInstanceThread {@link BatchInstanceThread}
 * @param pages11 {@link String}
 * @param widthOfPdfPage int
 * @param heightOfPdfPage int
 */
public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final String[] pages11,
        final int widthOfPdfPage, final int heightOfPdfPage) {
    if (pages11 != null && pages11.length > 0) {
        this.pages = new String[pages11.length];
        this.pages = pages11.clone();
        batchInstanceThread.add(new AbstractRunnable() {

            @Override
            public void run() {
                String pdf = pages[pages.length - 1];
                Document document = null;
                PdfWriter writer = null;
                RandomAccessFileOrArray randomAccessArray = null;
                try {
                    document = new Document(PageSize.LETTER, 0, 0, 0, 0);
                    writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
                    document.open();
                    int comps = 1;
                    int totalTiffImages = pages.length - 1;
                    int index = 0;
                    while (index < totalTiffImages) {
                        randomAccessArray = new RandomAccessFileOrArray(pages[index]);
                        comps = TiffImage.getNumberOfPages(randomAccessArray);
                        // Conversion statement
                        for (int tiffPageNumber = 0; tiffPageNumber < comps; ++tiffPageNumber) {
                            Image img = TiffImage.getTiffImage(randomAccessArray, tiffPageNumber + 1);
                            img.scaleToFit(widthOfPdfPage, heightOfPdfPage);
                            document.add(img);
                            document.newPage();
                        }
                        index++;
                    }
                } catch (Exception e) {
                    LOGGER.error("Error while creating pdf using iText" + e.getMessage(), e);
                    //pdf = null;
                } finally {
                    try {
                        if (document != null) {
                            document.close();
                        }
                        if (writer != null) {
                            writer.close();
                        }
                        if (randomAccessArray != null) {
                            randomAccessArray.close();
                        }
                    } catch (Exception e) {
                        LOGGER.error("Error while closing I/O streams for write PDF. " + e.getMessage());
                    }
                }
            }
        });
    }
}

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.
 * // w ww. j  a va2 s. c o  m
 * @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.ephesoft.dcma.util.PDFUtil.java

License:Open Source License

/**
 * The <code>closePassedStream</code> method closes the stream passed.
 * //ww  w .  j  a  v  a2 s.  c o  m
 * @param reader {@link PdfReader}
 * @param document {@link Document}
 * @param contentByte {@link PdfContentByte}
 * @param writer {@link PdfWriter}
 * @param fileInputStream {@link FileInputStream}
 * @param fileOutputStream {@link FileOutputStream}
 * @throws IOException {@link} if unable to close input or output stream
 */
private static void closePassedStream(final PdfReader reader, final Document document,
        final PdfContentByte contentByte, final PdfWriter writer, final FileInputStream fileInputStream,
        final FileOutputStream fileOutputStream) throws IOException {
    if (null != reader) {
        reader.close();
    }
    if (null != document) {
        document.close();
    }
    if (null != contentByte) {
        contentByte.closePath();
    }
    if (null != writer) {
        writer.close();
    }
    if (null != fileInputStream) {
        fileInputStream.close();
    }

    if (null != fileOutputStream) {
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

From source file:com.equiworx.util.Main.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*  w ww. j a va 2 s. c  o m*/

    txt1 = (TextView) findViewById(R.id.textView1);

    try {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document);
        //createImage();
        document.close();

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