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.github.hossman.PdfShrinker.java

License:Apache License

public static void main(String args[]) throws Exception {
    if (1 != args.length) {
        System.err.println("Run this app with a single command line PDF filename");
        System.err.println("The specified file will be read, and a shrunk version written to stdout");
        System.err.println("ie:   java -jar pdf-shrinker.jar big.pdf > small.pdf");
        System.exit(-1);/*from   ww  w.  j  a  va 2 s.c  o m*/
    }

    Document document = new Document();
    PdfSmartCopy copy = new PdfSmartCopy(document, System.out);
    copy.setCompressionLevel(9);
    copy.setFullCompression();
    document.open();
    PdfReader reader = new PdfReader(args[0]);
    List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader);
    int pages = reader.getNumberOfPages();
    for (int i = 0; i < pages; i++) {
        PdfImportedPage page = copy.getImportedPage(reader, i + 1);
        copy.addPage(page);
    }
    copy.freeReader(reader);
    reader.close();
    copy.setOutlines(bookmarks);
    document.close();
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void GeneraPDF(ResultSet Resultados) throws Exception {

    ResultSetMetaData metaData = Resultados.getMetaData();
    Object[] Columnas = new Object[metaData.getColumnCount()];

    String encabezado = "Reportes del Sistema Administrativo" + "\n" + "REGISTROS ACTUALES EN AL BASE DE DATOS"
            + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n";
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));

    Font fuente = new Font(Font.getFamily("ARIAL"), 12, Font.BOLD);

    String choro = "Reporte por fecha de los modulos\n" + "de catalogo" + "\n" + "Systema Administrativo" + "\n"
            + "\n" + "\n" + "\n";

    Image imagen = Image.getInstance(System.getProperty("user.dir") + "/Image/logo.png");
    imagen.setAlignment(Image.TEXTWRAP);

    try {/*ww w  . ja v a2  s  . c  o  m*/
        Paragraph linea = new Paragraph(encabezado, fuente);
        Phrase para = new Phrase(choro);
        Paragraph fecha = new Paragraph(date + "\n" + "\n");

        PdfPTable tabla = new PdfPTable(Columnas.length);
        tabla.setWidthPercentage(100);

        //Document documento = new Document(PageSize.LETTER);
        Document documento = new Document(PageSize.A4.rotate(), 50, 50, 100, 72);
        File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
        if (!Dir.exists()) {
            Dir.mkdirs();
        }

        String file = System.getProperty("user.dir") + "/Reportes/" + metaData.getTableName(1) + " " + date
                + ".pdf";

        PdfWriter.getInstance(documento, new FileOutputStream(file));

        documento.open();
        documento.add(imagen);
        documento.add(linea);
        documento.add(para);
        documento.add(fecha);

        for (int x = 0; x < Columnas.length; x++) {
            PdfPCell Celda = new PdfPCell(new Paragraph(metaData.getColumnName(x + 1),
                    FontFactory.getFont("arial", 9, Font.BOLD, BaseColor.RED)));
            Celda.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabla.addCell(Celda);
        }

        while (Resultados.next()) {
            for (int x = 0; x < Columnas.length; x++) {
                //if(Resultados.getObject(x+1).getClass().getSimpleName().equals("Integer"))
                PdfPCell Celda = new PdfPCell(new Paragraph(String.valueOf(Resultados.getObject(x + 1)),
                        FontFactory.getFont("arial", 9, BaseColor.BLACK)));
                Celda.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabla.addCell(Celda);
            }
        }

        documento.add(tabla);
        documento.close();
    } catch (DocumentException e) {
        Log.SaveLog(e.toString());
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        Log.SaveLog(e.toString());
        JOptionPane.showMessageDialog(null, e.getMessage(), "error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void CreateTablePDF(JTable tabla) {
    boolean shapes = false;
    Document document = new Document();
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));
    File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
    if (!Dir.exists()) {
        Dir.mkdirs();// w  ww .j  a v a 2s. com
    }
    try {
        PdfWriter writer;
        if (shapes) {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        } else {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(500, 500);
        Graphics2D g2;
        if (shapes) {
            g2 = tp.createGraphicsShapes(500, 500);
        } else {
            g2 = tp.createGraphics(500, 500);
        }

        g2.dispose();
        cb.addTemplate(tp, 30, 300);
    } catch (Exception e) {
        Log.SaveLog(e.toString());
    }
    document.close();
}

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

License:Open Source License

/**
 * This is the old <code>convert()</code> method, almost untouched.<br>
 * This method will be used if {@link #pdfFormat} is not set.
 *
 * @return true if the conversion was successful.
 *///from w  ww. ja  v a2 s  . c o  m
private boolean convertSimple() {
    boolean result = false;

    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;
}

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

License:Open Source License

/**
 * @param pdfXConformance determines into which format the PDF-X will be converted.
 * @return true if the conversion was successful.
 *///  w ww  . j av  a2 s  .  c  o  m
private boolean convertToPDFX(int pdfXConformance) {
    boolean result = false;
    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());
        writer.setPDFXConformance(pdfXConformance);

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

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

License:Open Source License

/**
 * @param pdfConformanceLevel determines into which format the PDF-A&/B will be converted.
 * @return true if the conversion was successful.
 *//*from  w  w  w.j a  va2s . co  m*/
