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: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 w w  w.  ja v a  2 s. 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 .ja  v  a2  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 {/*www. j a  v a 2  s . 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();

}

From source file:fr.aliasource.webmail.server.export.ConversationExporter.java

License:GNU General Public License

public void exportToPdf(IAccount account, ConversationReference cr, ClientMessage[] cm, OutputStream out)
        throws ConversationExporterException {
    try {//from  w  w w .  j  ava2s.co m
        Document document = new Document(PageSize.A4, 22, 22, 80, 72);
        PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setPageEvent(new ConversationPdfEventHandler(account, cr, cm));
        // NPP by Tom
        if (cr.getTitle() != null) {
            document.addTitle(cr.getTitle());
        } else {
            document.addTitle("");
        }
        document.addAuthor("MiniG");
        document.open();

        document.add(Chunk.NEWLINE);

        Set<ClientMessage> scm = new LinkedHashSet<ClientMessage>();
        for (int i = 0; i < cm.length; i++) {
            scm.add(cm[i]);
        }
        this.exportMessage(scm, document, false);
        document.close();
    } catch (Exception e) {
        throw new ConversationExporterException("Cannot export conversation ", e);
    }
}

From source file:fr.opensagres.xdocreport.itext.extension.NestedTable.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {//from   w  ww.  j  a v  a  2s .  com
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("NestedTable.pdf"));
        document.open();

        PdfPTable table = new PdfPTable(1);

        PdfPTable nestedTable = new PdfPTable(2);

        PdfPCell cell = new PdfPCell(nestedTable);

        PdfPCell cell1 = new PdfPCell();
        cell1.addElement(new Chunk("cell1"));
        nestedTable.addCell(cell1);

        PdfPCell cell2 = new PdfPCell();
        cell2.addElement(new Chunk("cell2"));
        nestedTable.addCell(cell2);

        table.addCell(cell);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.opensagres.xdocreport.itext.extension.NestedTable2.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {/*from   w  w w  . j  a  v  a  2  s  . co m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("NestedTable2.pdf"));
        document.open();

        PdfPTable table = new PdfPTable(1);

        PdfPTable nestedTable = new PdfPTable(2);
        PdfPCell cell1 = new PdfPCell();
        cell1.addElement(new Chunk("cell1"));
        nestedTable.addCell(cell1);

        PdfPCell cell2 = new PdfPCell();
        cell2.addElement(new Chunk("cell2"));
        nestedTable.addCell(cell2);

        Paragraph paragraph = new Paragraph();
        paragraph.add(new Chunk("eeeeeeeeee"));
        paragraph.add(nestedTable);

        PdfPCell cell = new PdfPCell(paragraph);
        //cell.addElement( nestedTable );
        //cell.addElement( new Chunk("cell3") );
        //cell.
        table.addCell(cell);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.opensagres.xdocreport.itext.extension.SimpleTable.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {// w ww. ja v  a2  s  .  c o  m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SimpleTable.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell;
        Paragraph p = new Paragraph("Text Text Text ");
        table.addCell("cell");
        table.addCell(p);
        table.addCell("cell");
        cell = new PdfPCell(p);

        p = new Paragraph("Text Text Text ");

        //Chunk c = new Chunk( "zzzzzzzzzz" );   

        //cell.setPadding( 0f );
        //cell.getColumn().setAdjustFirstLine( false );
        // make a room for borders
        //cell.setUseBorderPadding( false );

        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setBackgroundColor(Color.red);

        cell.addElement(p);

        cell.setUseAscender(true);
        //cell.addElement(c );
        // cell.setPaddingTop( 0f );
        // cell.setPaddingLeft( 20f );

        table.addCell(cell);
        //table.addCell( "cell" );
        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.opensagres.xdocreport.itext.extension.TableWithAlignment.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {//w  w w  .  j  av  a  2 s.  c o  m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("TableWithAlignment.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setUseAscender(true);
        table.getDefaultCell().setUseDescender(true);

        table.setWidths(new float[] { 5, 10 });
        table.setWidthPercentage(10);

        PdfPCell cell1 = new PdfPCell();
        cell1.addElement(new Chunk("cell1"));
        table.addCell(cell1);

        PdfPCell cell2 = new PdfPCell();
        cell2.addElement(new Chunk("cell2"));
        table.addCell(cell2);

        table.setSpacingBefore(-100);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.opensagres.xdocreport.itext.extension.TableWithVerticalAlignment.java

License:Open Source License

public static void main(String[] args) {
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
    try {/* w  w  w . ja v a  2 s. co  m*/
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream("TableWithVerticalAlignment.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(1);
        // PdfPCell cell1 = new PdfPCell();
        // cell1.setVerticalAlignment( Element.ALIGN_BOTTOM );
        // //cell1.setMinimumHeight( 100f );
        // cell1.addElement( new Chunk( "cell1" ) );
        // table.addCell( cell1 );

        PdfPCell cell2 = new PdfPCell();
        Paragraph p = new Paragraph();
        p.add(new Chunk("cellp&"));

        cell2.addElement(p);
        cell2.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell2.setMinimumHeight(38f);
        table.addCell(cell2);

        document.add(table);
    } catch (Exception de) {
        de.printStackTrace();
    }
    document.close();
}

