Example usage for com.itextpdf.text Document open

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

Introduction

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

Prototype

boolean open

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

Click Source Link

Document

Is the document open or not?

Usage

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 {//from   w ww . j av a 2  s.  c o 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());
        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 ww .j  ava2 s .  c  om*/
        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   w  w w. j  a  v  a2s  .  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());
        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();
    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);/*from   w  w w. java2  s .  c o m*/
    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;/* w w w . ja  v a2  s  . com*/

    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());
        }
    }
}

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

License:Open Source License

public void run() {
    // Class Method Instances
    String title;/*from  w ww.  ja v  a  2s  .c o  m*/
    PdfPTable pdfTable;
    PdfPCell titleCell, rowHeaderCell, bodyCell;
    Document pdfDocument;
    PdfWriter pdfWriter;
    ByteArrayOutputStream byteArrayOutputStream;

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

    MyJSQLView_ProgressBar dumpProgressBar;
    HashMap<String, String> summaryListTableNameTypes;
    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.
    rowNumber = summaryListTable.getRowCount();
    dumpProgressBar = new MyJSQLView_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 (tableColumnTypeHashMap != null)
            summaryListTableNameTypes.put(Integer.toString(i),
                    tableColumnTypeHashMap.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().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 = MyJSQLView_Utils.convertViewDateString_To_DBDateString(currentString,
                                DBTablesPanel.getGeneralDBProperties().getViewDateFormat());
                        currentString = MyJSQLView_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 (MyJSQLView.getDebug()) {
            System.out.println("Failed to Create Document Needed to Output Data. \n" + de.toString());
        }
    }
}

From source file:com.datamyne.charts.AlmostThereDemo.java

License:Apache License

/**
 * Creates PDf file./*from  w  ww.  j a v  a2s  .  co  m*/
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();

        //create PdfContentByte
        //if you work with this object, you write to
        //the top most layer, meaning anything behind
        //will be clipped
        PdfContentByte contentByte = writer.getDirectContent();
        //create PdfTemplate from PdfContentByte
        PdfTemplate template = contentByte.createTemplate(width, height);
        //create Graphics2D from PdfTemplate
        Graphics2D g2 = template.createGraphics(width, height, new DefaultFontMapper());
        //setup the drawing area
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        //pass the Graphics2D and drawing area to JFreeChart
        chart.draw(g2, r2D, null);
        g2.dispose(); //always dispose this
        //add the PdfTemplate to the PdfContentByte
        contentByte.addTemplate(template, 0, 300);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.FinallyDemo.java

License:Apache License

/**
 * Creates PDf file.// w ww .ja v a2 s .c o m
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //get dummy text
        String text = getText();
        //create text font
        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFamily.TIMES_ROMAN, 10.0f);

        //add text before
        document.add(new Paragraph(new Chunk(text, font)));

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();

        //create PdfContentByte
        //if you work with this object, you write to
        //the top most layer, meaning anything behind
        //will be clipped
        PdfContentByte contentByte = writer.getDirectContent();
        //create PdfTemplate from PdfContentByte
        PdfTemplate template = contentByte.createTemplate(width, height);
        //create Graphics2D from PdfTemplate
        Graphics2D g2 = template.createGraphics(width, height, new DefaultFontMapper());
        //setup the drawing area
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        //pass the Graphics2D and drawing area to JFreeChart
        chart.draw(g2, r2D, null);
        g2.dispose(); //always dispose this

        //create Image from PdfTemplate
        Image image = Image.getInstance(template);
        document.add(image);

        //add text after
        document.add(new Paragraph(new Chunk(text, font)));

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.FixingUglyDemoByScaling.java

License:Apache License

/**
 * Creates PDf file./*w w  w  .  j  a  v  a2s .  c o m*/
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        float fWidth = 0.6f * width;
        float fHeight = 0.6f * height;
        JFreeChart chart = getChart();
        BufferedImage bufferedImage = chart.createBufferedImage(width, height);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        image.scaleAbsolute(fWidth, fHeight);
        document.add(image);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.datamyne.charts.UglyDemo.java

License:Apache License

/**
 * Creates PDf file./*from   ww w  .j a v a 2s . c  o  m*/
 * @param outputStream {@link OutputStream}.
 * @throws DocumentException
 * @throws IOException
 */
public void create(OutputStream outputStream) throws DocumentException, IOException {
    Document document = null;
    PdfWriter writer = null;

    try {
        //instantiate document and writer
        document = new Document();
        writer = PdfWriter.getInstance(document, outputStream);

        //open document
        document.open();

        //add image
        int width = 300;
        int height = 300;
        JFreeChart chart = getChart();
        BufferedImage bufferedImage = chart.createBufferedImage(width, height);
        Image image = Image.getInstance(writer, bufferedImage, 1.0f);
        document.add(image);

        //release resources
        document.close();
        document = null;

        writer.close();
        writer = null;
    } catch (DocumentException de) {
        throw de;
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        //release resources
        if (null != document) {
            try {
                document.close();
            } catch (Exception ex) {
            }
        }

        if (null != writer) {
            try {
                writer.close();
            } catch (Exception ex) {
            }
        }
    }
}