Example usage for com.lowagie.text Document Document

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

Introduction

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

Prototype


public Document(Rectangle pageSize) 

Source Link

Document

Constructs a new Document -object.

Usage

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);/*from ww w.jav  a2  s .  com*/
    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 ww  . ja va 2  s. c  om
    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:ec.display.chart.StatisticsChartPaneTab.java

License:Academic Free License

/**
 * This method initializes jButton  /*from ww w . j  a va2s.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:edu.gmu.cs.sim.util.media.PDFEncoder.java

License:Academic Free License

public static void generatePDF(Component component, File file) {
    int width = component.getWidth();
    int height = component.getHeight();
    try {/*from   w w  w .  j  ava 2s.c  o  m*/
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addAuthor("MASON");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics g2 = tp.createGraphics(width, height, new DefaultFontMapper());
        component.paint(g2);
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.gmu.cs.sim.util.media.PDFEncoder.java

License:Academic Free License

public static void generatePDF(JFreeChart chart, int width, int height, File file) {
    try {//from   w  ww  . java2 s.  c o m
        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addAuthor("MASON");
        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 e) {
        e.printStackTrace();
    }
}

From source file:edu.psu.citeseerx.web.ViewPDFPageController.java

License:Apache License

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {

    String errorTitle = "Document Not Found";

    String doi = request.getParameter("doi");
    String rep = request.getParameter("rep");
    String page = request.getParameter("page");

    Map<String, Object> model = new HashMap<String, Object>();
    if (doi == null || rep == null) {
        model.put("pagetitle", errorTitle);
        return new ModelAndView("viewDocError", model);
    }/*from   w  w  w. ja v  a  2s  .  c  o  m*/

    int iPage;
    try {
        iPage = Integer.parseInt(page);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        model.put("pagetitle", errorTitle);
        return new ModelAndView("viewDocError", model);
    }

    try {
        PdfReader reader = csxdao.getPdfReader(doi, rep);
        Document document = new Document(reader.getPageSizeWithRotation(iPage));
        ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE);
        PdfCopy copy = new PdfCopy(document, baos);
        document.open();
        PdfImportedPage docPage = copy.getImportedPage(reader, iPage);
        copy.addPage(docPage);
        document.close();

        response.setContentType("application/pdf");
        response.setContentLength(baos.size());
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
        model.put("pagetitle", errorTitle);
        return new ModelAndView("viewDocError", model);
    } catch (DocumentException e) {
        e.printStackTrace();
        model.put("pagetitle", errorTitle);
        return new ModelAndView("viewDocError", model);
    }
    return null;
}

From source file:edu.ucsf.rbvi.clusterMaker2.internal.treeview.dendroview.GraphicsExportPanel.java

License:Open Source License

private void pdfSave(String format) {
    com.lowagie.text.Rectangle pageSize = PageSize.LETTER;
    Document document = new Document(pageSize);
    try {/*w w  w  .j  a v  a 2 s  .  c  o m*/
        OutputStream output = new BufferedOutputStream(new FileOutputStream(getFile()));
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight(), new DefaultFontMapper());

        double imageScale = Math.min(pageSize.getWidth() / ((double) estimateWidth() + getBorderPixels()),
                pageSize.getHeight() / ((double) estimateHeight() + getBorderPixels()));
        g.scale(imageScale, imageScale);
        drawAll(g, 1.0);
        g.dispose();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, new JTextArea("Dendrogram export had problem " + e));
        // logger.error("Exception " + e);
        // e.printStackTrace();
    }

    document.close();
}

