Example usage for com.lowagie.text Document close

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

Introduction

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

Prototype

boolean close

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

Click Source Link

Document

Has the document already been closed?

Usage

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 {// www . ja  v  a  2s .com
        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.harvard.mcz.imagecapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(List<UnitTrayLabel> taxa) throws PrintFailedException {
    boolean result = false;
    UnitTrayLabel label = new UnitTrayLabel();
    LabelEncoder encoder = new LabelEncoder(label);
    Image image = encoder.getImage();
    int counter = 0;
    try {//from   ww  w .j  a  va2 s .com
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("labels.pdf"));
        document.setPageSize(PageSize.LETTER);
        document.open();

        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100f);
        //table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
        float[] cellWidths = { 30f, 20f, 30f, 20f };
        table.setWidths(cellWidths);

        UnitTrayLabelLifeCycle uls = new UnitTrayLabelLifeCycle();
        if (taxa == null) {
            taxa = uls.findAll();
        }
        Iterator<UnitTrayLabel> i = taxa.iterator();
        PdfPCell cell = null;
        PdfPCell cell_barcode = null;
        // Create two lists of 12 cells, the first 6 of each representing
        // the left hand column of 6 labels, the second 6 of each 
        // representing the right hand column.  
        // cells holds the text for each label, cells_barcode the barcode.
        ArrayList<PdfPCell> cells = new ArrayList<PdfPCell>(12);
        ArrayList<PdfPCell> cells_barcode = new ArrayList<PdfPCell>(12);
        for (int x = 0; x < 12; x++) {
            cells.add(null);
            cells_barcode.add(null);
        }
        int cellCounter = 0;
        while (i.hasNext()) {
            // Loop through all of the taxa (unit tray labels) found to print 
            label = i.next();
            for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                // For each taxon, loop through the number of requested copies 
                // Generate a text and a barcode cell for each, and add to array for page
                log.debug("Label " + toPrint + " of " + label.getNumberToPrint());
                cell = new PdfPCell();
                cell.setBorderColor(Color.LIGHT_GRAY);
                cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                cell.disableBorderSide(PdfPCell.RIGHT);
                cell.setPaddingLeft(3);

                String higherNames = "";
                if (label.getTribe().trim().length() > 0) {
                    higherNames = label.getFamily() + ": " + label.getSubfamily() + ": " + label.getTribe();
                } else {
                    higherNames = label.getFamily() + ": " + label.getSubfamily();
                }
                Paragraph higher = new Paragraph();
                higher.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                higher.add(new Chunk(higherNames));
                cell.addElement(higher);

                Paragraph name = new Paragraph();
                Chunk genus = new Chunk(label.getGenus().trim() + " ");
                genus.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                Chunk species = new Chunk(label.getSpecificEpithet().trim());
                Chunk normal = null; // normal font prefix to preceed specific epithet (nr. <i>epithet</i>)
                if (label.getSpecificEpithet().contains(".") || label.getSpecificEpithet().contains("[")) {
                    if (label.getSpecificEpithet().startsWith("nr. ")) {
                        normal = new Chunk("nr. ");
                        normal.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                        species = new Chunk(label.getSpecificEpithet().trim().substring(4));
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                    } else {
                        species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                    }
                } else {
                    species.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                String s = "";
                if (label.getSubspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk subspecies = new Chunk(s + label.getSubspecificEpithet().trim());
                if (label.getSubspecificEpithet().contains(".")
                        || label.getSubspecificEpithet().contains("[")) {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));
                } else {
                    subspecies.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                }
                if (label.getInfraspecificRank().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infraRank = new Chunk(s + label.getInfraspecificRank().trim());
                infraRank.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                if (label.getInfraspecificEpithet().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk infra = new Chunk(s + label.getInfraspecificEpithet().trim());
                infra.setFont(new Font(Font.TIMES_ROMAN, 11, Font.ITALIC));
                if (label.getUnNamedForm().trim().length() > 0) {
                    s = " ";
                } else {
                    s = "";
                }
                Chunk unNamed = new Chunk(s + label.getUnNamedForm().trim());
                unNamed.setFont(new Font(Font.TIMES_ROMAN, 11, Font.NORMAL));

                name.add(genus);
                if (normal != null) {
                    name.add(normal);
                }
                name.add(species);
                name.add(subspecies);
                name.add(infraRank);
                name.add(infra);
                name.add(unNamed);
                cell.addElement(name);

                Paragraph authorship = new Paragraph();
                authorship.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                if (label.getAuthorship() != null && label.getAuthorship().length() > 0) {
                    Chunk c_authorship = new Chunk(label.getAuthorship());
                    authorship.add(c_authorship);
                }
                cell.addElement(authorship);
                //cell.addElement(new Paragraph(" "));
                if (label.getDrawerNumber() != null && label.getDrawerNumber().length() > 0) {
                    Paragraph drawerNumber = new Paragraph();
                    drawerNumber.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                    Chunk c_drawerNumber = new Chunk(label.getDrawerNumber());
                    drawerNumber.add(c_drawerNumber);
                    cell.addElement(drawerNumber);
                } else {
                    if (label.getCollection() != null && label.getCollection().length() > 0) {
                        Paragraph collection = new Paragraph();
                        collection.setFont(new Font(Font.TIMES_ROMAN, 10, Font.NORMAL));
                        Chunk c_collection = new Chunk(label.getCollection());
                        collection.add(c_collection);
                        cell.addElement(collection);
                    }
                }

                cell_barcode = new PdfPCell();
                cell_barcode.setBorderColor(Color.LIGHT_GRAY);
                cell_barcode.disableBorderSide(PdfPCell.LEFT);
                cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);

                encoder = new LabelEncoder(label);
                image = encoder.getImage();
                image.setAlignment(Image.ALIGN_TOP);
                cell_barcode.addElement(image);

                cells.add(cellCounter, cell);
                cells_barcode.add(cellCounter, cell_barcode);

                cellCounter++;
                // If we have hit a full set of 12 labels, add them to the document
                // in two columns, filling left column first, then right
                if (cellCounter == 12) {
                    // add a page of 12 cells in columns of two.
                    for (int x = 0; x < 6; x++) {
                        if (cells.get(x) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x));
                            table.addCell(cells_barcode.get(x));
                        }
                        if (cells.get(x + 6) == null) {
                            PdfPCell c = new PdfPCell();
                            c.setBorder(0);
                            table.addCell(c);
                            table.addCell(c);
                        } else {
                            table.addCell(cells.get(x + 6));
                            table.addCell(cells_barcode.get(x + 6));
                        }
                    }
                    // Reset to begin next page
                    cellCounter = 0;
                    document.add(table);
                    table = new PdfPTable(4);
                    table.setWidthPercentage(100f);
                    table.setWidths(cellWidths);
                    for (int x = 0; x < 12; x++) {
                        cells.set(x, null);
                        cells_barcode.set(x, null);
                    }
                }
            } // end loop through toPrint (for a taxon)
            counter++;
        } // end while results has next (for all taxa requested)
          // get any remaining cells in pairs
        for (int x = 0; x < 6; x++) {
            if (cells.get(x) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x));
                table.addCell(cells_barcode.get(x));
            }
            if (cells.get(x + 6) == null) {
                PdfPCell c = new PdfPCell();
                c.setBorder(0);
                table.addCell(c);
                table.addCell(c);
            } else {
                table.addCell(cells.get(x + 6));
                table.addCell(cells_barcode.get(x + 6));
            }
        }
        // add any remaining cells
        document.add(table);
        try {
            document.close();
        } catch (Exception e) {
            throw new PrintFailedException("No labels to print." + e.getMessage());
        }
        // Check to see if there was content in the document.
        if (counter == 0) {
            result = false;
        } else {
            // Printed to pdf ok.
            result = true;
            // Increment number printed.
            i = taxa.iterator();
            while (i.hasNext()) {
                label = i.next();
                for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                    label.setPrinted(label.getPrinted() + 1);
                }
                label.setNumberToPrint(0);
                try {
                    uls.attachDirty(label);
                } catch (SaveFailedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("File not found.");
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new PrintFailedException("Error buiding PDF document.");
    } catch (OutOfMemoryError e) {
        System.out.println("Out of memory error. " + e.getMessage());
        System.out.println("Failed.  Too many labels.");
        throw new PrintFailedException("Ran out of memory, too many labels at once.");
    }
    return result;
}

