Example usage for com.lowagie.text Document open

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

Introduction

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

Prototype

boolean open

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

Click Source Link

Document

Is the document open or not?

Usage

From source file:demo.dwr.simple.UploadDownload.java

License:Apache License

/**
 * Generates a PDF file with the given text
 * http://itext.ugent.be/itext-in-action/
 * @return A PDF file as a byte array/* w  w w.j  av  a  2 s  .co  m*/
 */
public FileTransfer downloadPdfFile(String contents) throws Exception {
    if (contents == null || contents.length() == 0) {
        contents = "[BLANK]";
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    // ?itext-asian
    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    // ?WINDOW c:\windows\Fonts\xxx.ttf
    // ?classpath: /src/main/resources/fonts/simsong.ttf

    Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents, fontChinese));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
}

From source file:desktopbugtracker.export.PdfInitializer.java

License:Open Source License

public Document getDocument() throws PdfExportException {
    Document document = null;
    try {//www .j a  v a2  s.c om
        document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
    } catch (DocumentException ex) {
        throw new PdfExportException(ex);
    } catch (FileNotFoundException ex) {
        throw new PdfExportException(ex);
    }
    return document;
}

From source file:dinamica.AbstractPDFOutput.java

License:LGPL

/**
 * Receives a byte buffer that should be filled with resulting PDF.
 * @param data Data module that provides recordsets to this output module
 * @param buf Buffer to print PDF, then used to send to browser
 * @throws Throwable/*from   www.j  a v  a  2s  .c  om*/
 */
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //pdf objects
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);

    //header
    HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false);
    header.setBorder(Rectangle.BOTTOM);
    header.setAlignment(Rectangle.ALIGN_CENTER);
    doc.setHeader(header);

    //footer
    HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true);
    footer.setBorder(Rectangle.TOP);
    footer.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.setFooter(footer);

    //pagesize
    doc.setPageSize(PageSize.LETTER);

    doc.open();

    //title
    Paragraph t = new Paragraph(getReportTitle(), new Font(Font.HELVETICA, 18f));
    t.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(t);

    //paragraph
    Paragraph p = new Paragraph("Hello World");
    p.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(p);

    doc.close();
    docWriter.close();

}

From source file:domain.reports.menu.PDFReportMenu.java

License:LGPL

@Override
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //inicializar documento: tamano de pagina, orientacion, margenes
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);
    doc.setPageSize(PageSize.LETTER.rotate());
    doc.setMargins(30, 30, 30, 40);/*from   w  w w  . j  a v a 2 s.co  m*/

    doc.open();

    //crear fonts por defecto
    tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD);
    tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL);

    //definir pie de pagina del lado izquierdo
    String footerText = this.getFooter(); //read it from config.xml or web.xml
    String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm");

    //crear template (objeto interno de IText) y manejador de evento 
    //para imprimir el pie de pagina
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb = docWriter.getDirectContent();
    tpl = cb.createTemplate(20, 14);
    docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate));

    //titulo - lo lee de config.xml por defecto
    reportTitle = getReportTitle();
    Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD));
    t.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.add(t);

    //logo
    img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false));
    img.scalePercent(100);
    float imgY = doc.top() - img.getHeight();
    float imgX = doc.left();
    img.setAbsolutePosition(imgX, imgY);
    doc.add(img);

    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));
    //blank line
    doc.add(new Paragraph(" "));

    //for each master record print a master/detail section
    MasterDetailReader dataobj = (MasterDetailReader) data;
    Recordset master = dataobj.getRecordset("master");
    master.top();
    while (master.next()) {
        //blank line
        doc.add(new Paragraph(" "));

        //print master section
        doc.add(getGroupMaster(master));

        //print detail section
        doc.add(getGroupDetail(master, dataobj.getDetail(master)));

    }

    //print grand total
    doc.add(new Paragraph(" "));

    doc.close();
    docWriter.close();

}

From source file:dr.app.tracer.analysis.TemporalAnalysisFrame.java

License:Open Source License

public final void doExportPDF() {
    FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE);

    dialog.setVisible(true);/*  w  w w .j av a2  s.  c o  m*/
    if (dialog.getFile() != null) {
        File file = new File(dialog.getDirectory(), dialog.getFile());

        Rectangle2D bounds = temporalAnalysisPlotPanel.getExportableComponent().getBounds();
        Document document = new Document(
                new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
        try {
            // step 2
            PdfWriter writer;
            writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // step 3
            document.open();
            // step 4
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
            Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(),
                    new DefaultFontMapper());
            temporalAnalysisPlotPanel.getExportableComponent().print(g2d);
            g2d.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        document.close();
    }
}

From source file:dr.app.tracer.application.TracerFrame.java

License:Open Source License