From source file:Faculty.Scans_Upload_Processor.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {/*from www. j a  v a 2s  . c o m*/
        HttpSession session = request.getSession();
        MyDB m = new MyDB();

        int total_sheets = (Integer) session.getAttribute("total_sheets");
        int p_id = (Integer) session.getAttribute("p_id");
        String path = (String) getServletContext().getInitParameter("Directory") + "//";

        if (!(new File(path)).exists()) {
            (new File(path)).mkdir(); // creates the directory if it does not exist        
        }

        path = path + (Integer) p_id + "//";

        System.out.println();
        ArrayList err = new ArrayList();
        ArrayList rollList = new ArrayList();
        ArrayList DocIds = new ArrayList();

        if (!(new File(path)).exists()) {
            (new File(path)).mkdir(); // creates the directory if it does not exist        
        }

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {

            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            // Parse the request
            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded form items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                } else {
                    try {

                        String str = item.getName();

                        String ext = FilenameUtils.getExtension(str);

                        if (ext.equals("txt") || ext.equals("text")) {
                            if ((new File(path + str)).exists()) {
                                (new File(path + str)).delete(); // deletes the file if it does already exist       
                            }

                            File savedFile = new File(path + str);

                            item.write(savedFile);

                            BufferedReader br = new BufferedReader(new FileReader(path + str));
                            String line;
                            while ((line = br.readLine()) != null) {
                                rollList.add(Integer.parseInt(line.trim()));
                            }
                            br.close();

                            DocIds = m.getDocIds(p_id, rollList);
                            Iterator it = DocIds.iterator();

                            while (it.hasNext()) {
                                int temp = (Integer) it.next();
                                if ((new File(path + temp + "//")).exists()) {
                                    try {
                                        delete(new File(path + temp + "//")); // deletes the directory if it does already exist       
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        System.exit(0);
                                    }

                                }

                            }
                            m.CreateDocIds(p_id, rollList);

                            DocIds = m.getDocIds(p_id, rollList);
                            it = DocIds.iterator();
                            while (it.hasNext()) {
                                int temp = (Integer) it.next();
                                if (!(new File(path + temp + "//")).exists()) {
                                    (new File(path + temp + "//")).mkdir(); // creates the directory if it does not exist        
                                }

                            }
                        }

                        else {
                            // To Store Split Files

                            if ((new File(path + "-1" + "//")).exists()) {
                                try {
                                    delete(new File(path + "-1" + "//")); // deletes the directory if it does already exist       
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    System.exit(0);
                                }

                            }

                            if (!(new File(path + "-1" + "//")).exists()) {
                                (new File(path + "-1" + "//")).mkdir(); // creates the directory if it does not exist        
                            }

                            //Splitting PDF
                            int n = 0; // no.of pages
                            try {
                                File savedFile = new File(path + "-1" + "//" + str);
                                item.write(savedFile);

                                String inFile = path + "-1" + "//" + str;
                                System.out.println("Reading " + inFile);
                                PdfReader reader = new PdfReader(inFile);
                                n = reader.getNumberOfPages();

                                // Reply User if PDF has invalid number of scans
                                if (n != total_sheets * DocIds.size()) {
                                    m.deleteDocIds(p_id, rollList);
                                    Iterator it = DocIds.iterator();

                                    while (it.hasNext()) {
                                        int temp = (Integer) it.next();
                                        if ((new File(path + temp + "//")).exists()) {
                                            try {
                                                delete(new File(path + temp + "//")); // deletes the directory if it does already exist       
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                                System.exit(0);
                                            }

                                        }

                                    }
                                    err.add("PDF has missing scans!! It must have "
                                            + total_sheets * DocIds.size() + " pages");

                                    break;
                                }
                                //                                    postData();

                                System.out.println("Number of pages : " + n);
                                int i = 0;
                                while (i < n) {
                                    String outFile = (i + 1) + ".pdf";
                                    System.out.println("Writing " + outFile);
                                    Document document = new Document(reader.getPageSizeWithRotation(1));
                                    PdfCopy writer = new PdfCopy(document,
                                            new FileOutputStream(path + "-1" + "//" + outFile));
                                    document.open();
                                    PdfImportedPage page = writer.getImportedPage(reader, ++i);
                                    writer.addPage(page);
                                    document.close();
                                    writer.close();
                                }

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

                            // Placing files in Corresponding directories
                            //System.out.println(DocIds);
                            for (int i = 1; i <= n; i++) {
                                int temp2 = (i - 1) / total_sheets;
                                int d_id = (Integer) DocIds.get(temp2);
                                String itemName = "";

                                if ((i % total_sheets) == 0) {
                                    itemName = ((Integer) total_sheets).toString();
                                } else {
                                    itemName = ((Integer) (i % total_sheets)).toString();
                                }

                                File source = new File(path + "-1" + "//" + i + ".pdf");
                                File desc = new File(
                                        path + "-1//" + p_id + "_" + d_id + "_" + itemName + ".pdf");

                                try {
                                    FileUtils.copyFile(source, desc);
                                    uploadFile(path + "-1//" + p_id + "_" + d_id + "_" + itemName + ".pdf",
                                            (String) getServletContext().getInitParameter("UploadPhP"));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            try {
                                delete(new File(path + "-1" + "//")); // deletes the directory if it does already exist  
                                delete(new File(path)); // deletes all docs in this paper id
                            } catch (IOException e) {
                                e.printStackTrace();
                                System.exit(0);
                            }

                            err.add("Scans  sucessfully saved !");
                        }

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

            request.setAttribute("err", err);

            RequestDispatcher rd = request.getRequestDispatcher("Paper_Spec_Fetcher");
            rd.forward(request, response);
        } else {
            // Normal request. request.getParameter will suffice.
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }

}

From source file:fitnessmanagersystem.ExportPanel.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    Document document = new Document(PageSize.A2.rotate());
    try {//w  w  w  .  java 2 s .c  o m

        JFileChooser chooser = new JFileChooser(".");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf");
        chooser.setFileFilter(filter);
        chooser.showSaveDialog(this);

        String fileName = chooser.getSelectedFile().getPath();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();

        Graphics2D g2 = cb.createGraphicsShapes(1500, 500);
        Shape oldClip = g2.getClip();
        g2.clipRect(0, 0, 1500, 500);

        jTable1_clients.print(g2);
        g2.setClip(oldClip);
        g2.dispose();
        cb.restoreState();

    } catch (FileNotFoundException | DocumentException e) {
        System.err.println(e.getMessage());
    }
    document.close();

}

From source file:fitnessmanagersystem.ExportPanelProducts.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    Document document = new Document(PageSize.A2.rotate());
    try {//from  w  w w. j av a  2s  .  c  o m
        String FileDialog = null;

        //   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\DISHLIEV\\Desktop\\jTsdfb11wablwe.pdf"));

        JFileChooser chooser = new JFileChooser(".");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf");
        chooser.setFileFilter(filter);
        chooser.showSaveDialog(this);

        //chooser.setFileFilter(filter);
        //        chooser.addChoosableFileFilter(filter);
        File file = chooser.getSelectedFile();

        String fileName = chooser.getSelectedFile().getPath();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));

        // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FileDialog+"C:\\Users\\DISHLIEV\\Desktop\\jTsdfb11wablwe.pdf"));

        /*   FileDialog saveFileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
              saveFileDialog.setFile("");
              saveFileDialog.setVisible(true);   
              saveFileDialog.getDirectory();
                
               try {
            dexceleporte exp = new dexceleporte();
                
          exp.fillData(jTable1, new File(saveFileDialog.getDirectory()+saveFileDialog.getFile()+".xls"));
                  
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        */

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();
        Graphics2D g2 = cb.createGraphicsShapes(1500, 500);

        Shape oldClip = g2.getClip();

        g2.clipRect(0, 0, 1500, 500);

        jTable12dfv.print(g2);
        g2.setClip(oldClip);

        g2.dispose();
        cb.restoreState();

        //}

    } catch (FileNotFoundException | DocumentException e) {
        System.err.println(e.getMessage());
    }
    document.close();

}