From source file:edu.jhu.jmontan.hw5.CostAsPdf.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w  .  j  av a 2s .  com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/pdf");
    HttpSession session = request.getSession();
    LineItemReceipt receipt = (LineItemReceipt) session.getAttribute("receipt");
    User user = (User) session.getAttribute("user");
    try {
        Document document = new Document();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, buffer);

        document.open();
        document.add(new Paragraph("JOHN HOPKINS ANNUAL SOFTWARE DEVELOPMENT SEMINAR"));
        document.add(new Paragraph(user.getName()));
        document.add(new Paragraph("You are registered for the following courses as a "
                + user.getFormattedEmploymentStatus() + ":"));
        PdfPTable table = new PdfPTable(2);
        table.addCell("Course");
        table.addCell("Cost");
        for (LineItem lineItem : receipt.getLineItems()) {
            table.addCell(lineItem.getName());
            table.addCell("$" + lineItem.getCost());
        }
        table.addCell("Total");
        table.addCell("$" + receipt.getTotal());
        document.add(table);
        document.close();
        DataOutput output = new DataOutputStream(response.getOutputStream());
        byte[] bytes = buffer.toByteArray();
        response.setContentLength(bytes.length);
        for (int i = 0; i < bytes.length; i++) {
            output.writeByte(bytes[i]);
        }
    } catch (DocumentException ex) {
        Logger.getLogger(CostAsPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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);
    }/*www  .  j  a  v a2 s. com*/

    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 ww  . j a v a  2s  .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:es.uniovi.asw.personalletter.PDFTextWritter.java

