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.coderbd.pos.pdf.OrderReportPDF.java

public boolean genPdf() throws UnsupportedEncodingException {
    List<SupplierOrderProductReport> soprs = sor.getSupplierOrderProductReports();
    IDBuilder idBuilder = new IDBuilder();
    Font innerFont = FontFactory.getFont("Arial", BaseFont.WINANSI, BaseFont.EMBEDDED, 8, Font.NORMAL);
    Font headerFont = FontFactory.getFont("Arial", BaseFont.WINANSI, BaseFont.EMBEDDED, 8, Font.BOLD);
    try {/*from www .j  a  va  2s.  c o  m*/
        String timestamp = idBuilder.getUniqueTimeStampID();
        String filename = sor.getSupplier().getSupplierName() + "_O" + sor.getSupplierOrderId() + "_"
                + timestamp + ".pdf";
        String filePath = directory + "\\" + filename;

        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
        document.open();

        PdfPTable pdfPTable = new PdfPTable(5);

        pdfPTable.setWidthPercentage(90);
        float[] widths = { 0.40f, 0.13f, 0.15f, 0.15f, 0.17f };
        pdfPTable.addCell(new Paragraph("Product Name", headerFont));
        pdfPTable.addCell(new Paragraph("Buy Rate", headerFont));
        pdfPTable.addCell(new Paragraph("Primary Qty", headerFont));
        pdfPTable.addCell(new Paragraph("Unsold Qty", headerFont));
        pdfPTable.addCell(new Paragraph("Unsold Amount", headerFont));

        pdfPTable.setWidths(widths);
        for (SupplierOrderProductReport sopr : soprs) {

            SupplierOrderProduct sop = sopr.getSupplierOrderProduct();
            String name = sop.getSupplierProductName();
            Double rate = sop.getSupplierRate();
            Integer pQty = sop.getSupplierProductQuantity();
            Integer unQty = sopr.getUnSoldProductQuantity();
            Double unAmount = sopr.getUnSoldProductAmount();

            Paragraph nameParag = new Paragraph(name, innerFont);
            Paragraph buyRateParag = new Paragraph(rate.toString(), innerFont);
            Paragraph primaryQuantityParag = new Paragraph(pQty.toString(), innerFont);
            Paragraph unsoldQuantityParag = new Paragraph(unQty.toString(), innerFont);
            Paragraph unsoldAmountParag = new Paragraph(unAmount.toString(), innerFont);

            PdfPCell nameCell = new PdfPCell(nameParag);
            PdfPCell buyRateCell = new PdfPCell(buyRateParag);
            PdfPCell primaryQuantityCell = new PdfPCell(primaryQuantityParag);
            PdfPCell unsoldQuantityCell = new PdfPCell(unsoldQuantityParag);
            PdfPCell unsoldAmountCell = new PdfPCell(unsoldAmountParag);

            pdfPTable.addCell(nameCell);
            pdfPTable.addCell(buyRateCell);
            pdfPTable.addCell(primaryQuantityCell);
            pdfPTable.addCell(unsoldQuantityCell);
            pdfPTable.addCell(unsoldAmountCell);
        }
        document.add(getHeader());

        document.add(pdfPTable);
        document.add(getFooter());
        document.add(new Paragraph("            Report Generated: " + new Date().toString(), innerFont));
        document.close();
        return true;
    } catch (DocumentException | FileNotFoundException dex) {
        System.out.println(dex.getMessage());
        return false;
    }
}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioEstoqueProdutos(boolean valoresNegativos, File destino) {
    Document doc = new Document();
    try {/* w ww. j av  a  2 s .  co m*/
        String path = a.getRelatorio().getCanonicalPath() + destino.getName();
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        //String subTitulo = "Estoque Verificado no dia "
        //        + new SimpleDateFormat("dd/MM/yyyy HH:mm").format(Calendar.getInstance().getTime());

        String subTitulo = "Balano Geral de Estoque do perodo 01/12/2017  31/12/2017";
        inserirHead(doc,
                "Mercadinho Popular\n" + "Edvaneide Torres Vilar de Carvalho\n" + "CNPJ: 07.643.907/0001-18",
                subTitulo);

        PdfPTable table = getTableEstoqueProdutos(valoresNegativos);

        doc.add(table);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioEstoqueProdutos(boolean valoresNegativos, boolean pararLista,
        Calendar dataInicio, Calendar dataFim, List<String> codigos_retirados, double total_requisitado,
        File destino) {/* w w  w .ja v a  2s .c  o m*/
    Document doc = new Document();
    try {
        String path = a.getRelatorio().getCanonicalPath() + destino.getName();
        PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();

        //String subTitulo = "Estoque Verificado no dia "
        //        + new SimpleDateFormat("dd/MM/yyyy HH:mm").format(Calendar.getInstance().getTime());

        String data = "";
        try {
            data += OperacaoStringUtil.formatDataValor(dataInicio) + "  "
                    + OperacaoStringUtil.formatDataValor(dataFim);
        } catch (NullPointerException e) {
            data += ("01/01/" + (Calendar.getInstance().get(Calendar.YEAR) - 1)) + "  ";
            data += ("31/12/" + (Calendar.getInstance().get(Calendar.YEAR) - 1));
        }

        String subTitulo = "Balano Geral de Estoque do perodo " + data; //" 01/12/2017  31/12/2017";
        inserirHead(doc,
                "Mercadinho Popular\n" + "Edvaneide Torres Vilar de Carvalho\n" + "CNPJ: 07.643.907/0001-18",
                subTitulo);

        PdfPTable table = getTableEstoqueProdutos(valoresNegativos, pararLista, codigos_retirados,
                total_requisitado);

        doc.add(table);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioDebitoClientes(double maiorQue, File destino) {
    Document doc = new Document();
    try {//from w ww.  j  a  va 2  s.  c o m
        String path = a.getRelatorio().getCanonicalPath() + destino.getName();
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo;
        if (maiorQue == 0) {
            subTitulo = "Dbito dos Clientes \n Refernte ao dia "
                    + new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime());
        } else {
            subTitulo = "Clientes com Dbitos Maiores que "
                    + OperacaoStringUtil.formatarStringValorMoedaComDescricao(maiorQue)
                    + "\n Refernte ao dia "
                    + new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime());
        }
        inserirHead(doc, "Dbito dos Clientes", subTitulo);

        PdfPTable table = getTableDebitoClientes(maiorQue);

        doc.add(table);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioBalancoProdutos(Date inicio, Date fim, File destino) {
    Document doc = new Document();
    try {//w w  w.j  a  v a 2  s  .c o m
        String path = a.getRelatorio().getCanonicalPath() + destino.getName();
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Sada de produtos \n Refernte do dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(inicio) + " ao dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(fim);
        inserirHead(doc, "Balano de Produtos", subTitulo);

        PdfPTable table = getTableBalancoProdutos(inicio, fim);

        doc.add(table);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfDaVenda(Venda v, List<ItemDeVenda> itens, File destino) throws IOException {
    Document doc = new Document();

    try {//w w w  .j av a  2s .  c  om
        String path = a.getRelatorio().getCanonicalPath() + "/Venda_" + v.getId() + ".pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Venda Realizada no dia "
                + new SimpleDateFormat("dd/MM/yyyy HH:mm").format(v.getDia().getTime());
        try {
            inserirHead(doc, "Venda do Cliente " + v.getCliente().getNome(), subTitulo);
        } catch (NullPointerException ne) {
            inserirHead(doc, "Venda  vista ID: " + v.getId(), subTitulo);
        }

        PdfPTable table = getTableDeItens(itens);

        doc.add(table);

        Paragraph p2 = new Paragraph("Total: " + new DecimalFormat("0.00").format(v.getTotal())
                + " \n Funcionrio: " + v.getFuncionario().getNome(),
                new Font(Font.FontFamily.COURIER, 16, Font.BOLD));
        doc.add(p2);

        doc.close();
        Arquivo.copyFile(new File(path), destino);
        return destino.getAbsolutePath();
    } catch (DocumentException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfRelatorioBalancoProdutos(Date inicio, Date fim) {
    Document doc = new Document();
    try {/*from   w  w  w . jav  a 2  s . com*/
        String path = a.getRelatorio().getCanonicalPath() + "/RelatorioBalancoProdutos.pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Sada de produtos \n Refernte do dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(inicio) + " ao dia "
                + new SimpleDateFormat("dd/MM/yyyy").format(fim);
        inserirHead(doc, "Balano de Produtos", subTitulo);

        PdfPTable table = getTableBalancoProdutos(inicio, fim);

        doc.add(table);

        doc.close();
        return path;
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cs.sis.controller.gerador.GeradorPDF.java

public String gerarPdfDaVenda(Venda v, List<ItemDeVenda> itens) {
    Document doc = new Document();

    try {//from   ww w  . jav  a 2s. co m
        String path = a.getRelatorio().getCanonicalPath() + "/Venda_" + v.getId() + ".pdf";
        PdfWriter.getInstance(doc, new FileOutputStream(path));
        doc.open();
        String subTitulo = "Venda Realizada no dia "
                + new SimpleDateFormat("dd/MM/yyyy HH:mm").format(v.getDia().getTime());
        if (v.getCliente() != null) {
            inserirHead(doc, "Venda do Cliente " + v.getCliente().getNome(), subTitulo);
        } else {//venda a vista
            inserirHead(doc, "Venda  Vista", subTitulo);
        }

        PdfPTable table = getTableDeItens(itens);

        doc.add(table);

        Paragraph p2 = new Paragraph("Total: " + new DecimalFormat("0.00").format(v.getTotal())
                + " \n Funcionrio: " + v.getFuncionario().getNome(),
                new Font(Font.FontFamily.COURIER, 16, Font.BOLD));
        doc.add(p2);

        doc.close();
        return path;
    } catch (DocumentException | IOException e) {
        e.printStackTrace();
        return "";
    }

}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

public String createInvoicePDF(String imagePath, String OUTPUT_FILEPATH)
        throws FileNotFoundException, IOException, DocumentException, InterruptedException, URISyntaxException {

    float currPosition = 0;
    String sFilepath = OUTPUT_FILEPATH;
    Image image = Image.getInstance(imagePath);
    //create a paragraph
    Paragraph paragraph = new Paragraph();
    Document d = new Document(PageSize.A4_LANDSCAPE.rotate());
    PdfWriter w = PdfWriter.getInstance(d, new FileOutputStream(sFilepath));
    d.open();/*  www  .jav a 2 s . c  om*/
    PdfContentByte cb = w.getDirectContent();
    ByteArrayOutputStream stampedBuffer;
    URL resource = this.getClass().getClassLoader().getResource(ShippingConstants.INVOICE_TEMPLATE);
    File file = new File(resource.toURI());
    PdfReader templateReader = new PdfReader(new FileInputStream(file));
    stampedBuffer = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(templateReader, stampedBuffer);
    stamper.setFormFlattening(true);
    AcroFields form = stamper.getAcroFields();
    float[] columnWidths = { 1f, 1f, 1f, 3f };
    //create PDF table with the given widths
    PdfPTable table = new PdfPTable(columnWidths);
    // form.setField("field1", String.format("Form Text %d", i+1));
    form.setField("OBName", "Ragav");
    form.setField("OBCompany", "Ragav");
    form.setField("OBAddress", "2002 SW Sarazen Cr");
    form.setField("OBCity", "Bentonville");
    form.setField("OBPhone", "1234567890");
    form.setField("STName", "Ragav");
    form.setField("STCompany", "Ragav");
    form.setField("STAddress", "2002 SW Sarazen Cr");
    form.setField("STCity", "Bentonville");
    form.setField("STPhone", "1234567890");
    form.setField("itemNo", "12334535");
    form.setField("itemDesc", "Laundry Bag");
    stamper.close();
    templateReader.close();
    form = null;
    stamper.close();
    templateReader.close();
    PdfReader stampedReader = new PdfReader(stampedBuffer.toByteArray());
    PdfImportedPage page = w.getImportedPage(stampedReader, 1);
    cb.addTemplate(page, 0, currPosition);
    image.scaleAbsoluteHeight(325);
    image.scaleAbsoluteWidth(550);
    image.setRotationDegrees(270);
    image.setAbsolutePosition(450, 20);
    d.add(image);
    d.close();
    w.close();

    return sFilepath;
}

From source file:com.dandymadeproductions.ajqvue.io.PDFDataTableDumpThread.java

License:Open Source License

public void run() {
    // Class Method Instances
    String title;/*from  w  ww. j  a v  a2  s.  co m*/

    Font titleFont;
    Font rowHeaderFont;
    Font tableDataFont;
    BaseFont rowHeaderBaseFont;

    PdfPTable pdfTable;
    PdfPCell titleCell;
    PdfPCell rowHeaderCell;
    PdfPCell bodyCell;

    Document pdfDocument;
    PdfWriter pdfWriter;
    ByteArrayOutputStream byteArrayOutputStream;

    int columnCount, rowNumber;
    int[] columnWidths;
    int totalWidth;
    Rectangle pageSize;

    ProgressBar dumpProgressBar;
    HashMap<String, String> summaryListTableNameTypes;
    DataExportProperties pdfDataExportOptions;

    String currentTableFieldName;
    String currentType, currentString;

    // Setup
    columnCount = summaryListTable.getColumnCount();
    rowNumber = summaryListTable.getRowCount();
    columnWidths = new int[columnCount];

    pdfTable = new PdfPTable(columnCount);
    pdfTable.setWidthPercentage(100);
    pdfTable.getDefaultCell().setPaddingBottom(4);
    pdfTable.getDefaultCell().setBorderWidth(1);

    summaryListTableNameTypes = new HashMap<String, String>();
    pdfDataExportOptions = DBTablesPanel.getDataExportProperties();

    titleFont = new Font(pdfDataExportOptions.getFont());
    titleFont.setStyle(Font.BOLD);
    titleFont.setSize((float) pdfDataExportOptions.getTitleFontSize());
    titleFont.setColor(new BaseColor(pdfDataExportOptions.getTitleColor().getRGB()));

    rowHeaderFont = new Font(pdfDataExportOptions.getFont());
    rowHeaderFont.setStyle(Font.BOLD);
    rowHeaderFont.setSize((float) pdfDataExportOptions.getHeaderFontSize());
    rowHeaderFont.setColor(new BaseColor(pdfDataExportOptions.getHeaderColor().getRGB()));
    rowHeaderBaseFont = rowHeaderFont.getCalculatedBaseFont(false);

    tableDataFont = pdfDataExportOptions.getFont();

    // Constructing progress bar.
    dumpProgressBar = new ProgressBar(exportedTable + " Dump");
    dumpProgressBar.setTaskLength(rowNumber);
    dumpProgressBar.pack();
    dumpProgressBar.center();
    dumpProgressBar.setVisible(true);

    // Create a Title if Optioned.
    title = pdfDataExportOptions.getTitle();

    if (!title.equals("")) {
        if (title.equals("EXPORTED TABLE"))
            title = exportedTable;

        titleCell = new PdfPCell(new Phrase(title, titleFont));
        titleCell.setBorder(0);
        titleCell.setPadding(10);
        titleCell.setColspan(summaryListTable.getColumnCount());
        titleCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);

        pdfTable.addCell(titleCell);
        pdfTable.setHeaderRows(2);
    } else
        pdfTable.setHeaderRows(1);

    // Create Row Header.
    for (int i = 0; i < columnCount; i++) {
        currentTableFieldName = summaryListTable.getColumnName(i);
        rowHeaderCell = new PdfPCell(new Phrase(currentTableFieldName, rowHeaderFont));
        rowHeaderCell.setBorderWidth(pdfDataExportOptions.getHeaderBorderSize());
        rowHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        rowHeaderCell.setBorderColor(new BaseColor(pdfDataExportOptions.getHeaderBorderColor().getRGB()));
        pdfTable.addCell(rowHeaderCell);
        columnWidths[i] = Math.min(50000,
                Math.max(columnWidths[i], rowHeaderBaseFont.getWidth(currentTableFieldName + " ")));
        if (tableColumnTypeNameHashMap != null)
            summaryListTableNameTypes.put(Integer.toString(i),
                    tableColumnTypeNameHashMap.get(currentTableFieldName));
        else
            summaryListTableNameTypes.put(Integer.toString(i), "String");
    }

    // Create the Body of Data.
    int i = 0;
    while ((i < rowNumber) && !dumpProgressBar.isCanceled()) {
        dumpProgressBar.setCurrentValue(i);

        // Collecting rows of data & formatting date & timestamps
        // as needed according to the Export Properties.

        if (summaryListTable.getValueAt(i, 0) != null) {
            for (int j = 0; j < summaryListTable.getColumnCount(); j++) {
                currentString = summaryListTable.getValueAt(i, j) + "";
                currentString = currentString.replaceAll("\n", "");
                currentString = currentString.replaceAll("\r", "");
                currentType = summaryListTableNameTypes.get(Integer.toString(j));

                // Format Date & Timestamp Fields as Needed.

                if ((currentType != null) && (currentType.equals("DATE") || currentType.equals("DATETIME")
                        || currentType.indexOf("TIMESTAMP") != -1)) {
                    if (!currentString.toLowerCase(Locale.ENGLISH).equals("null")) {
                        int firstSpace;
                        String time;

                        // Dates fall through DateTime and Timestamps try
                        // to get the time separated before formatting
                        // the date.

                        if (currentString.indexOf(" ") != -1) {
                            firstSpace = currentString.indexOf(" ");
                            time = currentString.substring(firstSpace);
                            currentString = currentString.substring(0, firstSpace);
                        } else
                            time = "";

                        currentString = Utils.convertViewDateString_To_DBDateString(currentString,
                                DBTablesPanel.getGeneralDBProperties().getViewDateFormat());
                        currentString = Utils.convertDBDateString_To_ViewDateString(currentString,
                                pdfDataExportOptions.getPDFDateFormat()) + time;
                    }
                }
                bodyCell = new PdfPCell(new Phrase(currentString, tableDataFont));
                bodyCell.setPaddingBottom(4);

                if (currentType != null) {
                    // Set Numeric Fields Alignment.
                    if (currentType.indexOf("BIT") != -1 || currentType.indexOf("BOOL") != -1
                            || currentType.indexOf("NUM") != -1 || currentType.indexOf("INT") != -1
                            || currentType.indexOf("FLOAT") != -1 || currentType.indexOf("DOUBLE") != -1
                            || currentType.equals("REAL") || currentType.equals("DECIMAL")
                            || currentType.indexOf("COUNTER") != -1 || currentType.equals("BYTE")
                            || currentType.equals("CURRENCY")) {
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getNumberAlignment());
                        bodyCell.setPaddingRight(4);
                    }
                    // Set Date/Time Field Alignment.
                    if (currentType.indexOf("DATE") != -1 || currentType.indexOf("TIME") != -1
                            || currentType.indexOf("YEAR") != -1)
                        bodyCell.setHorizontalAlignment(pdfDataExportOptions.getDateAlignment());
                }

                pdfTable.addCell(bodyCell);
                columnWidths[j] = Math.min(50000,
                        Math.max(columnWidths[j], BASE_FONT.getWidth(currentString + " ")));
            }
        }
        i++;
    }
    dumpProgressBar.dispose();

    // Check to see if any data was in the summary
    // table to even be saved.

    if (pdfTable.size() <= pdfTable.getHeaderRows())
        return;

    // Create a document of the PDF formatted data
    // to be saved to the given output file.

    try {
        // Sizing & Layout
        totalWidth = 0;
        for (int width : columnWidths)
            totalWidth += width;

        if (pdfDataExportOptions.getPageLayout() == PDFExportPreferencesPanel.LAYOUT_PORTRAIT)
            pageSize = PageSize.A4;
        else {
            pageSize = PageSize.A4.rotate();
            pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
            pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));
        }

        pdfTable.setWidths(columnWidths);

        // Document
        pdfDocument = new Document(pageSize);
        byteArrayOutputStream = new ByteArrayOutputStream();
        pdfWriter = PdfWriter.getInstance(pdfDocument, byteArrayOutputStream);
        pdfDocument.open();
        pdfTemplate = pdfWriter.getDirectContent().createTemplate(100, 100);
        pdfTemplate.setBoundingBox(new com.itextpdf.text.Rectangle(-20, -20, 100, 100));
        pdfWriter.setPageEvent(this);
        pdfDocument.add(pdfTable);
        pdfDocument.close();

        // Outputting
        WriteDataFile.mainWriteDataString(fileName, byteArrayOutputStream.toByteArray(), false);

    } catch (DocumentException de) {
        if (Ajqvue.getDebug()) {
            System.out.println("Failed to Create Document Needed to Output Data. \n" + de.toString());
        }
    }
}