private boolean convertToPDFA(PdfAConformanceLevel pdfConformanceLevel) {
    boolean result = false;
    Document document = new Document();

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    if (classLoader == null) {
        classLoader = Class.class.getClassLoader();
    }

    try {
        PdfAWriter writer = PdfAWriter.getInstance(document, getOutputStream(), pdfConformanceLevel);
        writer.createXmpMetadata();

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        InputStream is = this.getClass().getResourceAsStream("/sRGB.profile");

        ICC_Profile icc = ICC_Profile.getInstance(is);
        writer.setOutputIntents(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE, "http://www.color.org",
                "sRGB IEC61966-2.1", icc);

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

From source file:com.github.sgelb.sldownloader.model.Pdf.java

License:Open Source License

public void mergePdfs() throws DocumentException, IOException {
    String title = book.getPdfTitle() + ".pdf";
    File saveFile = new File(saveFolder, title);

    int count = 1;
    while (saveFile.exists()) {
        title = book.getPdfTitle() + "_" + count++ + ".pdf";
        saveFile = new File(saveFolder, title);
    }/*from w  w w.j av a2 s  .c o  m*/
    book.setInfo("saveFile", saveFile.toString());

    Document document = new Document();
    PdfCopy destPdf = new PdfCopy(document, new FileOutputStream(saveFile));
    document.open();
    PdfReader reader;
    int page_offset = 0;
    int n;
    ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>();
    List<HashMap<String, Object>> tmp;

    count = 1;
    System.out.println("Start mergin\u2026");
    for (File srcPdf : src) {

        if (Thread.interrupted()) {
            return;
        }

        System.out.print(":: " + count++ + "/" + src.size());
        reader = new PdfReader(srcPdf.toString());

        tmp = SimpleBookmark.getBookmark(reader);
        if (tmp != null) {
            SimpleBookmark.shiftPageNumbers(tmp, page_offset, null);
            bookmarks.addAll(tmp);
        }

        n = reader.getNumberOfPages();
        page_offset += n;
        for (int page = 0; page < n;) {
            destPdf.addPage(destPdf.getImportedPage(reader, ++page));
        }
        destPdf.freeReader(reader);
        reader.close();
        System.out.println(" succeed.");
    }
    if (!bookmarks.isEmpty()) {
        destPdf.setOutlines(bookmarks);
    }

    if (book.getInfo("author") != null)
        document.addAuthor(book.getInfo("author"));
    if (book.getInfo("title") != null)
        document.addTitle(book.getInfo("title"));
    if (book.getInfo("subtitle") != null)
        document.addSubject(book.getInfo("subtitle"));
    document.close();

    System.out.println("Merge complete. Saved to " + saveFile);
}

From source file:com.github.ukase.bulk.BulkRenderTask.java

License:Open Source License

private void mergeSubTasksPdfs() {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();// w  ww.java  2 s  .  c  o  m
        PdfContentByte cb = writer.getDirectContent();

        appendPdfs(document, writer, cb);

        document.close();
        pdf = baos.toByteArray();
    } catch (IOException | DocumentException e) {
        log.warn("Cannot bulk pdfs", e);
    } finally {
        registerResult();
    }
}

From source file:com.github.wolfposd.imsqti2pdf.PDFCreator.java

License:Open Source License

public void createPDF(String outputFile, ArrayList<Question> qlist, boolean showCorrectAnswer,
        PageCounter pagecounter, int maximumPageNumber, String inputFolder)
        throws DocumentException, IOException {
    _inputFolder = inputFolder;//from w  ww. j  av  a 2  s  .co  m
    Document document = new Document(PageSize.A4, 50, 50, 70, 50);
    PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));

    pdfwriter.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    pdfwriter.setPageEvent(new HeaderFooter(maximumPageNumber));

    if (pagecounter != null) {
        pdfwriter.setPageEvent(pagecounter);
    }

    document.open();

    Paragraph p = new Paragraph();
    // p.setSpacingBefore(SPACING);
    p.setSpacingAfter(SPACING);
    p.setIndentationLeft(INDENTATION);

    writeQuestions(p, document, showCorrectAnswer, qlist);

    document.close();

}

From source file:com.gp.cong.logisoft.reports.LclExportVoyageNotificationPdf.java

public void createPdf(String realPath, String outputFileName, Long notificationId, String companyName,
        LclFileNumber fileNumber) throws DocumentException, IOException, Exception {
    LclExportNotiFicationForm lclExportNotiFicationForm = new LclExportsVoyageNotificationDAO()
            .getNotificationDetail(notificationId);
    LclSsDetail lclSsDetail = null;//from w w w. j  ava  2  s  .  c om
    String pod = "", finalDest = "";
    String voyageHeading = "Voyage Notification";

    if (lclExportNotiFicationForm != null) {
        lclSsDetail = new LclSsDetailDAO().findByTransMode(lclExportNotiFicationForm.getHeaderId(), "V");
        if (lclSsDetail != null) {
            pod = new LclUtils().getConcatenatedOriginByUnlocation(lclSsDetail.getArrival());
            finalDest = new LclUtils()
                    .getConcatenatedOriginByUnlocation(lclSsDetail.getLclSsHeader().getDestination());
        }
    }
    companyCode = new SystemRulesDAO().getSystemRules("CompanyCode");
    String path = LoadLogisoftProperties.getProperty(
            companyCode.equalsIgnoreCase("03") ? "application.image.logo" : "application.image.econo.logo");

    Document document = new Document(PageSize.A4);
    PdfWriter.getInstance(document, new FileOutputStream(outputFileName));
    document.open();
    document.add(imageBlock(realPath, path));
    document.add(headerPage(voyageHeading));
    document.add(informationBlock(companyName, pod, finalDest));
    document.add(changesBlock(lclSsDetail, lclExportNotiFicationForm));
    document.add(containerBlock(companyName, finalDest, fileNumber, lclExportNotiFicationForm));
    document.add(reasonBlock(lclExportNotiFicationForm));
    document.add(footerBlock());
    document.close();
}