public final void doExportPDF() {
    FileDialog dialog = new FileDialog(this, "Export PDF Image...", FileDialog.SAVE);

    dialog.setVisible(true);//from  w w  w. j a v  a  2 s . c o  m
    if (dialog.getFile() != null) {
        File file = new File(dialog.getDirectory(), dialog.getFile());

        Rectangle2D bounds = tracePanel.getExportableComponent().getBounds();
        Document document = new Document(
                new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
        try {
            // step 2
            PdfWriter writer;
            writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // step 3
            document.open();
            // step 4
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
            Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(),
                    new DefaultFontMapper());
            tracePanel.getExportableComponent().print(g2d);
            g2d.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de, "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e, "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        document.close();
    }
}

From source file:Driver.RunTestCases.java

License:Open Source License

public void generateReport() {

    File file = new File("Report1.pdf");
    FileOutputStream fileout = null;
    try {//  ww w. j av a 2s  .c  o m
        fileout = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, fileout);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.addAuthor("AGTT");
    document.addTitle("AGTT Report");

    document.open();
    Boolean status = true;
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("Results.txt"));
        String line = null;
        String testCase = null;
        Chunk chunk = null;
        int index = 0;
        List list = new List();
        while ((line = reader.readLine()) != null) {
            if (line.contains("Case")) {

                if (index > 0) {
                    System.out.println(line + status + list.size());
                    if (status == false) {
                        chunk.setBackground(Color.RED);
                    }
                    if (status == true) {
                        chunk.setBackground(Color.GREEN);
                    }
                    document.add(chunk);
                    document.add((Element) list);
                    status = true;
                    list = new List();
                    testCase = null;
                }
                chunk = new Chunk(line + "\n");
                Font font = new Font(Font.TIMES_ROMAN);
                font.setSize(18);
                chunk.setFont(font);
                index++;
            } else {
                if (line.contains("not")) {
                    status = false;
                }
                list.add(line);
            }
            //   document.add(chunk);
        }
    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:ec.display.chart.StatisticsChartPaneTab.java

License:Academic Free License

/**
 * This method initializes jButton  // w  ww . ja  va2  s . c o m
 *  
 * @return javax.swing.JButton      
 */
private JButton getPrintButton() {
    if (printButton == null) {
        printButton = new JButton();
        printButton.setText("Export to PDF...");
        final JFreeChart chart = chartPane.getChart();
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try

                {
                    int width = chartPane.getWidth();
                    int height = chartPane.getHeight();

                    FileDialog fileDialog = new FileDialog(new Frame(), "Export...", FileDialog.SAVE);
                    fileDialog.setDirectory(System.getProperty("user.dir"));
                    fileDialog.setFile("*.pdf");
                    fileDialog.setVisible(true);
                    String fileName = fileDialog.getFile();
                    if (fileName != null)

                    {
                        if (!fileName.endsWith(".pdf")) {
                            fileName = fileName + ".pdf";
                        }
                        File f = new File(fileDialog.getDirectory(), fileName);
                        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
                        document.addAuthor("ECJ Console");
                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(width, height);
                        Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
                        chart.draw(g2, rectangle2D);
                        g2.dispose();
                        cb.addTemplate(tp, 0, 0);
                        document.close();
                    }
                } catch (Exception ex)

                {
                    ex.printStackTrace();
                }
            }
        });
    }
    return printButton;
}

From source file:ec.edu.chyc.manejopersonal.managebean.PDFCustomExporter.java

License:Apache License

@Override
public void export(ActionEvent event, String tableId, FacesContext context, String filename, String tableTitle,
        boolean pageOnly, boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor, boolean subTable) throws IOException {
    try {/* ww  w.  ja v  a2s. com*/
        Document document = new Document();
        if (orientation.equalsIgnoreCase("Landscape")) {
            document.setPageSize(PageSize.A4.rotate());
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        StringTokenizer st = new StringTokenizer(tableId, ",");
        while (st.hasMoreElements()) {
            String tableName = (String) st.nextElement();
            UIComponent component = SearchExpressionFacade.resolveComponent(context, event.getComponent(),
                    tableName);
            if (component == null) {
                throw new FacesException("Cannot find component \"" + tableName + "\" in view.");
            }
            if (!(component instanceof DataTable || component instanceof DataList)) {
                throw new FacesException("Unsupported datasource target:\"" + component.getClass().getName()
                        + "\", exporter must target a PrimeFaces DataTable/DataList.");
            }

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

            if (!document.isOpen()) {
                document.open();
            }
            if (tableTitle != null && !tableTitle.isEmpty() && !tableId.contains("" + ",")) {

                Font tableTitleFont = FontFactory.getFont(FontFactory.TIMES, encodingType, Font.DEFAULTSIZE,
                        Font.BOLD);
                Paragraph title = new Paragraph(tableTitle, tableTitleFont);
                document.add(title);

                Paragraph preface = new Paragraph();
                addEmptyLine(preface, 3);
                document.add(preface);
            }
            PdfPTable pdf;
            DataList list = null;
            DataTable table = null;
            if (component instanceof DataList) {
                list = (DataList) component;
                pdf = exportPDFTable(context, list, pageOnly, encodingType);
            } else {
                table = (DataTable) component;
                pdf = exportPDFTable(context, table, pageOnly, selectionOnly, encodingType, subTable);
            }

            if (pdf != null) {
                document.add(pdf);
            }
            // add a couple of blank lines
            Paragraph preface = new Paragraph();
            addEmptyLine(preface, datasetPadding);
            document.add(preface);

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

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

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

From source file:ec.edu.uce.erp.web.common.util.CustomPDFExporter.java

@Override
public void export(FacesContext context, DataTable table, String filename, boolean pageOnly,
        boolean selectionOnly, String encodingType, MethodExpression preProcessor,
        MethodExpression postProcessor) throws IOException {

    try {//ww  w. jav a  2  s. c o  m
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

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

        //         addMetaData(document);
        addTitlePage(document);

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

        document.close();

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

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