From source file:fr.paris.lutece.plugins.directory.modules.pdfproducer.utils.PDFUtils.java

License:Open Source License

/**
 * method to create PDF/*from   w w  w  . j  ava  2 s  .c  o m*/
 * @param adminUser The admin user
 * @param locale The locale
 * @param strNameFile PDF name
 * @param out OutputStream
 * @param nIdRecord the id record
 * @param listIdEntryConfig list of config id entry
 * @param bExtractNotFilledField if true, extract empty fields, false
 */
public static void doCreateDocumentPDF(AdminUser adminUser, Locale locale, String strNameFile, OutputStream out,
        int nIdRecord, List<Integer> listIdEntryConfig, Boolean bExtractNotFilledField) {
    Document document = new Document(PageSize.A4);

    Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);

    EntryFilter filter;

    Record record = RecordHome.findByPrimaryKey(nIdRecord, plugin);

    filter = new EntryFilter();
    filter.setIdDirectory(record.getDirectory().getIdDirectory());
    filter.setIsGroup(EntryFilter.FILTER_TRUE);

    List<IEntry> listEntry = DirectoryUtils.getFormEntries(record.getDirectory().getIdDirectory(), plugin,
            adminUser);
    int nIdDirectory = record.getDirectory().getIdDirectory();
    Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, plugin);

    try {
        PdfWriter.getInstance(document, out);
    } catch (DocumentException e) {
        AppLogService.error(e);
    }

    document.open();

    if (record.getDateCreation() != null) {
        SimpleDateFormat monthDayYearformatter = new SimpleDateFormat(
                AppPropertiesService.getProperty(PROPERTY_POLICE_FORMAT_DATE));

        Font fontDate = new Font(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_DATE)),
                DirectoryUtils
                        .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_DATE)));

        Paragraph paragraphDate = new Paragraph(
                new Phrase(monthDayYearformatter.format(record.getDateCreation()).toString(), fontDate));

        paragraphDate.setAlignment(DirectoryUtils
                .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_ALIGN_DATE)));

        try {
            document.add(paragraphDate);
        } catch (DocumentException e) {
            AppLogService.error(e);
        }
    }

    Image image;

    try {

        image = Image.getInstance(ImageIO.read(new File(AppPathService
                .getAbsolutePathFromRelativePath(AppPropertiesService.getProperty(PROPERTY_IMAGE_URL)))), null);
        image.setAlignment(
                DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_IMAGE_ALIGN)));
        float fitWidth;
        float fitHeight;

        try {
            fitWidth = Float.parseFloat(AppPropertiesService.getProperty(PROPERTY_IMAGE_FITWIDTH));
            fitHeight = Float.parseFloat(AppPropertiesService.getProperty(PROPERTY_IMAGE_FITHEIGHT));
        } catch (NumberFormatException e) {
            fitWidth = 100f;
            fitHeight = 100f;
        }

        image.scaleToFit(fitWidth, fitHeight);

        try {
            document.add(image);
        } catch (DocumentException e) {
            AppLogService.error(e);
        }
    } catch (BadElementException e) {
        AppLogService.error(e);
    } catch (MalformedURLException e) {
        AppLogService.error(e);
    } catch (IOException e) {
        AppLogService.error(e);
    }

    directory.getTitle();

    Font fontTitle = new Font(
            DirectoryUtils.convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_NAME)),
            DirectoryUtils
                    .convertStringToInt(AppPropertiesService.getProperty(PROPERTY_POLICE_SIZE_TITLE_DIRECTORY)),
            DirectoryUtils.convertStringToInt(
                    AppPropertiesService.getProperty(PROPERTY_POLICE_STYLE_TITLE_DIRECTORY)));
    fontTitle.isUnderlined();

    Paragraph paragraphHeader = new Paragraph(new Phrase(directory.getTitle(), fontTitle));
    paragraphHeader.setAlignment(Element.ALIGN_CENTER);
    paragraphHeader.setSpacingBefore(DirectoryUtils.convertStringToInt(
            AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_BEFORE_TITLE_DIRECTORY)));
    paragraphHeader.setSpacingAfter(DirectoryUtils.convertStringToInt(
            AppPropertiesService.getProperty(PROPERTY_POLICE_SPACING_AFTER_TITLE_DIRECTORY)));

    try {
        document.add(paragraphHeader);
    } catch (DocumentException e) {
        AppLogService.error(e);
    }

    builderPDFWithEntry(document, plugin, nIdRecord, listEntry, listIdEntryConfig, locale,
            bExtractNotFilledField);
    document.close();
}