@Override
public void createDocument(String documentName, String content) throws CitizenException {
    String realPath = FILE_PATH + documentName + ".pdf";
    Document doc = new Document();
    try {/*  ww  w  .  j a va2  s. c om*/
        PdfWriter.getInstance(doc, new FileOutputStream(realPath));
        doc.open();
        addMetaData(doc);
        addTitlePage(doc);
        addContent(doc, content);
    } catch (DocumentException | FileNotFoundException e) {
        throw new CitizenException("Error al generar documento pdf" + " [" + FILE_PATH + documentName
                + ".pdf] | [" + this.getClass().getName() + "]");
    } finally {
        if (doc != null) {
            doc.close();
        }
    }

}

From source file:etc.Exporter.java

License:Open Source License

public static void saveAsPDF(File file, Task task) {
    try {//from w ww.j a v  a  2s  . com
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(file));

        document.open();
        Paragraph taskid = new Paragraph("ID e Detyres: " + task.getIdentifier(),
                FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC));
        document.add(taskid);

        Paragraph creator = new Paragraph("Krijuar nga " + task.getCreator().toString() + "["
                + task.getCreationTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy - HH.mm")) + "]",
                FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC));
        document.add(creator);

        Paragraph executor = new Paragraph("Per zbatim prej: " + task.getExecutor().toString(),
                FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC));
        document.add(executor);

        Paragraph title = new Paragraph(task.getTitle().toUpperCase(),
                FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD));
        document.add(title);

        Paragraph description = new Paragraph(task.getDescription(),
                FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL));
        document.add(description);

        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.BOTTOM);

        PdfPTable table = new PdfPTable(1);
        table.addCell(cell);
        table.setWidthPercentage(100f);
        document.add(table);

        if (task instanceof dc.CompletedTask) {
            document.add(new Paragraph(
                    "Gjendja: Perfunduar [" + ((dc.CompletedTask) task).getCompletitionTime()
                            .format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH.mm")) + "]",
                    FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC)));
            document.add(new Paragraph("Shenimet e Zbatuesit".toUpperCase(),
                    FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD)));
            document.add(new Paragraph(((dc.CompletedTask) task).getAnnotations(),
                    FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL)));
        } else if (task instanceof dc.RejectedTask) {
            document.add(new Paragraph(
                    "Gjendja: Refuzuar [" + ((dc.RejectedTask) task).getRejectionTime()
                            .format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH.mm")) + "]",
                    FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC)));
            document.add(new Paragraph("Shenimet e Zbatuesit".toUpperCase(),
                    FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD)));
            document.add(new Paragraph(((dc.RejectedTask) task).getAnnotations(),
                    FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL)));
        } else {
            document.add(new Paragraph("Gjendja: Ne Pritje",
                    FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC)));
        }

        document.close();

        Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file.getAbsolutePath());
        p.waitFor();
    } catch (DocumentException | InterruptedException | IOException ex) {
        Logger.getLogger(Exporter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java

License:Open Source License

/**
 * Produce a human readable export of the given tsl to the given file.
 * //from   w  w  w  .  ja v a 2 s.c o  m
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);

        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
            schemeTypes.add(schemeType);
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeName(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

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  ww w.  j  av  a2 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  ww  .  j  a  va 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();

}