Example usage for com.itextpdf.text Element ALIGN_RIGHT

List of usage examples for com.itextpdf.text Element ALIGN_RIGHT

Introduction

In this page you can find the example usage for com.itextpdf.text Element ALIGN_RIGHT.

Prototype

int ALIGN_RIGHT

To view the source code for com.itextpdf.text Element ALIGN_RIGHT.

Click Source Link

Document

A possible value for paragraph alignment.

Usage

From source file:Controlador.ControladorClasificacion.java

/**
 * Mtodo generarPDF que genera el PDF con la clasificacin al pulsar el
 * botn generar PDF/* w ww .ja v  a 2 s .c  o  m*/
 *
 * @throws FileNotFoundException salta la excepcion
 * @throws DocumentException salta la excepcion
 * @throws IOException salta la excepcion
 */
public void generarPDF() throws FileNotFoundException, DocumentException, IOException {

    Calendar cal = Calendar.getInstance();
    String time = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(cal.getTime());

    File file = new File("Clasificacion.pdf");
    FileOutputStream fileout = new FileOutputStream(file.getAbsolutePath());
    Document document = new Document();
    PdfWriter.getInstance(document, fileout);

    Font fuente1 = new Font();
    Font fuente2 = new Font();
    Font fuente3 = new Font();
    fuente1.setStyle(Font.BOLD | Font.ITALIC | Font.UNDERLINE);
    fuente1.setSize(18);
    fuente1.setColor(0, 51, 204);
    fuente2.setStyle(Font.BOLD | Font.ITALIC);
    fuente2.setColor(0, 51, 204);
    fuente2.setSize(13);
    fuente3.setStyle(Font.BOLD | Font.ITALIC);
    fuente3.setSize(16);
    fuente3.setColor(255, 153, 0);

    document.open();

    Paragraph pa = new Paragraph("Fecha y hora: " + time);

    pa.setAlignment(Element.ALIGN_RIGHT);
    document.add(pa);

    /*String url = "imagenPDF.jpg";
    File file2 = new File(url);
    FileInputStream filein = new FileInputStream(file2.getAbsolutePath());
    //String url = "./imagenPDF.jpg";
    Image imagen = Image.getInstance(filein.getFD());  
    //System.out.println(file2.getAbsolutePath());
    imagen.scalePercent(20);
    document.add(imagen);*/
    document.add(new Paragraph("\n"));
    Paragraph p3 = new Paragraph("GESTOR DE CAMPEONATO DE BALONCESTO", fuente1);
    p3.setAlignment(Element.ALIGN_CENTER);
    document.add(p3);

    document.add(new Paragraph("\n"));
    String tipo_competicion = FicherosTipo.leerFichero();

    if (tipo_competicion.contains("Copa")) {
        Paragraph pa1 = new Paragraph("COPA", fuente3);
        pa1.setAlignment(Element.ALIGN_CENTER);
        document.add(pa1);
        document.add(new Paragraph(
                "---------------------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph("\n"));
        int jornada_maxima = PartidoDAO.obtenerJornadaActual();

        for (int i = jornada_maxima; i > 0; i--) {
            List<Partido> listarPartidosJornada = PartidoDAO.listarPartidosJornada(i);
            for (Partido p : listarPartidosJornada) {

                List<PartidoJugado> listarEquiposporPartido = PartidoJugadoDAO
                        .listarEquiposporPartido(p.getIdPartido());

                int equipoA = listarEquiposporPartido.get(0).getIdEquipo();
                int equipoB = listarEquiposporPartido.get(1).getIdEquipo();

                Paragraph p2 = new Paragraph(
                        "Equipo A: " + EquipoDAO.obtenerNombreEquipo(equipoA) + " - Equipo B: "
                                + EquipoDAO.obtenerNombreEquipo(equipoB) + " - Resultado: " + p.getResultado(),
                        fuente2);
                p2.setAlignment(Element.ALIGN_LEFT);
                document.add(p2);
            }

        }

    } else if (tipo_competicion.contains("Liga")) {
        Paragraph pa1 = new Paragraph("LIGA", fuente3);
        pa1.setAlignment(Element.ALIGN_LEFT);
        document.add(pa1);
        document.add(new Paragraph(
                "---------------------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph("\n"));
        List<Equipo> obtenerTodosEquipos = EquipoDAO.obtenerTodosEquipos();
        Collections.sort(obtenerTodosEquipos);
        System.out.println(obtenerTodosEquipos);
        for (Equipo p : obtenerTodosEquipos) {
            Paragraph pa2 = new Paragraph(p.getNombre(), fuente2);
            pa2.setAlignment(Element.ALIGN_LEFT);
            document.add(pa2);
        }

    }
    document.close();
    File myfile = new File("Clasificacion.pdf");
    Desktop.getDesktop().open(myfile);
}

From source file:ControleurClients.ControleurClients.java

private void pageCommandes(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DocumentException {
    request.setAttribute("attente", commandef.getAttente(clientConnect));
    request.setAttribute("cours", commandef.getCours(clientConnect));
    request.setAttribute("effectuee", commandef.getEffectuee(clientConnect));

    List<Commande> attente = commandef.getAttente();
    List<Commande> cours = commandef.getCours();
    List<Commande> effectue = commandef.getEffectuee();
    if (!attente.isEmpty()) {
        for (Commande c : attente) {
            Document document1 = new Document();
            PdfWriter.getInstance(document1,
                    new FileOutputStream("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/attente"
                            + c.getId().toString() + ".pdf"));

            document1.open();/* w  ww . ja  v a 2s  .  com*/
            Paragraph text = new Paragraph();
            text.add(new Paragraph("Grenoble Dvd", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Facture", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("En attente : Commande n" + c.getId().toString(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));

            document1.add(text);

            Paragraph p = new Paragraph(c.getDate(), new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC));
            p.setAlignment(Element.ALIGN_RIGHT);
            p.add(new Paragraph(" "));
            p.add(new Paragraph(" "));
            document1.add(p);

            Paragraph text1 = new Paragraph();
            text1.add(new Paragraph(
                    "Mr " + c.getClient().getNom().substring(0, 1).toUpperCase()
                            + c.getClient().getNom().substring(1) + " "
                            + c.getClient().getPrenom().substring(0, 1).toUpperCase()
                            + c.getClient().getPrenom().substring(1),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            text1.add(new Paragraph("Email: " + c.getClient().getEmail(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));

            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));

            document1.add(text1);

            PdfPTable table = new PdfPTable(3);
            //On crer l'objet cellule.
            PdfPCell cell;

            cell = new PdfPCell(new Phrase("Facture"));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("Nom du Dvd"));
            cell.setRowspan(1);
            table.addCell(cell);
            //contenu du tableau.
            table.addCell("Quantit");
            table.addCell("Prix");

            for (Entry<Dvd, Integer> entry : c.getDvds().entrySet()) {

                Dvd dvd = (Dvd) entry.getKey();
                Object value = entry.getValue();
                //Image dvdimage = Image.getInstance(dvd.getImage());
                //On crer un objet table dans lequel on intialise a taille.

                cell = new PdfPCell(new Phrase(dvd.getTitre()));
                cell.setRowspan(1);
                table.addCell(cell);

                table.addCell(String.valueOf(value));
                table.addCell(String.valueOf(dvd.getPrix()));

            }

            cell = new PdfPCell(new Phrase("Total: " + String.valueOf(c.getMontant()) + " "));
            cell.setColspan(3);

            table.addCell(cell);

            document1.add(table);
            Paragraph p1 = new Paragraph();
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" Grenoble Dvd: 12 avenue des ensimag 38000 Grenoble",
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            p1.setAlignment(Element.ALIGN_RIGHT);
            document1.add(p1);
            document1.close();
        }
    }

    if (!cours.isEmpty()) {
        for (Commande c : cours) {
            Document document1 = new Document();
            PdfWriter.getInstance(document1,
                    new FileOutputStream("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/cours"
                            + c.getId().toString() + ".pdf"));

            document1.open();
            Paragraph text = new Paragraph();
            text.add(new Paragraph("Grenoble Dvd", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Facture", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("En cours : Commande n" + c.getId().toString(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));

            document1.add(text);

            Paragraph p = new Paragraph(c.getDate(), new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC));
            p.setAlignment(Element.ALIGN_RIGHT);
            p.add(new Paragraph(" "));
            p.add(new Paragraph(" "));
            document1.add(p);

            Paragraph text1 = new Paragraph();
            text1.add(new Paragraph(
                    "Mr " + c.getClient().getNom().substring(0, 1).toUpperCase()
                            + c.getClient().getNom().substring(1) + " "
                            + c.getClient().getPrenom().substring(0, 1).toUpperCase()
                            + c.getClient().getPrenom().substring(1),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            text1.add(new Paragraph("Email: " + c.getClient().getEmail(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));

            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));

            document1.add(text1);

            PdfPTable table = new PdfPTable(3);
            //On crer l'objet cellule.
            PdfPCell cell;

            cell = new PdfPCell(new Phrase("Facture"));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("Nom du Dvd"));
            cell.setRowspan(1);
            table.addCell(cell);
            //contenu du tableau.
            table.addCell("Quantit");
            table.addCell("Prix");

            for (Entry<Dvd, Integer> entry : c.getDvds().entrySet()) {

                Dvd dvd = (Dvd) entry.getKey();
                Object value = entry.getValue();
                //Image dvdimage = Image.getInstance(dvd.getImage());
                //On crer un objet table dans lequel on intialise a taille.

                cell = new PdfPCell(new Phrase(dvd.getTitre()));
                cell.setRowspan(1);
                table.addCell(cell);

                table.addCell(String.valueOf(value));
                table.addCell(String.valueOf(dvd.getPrix()));

            }

            cell = new PdfPCell(new Phrase("Total : " + String.valueOf(c.getMontant()) + " "));
            cell.setColspan(3);

            table.addCell(cell);

            document1.add(table);
            Paragraph p1 = new Paragraph();
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" Grenoble Dvd: 12 avenue des ensimag 38000 Grenoble",
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            p1.setAlignment(Element.ALIGN_RIGHT);
            document1.add(p1);
            document1.close();
        }
    }

    if (!effectue.isEmpty()) {
        for (Commande c : effectue) {
            new File("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/attente" + c.getId().toString()
                    + ".pdf").delete();
            new File("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/cours" + c.getId().toString()
                    + ".pdf").delete();

            Document document1 = new Document();
            PdfWriter.getInstance(document1,
                    new FileOutputStream("/home/aymeric/Commerce/Commerce/Commerce-war/web/pdf/effectue"
                            + c.getId().toString() + ".pdf"));

            document1.open();
            Paragraph text = new Paragraph();
            text.add(new Paragraph("Grenoble Dvd", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Facture", new Font(Font.FontFamily.TIMES_ROMAN, 24, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));
            text.add(new Paragraph("Effectue : Commande n" + c.getId().toString(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD)));
            text.add(new Paragraph(" "));
            text.add(new Paragraph(" "));

            document1.add(text);

            Paragraph p = new Paragraph(c.getDate(), new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC));
            p.setAlignment(Element.ALIGN_RIGHT);
            p.add(new Paragraph(" "));
            p.add(new Paragraph(" "));
            document1.add(p);

            Paragraph text1 = new Paragraph();
            text1.add(new Paragraph(
                    "Mr " + c.getClient().getNom().substring(0, 1).toUpperCase()
                            + c.getClient().getNom().substring(1) + " "
                            + c.getClient().getPrenom().substring(0, 1).toUpperCase()
                            + c.getClient().getPrenom().substring(1),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            text1.add(new Paragraph("Email: " + c.getClient().getEmail(),
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));

            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));
            text1.add(new Paragraph(" "));

            document1.add(text1);

            PdfPTable table = new PdfPTable(3);
            //On crer l'objet cellule.
            PdfPCell cell;

            cell = new PdfPCell(new Phrase("Facture"));
            cell.setColspan(3);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("Nom du Dvd"));
            cell.setRowspan(1);
            table.addCell(cell);
            //contenu du tableau.
            table.addCell("Quantit");
            table.addCell("Prix");

            for (Entry<Dvd, Integer> entry : c.getDvds().entrySet()) {

                Dvd dvd = (Dvd) entry.getKey();
                Object value = entry.getValue();
                //Image dvdimage = Image.getInstance(dvd.getImage());
                //On crer un objet table dans lequel on intialise a taille.

                cell = new PdfPCell(new Phrase(dvd.getTitre()));
                cell.setRowspan(1);
                table.addCell(cell);

                table.addCell(String.valueOf(value));
                table.addCell(String.valueOf(dvd.getPrix()));

            }

            cell = new PdfPCell(new Phrase("Total : " + String.valueOf(c.getMontant()) + " "));
            cell.setColspan(3);

            table.addCell(cell);

            document1.add(table);

            Paragraph p1 = new Paragraph();
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" "));
            p1.add(new Paragraph(" Grenoble Dvd: 12 avenue des ensimag 38000 Grenoble",
                    new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.ITALIC)));
            p1.setAlignment(Element.ALIGN_RIGHT);
            document1.add(p1);
            document1.close();
        }

    }

    getServletContext().getRequestDispatcher("/WEB-INF/Commande.jsp").forward(request, response);
}

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;/*from  w w w .  jav a2s  .  c o  m*/

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:Controller.ControllerCompra.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w ww  .ja  v  a  2  s.c om
 *
 * @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("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        //int estado = 0;
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String facturaProveedor = (request.getParameter("txtNumeroFactura"));
            String nombreProveedor = (request.getParameter("txtNombre"));
            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalCompra"));
            listObjDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listObjDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objCompra.setFacturaProveedor(facturaProveedor);
            _objCompra.setNombreProveedor(nombreProveedor);
            _objCompra.setTotalCompra(totalCompra);
            daoModelCompra = new ModelCompra();
            String salida = Mensaje(daoModelCompra.Add(_objCompra, _objUsuario, listObjDetalleMovimientos),
                    "La compra ha sido registrada", "Ha ocurrido un error");
            daoModelCompra.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableCompra());
            break;
        }
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iText">
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> compra = (Map) material.get("Compra");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra                        
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Nombre del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("nombreProveedor") + "\n"));
                headerDerecha.add(new Chunk("Factura del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("facturaProveedor") + "\n"));
                headerDerecha.add(new Chunk("Fecha Compra: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("fechaCompra") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Compra", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(compra.get("totalCompra")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        //</editor-fold>
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iReports">
        case "Imprimir2": {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String source = url + "/reports/newReport1.jrxml";
                JasperPrint jasperPrint = null;
                JasperReport jasperReport = null;
                JasperDesign jasperDesign = null;
                System.out.println(source);
                String reportPath = request.getServletContext().getRealPath("reports") + "\\newReport1.jrxml";
                jasperDesign = JRXmlLoader.load(reportPath);
                jasperReport = JasperCompileManager.compileReport(jasperDesign);
                jasperPrint = JasperFillManager.fillReport(jasperReport, reporte(id),
                        daoModelCompra.getConnection());
                JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
            } catch (Exception ex) {
                for (StackTraceElement ruta : ex.getStackTrace()) {
                    System.err.println(ruta);
                }
            }
        }
            break;
        //</editor-fold>

        }
    }

}

From source file:Controller.ControllerVenta.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w.j  a  v a2  s  .  c  o m
 *
 * @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("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String documentoCliente = null;
            String nombreCliente = null;
            int numeroVenta = 0;
            if (Validador.validarDocumento(request.getParameter("documentoCliente"))
                    & Validador.validarNombresCompletos(request.getParameter("txtNombreCliente"))
                    & Validador.validarNumero(request.getParameter("txtNumeroVenta"))) {
                documentoCliente = (request.getParameter("documentoCliente"));
                nombreCliente = (request.getParameter("txtNombreCliente"));
                numeroVenta = Integer.parseInt(request.getParameter("txtNumeroVenta"));
            } else {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(Mensaje(false, null, "Ha ingresado datos incorrectos"));
                break;
            }

            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalVenta"));
            listOjbDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listOjbDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objVenta.setIdVenta(numeroVenta);
            _objVenta.setDocumentoCliente(documentoCliente);
            _objVenta.setNombreCliente(nombreCliente);
            _objVenta.setTotalVenta(totalCompra);
            daoModelVenta = new ModelVenta();
            String salida = Mensaje(daoModelVenta.Add(_objVenta, _objUsuario, listOjbDetalleMovimientos),
                    "La venta ha sido registrada", "Ha ocurrido un error");
            daoModelVenta.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableVenta());
            break;
        }
        case "Contador": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getContador());
            break;
        }
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> venta = (Map) material.get("Venta");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra         
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Id. de la Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("numeroVenta") + "\n"));
                headerDerecha.add(new Chunk("Nombre del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("nombreCliente") + "\n"));
                headerDerecha.add(new Chunk("Documento del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("documentoCliente") + "\n"));
                headerDerecha.add(new Chunk("Fecha Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("fechaVenta") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Venta", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(venta.get("totalVenta")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        }
    }
}

From source file:Controller.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {//from ww  w.j  a v  a2  s  . c o  m

        DonHang donhang = new DonHang();
        donhang.init(maDH);
        float CONVERT = 28.346457f;// 1 cm
        FacesContext faces = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();
        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Content-disposition","inline; filename=kiran.pdf");
        response.setHeader("Pragma", "public");
        response.setContentType("application/pdf");
        //response.setHeader("Content-Disposition", "attachment;filename=\"ContactList.pdf\"");
        response.addHeader("Content-disposition", "attachment;filename=\"DataListBean.pdf\"");
        //step 1: creation of a document-object
        Document document = new Document(PageSize.A4, 0.5f * CONVERT, 0.5f * CONVERT, 1.0f * CONVERT,
                1.0f * CONVERT);
        //step 2: we create a writer that listens to the document
        // and directs a PDF-stream to a temporary buffer
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
        Font font = new Font(bf, 18, Font.BOLD);
        Font font11 = new Font(bf, 11, Font.NORMAL);
        Font font11_bo = new Font(bf, 11, Font.BOLD);
        Font font12 = new Font(bf, 12, Font.NORMAL);
        Font font10 = new Font(bf, 10, Font.NORMAL);
        Font font9 = new Font(bf, 9, Font.NORMAL);
        //step 3: we open the document
        document.open();

        PdfPTable tab_Header1;
        tab_Header1 = new PdfPTable(1);
        tab_Header1.setWidthPercentage(100);

        tab_Header1.setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell cell1;
        cell1 = new PdfPCell(new Phrase("CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S?T: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?N GIAO HNG", font12));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Bn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: CNG TY TNHH ABC FASHION", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(
                new Phrase("?a ch: 146 Linh Trung,P. Linh Trung, Q. Th ?c, TP HCM", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: 0909465621", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Mua:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn: " + donhang.getTenKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch: " + donhang.getDiaChiKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi: " + donhang.getSoDTKH(), font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Bn Vn chuyn:", font11_bo));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tn:....................................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("?a ch:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S in thoi:...............................", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Danh sch hng ha:", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);
        ///////////////////////////////bn sn phm
        float[] crDonHang = { 1.0f * CONVERT, 4.0f * CONVERT, 1.0f * CONVERT, 2.0f * CONVERT, 2.0f * CONVERT };

        PdfPTable tab_Header2;
        tab_Header2 = new PdfPTable(crDonHang.length);
        tab_Header2.setWidthPercentage(100);
        tab_Header2.setWidths(crDonHang);
        tab_Header2.setHorizontalAlignment(Element.ALIGN_CENTER);
        NumberFormat formatter = new DecimalFormat("#,###,###");

        String[] crheader = { "STT", "Tn Hng", "S Lng", "Gi Bn(VN?)", "Thnh Ti?n(VN?)" };

        for (int i = 0; i < crheader.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(crheader[i], font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);
        }
        int stt = 1;
        for (SanPhamDH sp : donhang.getListSP()) {

            PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(stt), font11));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getTenSP(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(sp.getSoluong(), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getGiaSP())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            cell = new PdfPCell(new Phrase(formatter.format(Double.parseDouble(sp.getThanhTien())), font11));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

            tab_Header2.addCell(cell);

            stt++;
        }
        cell1 = new PdfPCell(tab_Header2);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n hng:   "
                + formatter.format(
                        Double.parseDouble(donhang.getTienTamTinh() == null ? "0" : donhang.getTienTamTinh()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n vn chuyn:   "
                + formatter.format(Double
                        .parseDouble(donhang.getTienVanChuyen() == null ? "0" : donhang.getTienVanChuyen()))
                + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Tng ti?n thanh ton:   "
                + formatter.format(Double.parseDouble(donhang.getTongTien())) + " VN?", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("S ti?n thanh ton bng ch: "
                + DocTien.doctien(donhang.getTongTien().replaceAll(" ", "")) + "ng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("TP H Ch Minh, ngy      thng       nm       ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell1.setPaddingRight(1.0f * CONVERT);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        cell1 = new PdfPCell(new Phrase(" ", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        PdfPTable tab_Header3;
        tab_Header3 = new PdfPTable(3);
        tab_Header3.setWidthPercentage(100);

        tab_Header3.setHorizontalAlignment(Element.ALIGN_CENTER);

        cell1 = new PdfPCell(new Phrase("Ng?i nhn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i giao hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("Ng?i bn hng", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(new Phrase("(k v ghi r h? tn)", font11));
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setPaddingBottom(5.0f);
        cell1.setBorder(0);
        tab_Header3.addCell(cell1);

        cell1 = new PdfPCell(tab_Header3);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setBorder(0);
        tab_Header1.addCell(cell1);

        document.add(tab_Header1);

        document.close();
        //step 6: we output the writer as bytes to the response output
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        baos.flush();
        faces.responseComplete();

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

From source file:Controller.Receipt.Controller_FXML_Receipt.java

public void createReceipt(String filename, String patientid)
        throws DocumentException, IOException, PrinterException {
    {/*from   www . ja  v a 2s .  c o m*/

        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        Document document = new Document();
        String receipt_id = null;
        String patientname = null;
        String date = null;
        String total_sum = null;
        try {
            try {
                PdfWriter.getInstance(document, new FileOutputStream(filename));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (DocumentException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        document.open();
        Font font = new Font(FontFamily.TIMES_ROMAN, 10, Font.BOLD);
        //getFont("c:/windows/fonts/Shruti.ttf",
        //BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        //document.add(new Paragraph("english",font));
        com.itextpdf.text.Image img = null;
        //            try {
        //                img = com.itextpdf.text.Image.getInstance("C:");
        //                img.scalePercent(80f);
        //            } catch (BadElementException ex) {
        //                Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        //            } catch (IOException ex) {
        //                Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        //            }

        /*try {
         document.add(img);
         } catch (DocumentException ex) {
         Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
         }*/
        Paragraph title = new Paragraph("RECEIPT", font);
        Paragraph header = new Paragraph("SHARDA HOSPITAL");
        header.setAlignment(Element.ALIGN_CENTER);
        title.setAlignment(Element.ALIGN_CENTER);
        Paragraph receiptid = new Paragraph("R.No" + receipt_id, font);
        receiptid.setAlignment(Element.ALIGN_LEFT);
        Paragraph Date = new Paragraph("Date :" + date, font);
        Date.setAlignment(Element.ALIGN_RIGHT);
        try {
            document.add(header);
        } catch (DocumentException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            document.add(title);
        } catch (DocumentException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            document.add(receiptid);
        } catch (DocumentException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            document.add(Date);
        } catch (DocumentException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        String DOJ = null;
        String diagnosis = null;
        String no_of_days = null;
        String DOD = null;
        Paragraph patient_details = new Paragraph("Received " + total_sum + "from Mr./Mrs. " + patientname
                + " towards indoor/outdoor charges detailed as below."
                + " He/She was admitted in hospital/under treatment from" + DOJ + "to " + DOD
                + ". He/She is suffering from " + diagnosis + "." + " He/She has to take future medicie for"
                + no_of_days + ".", font);
        try {
            document.add(patient_details);
        } catch (DocumentException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Chaitanya");
        Object newValue = null;
        //Check whether item is selected and set value of selected item to Label
        if (table.getSelectionModel().getSelectedItem() != null) {
            TableView.TableViewSelectionModel selectionModel = table.getSelectionModel();
            ObservableList selectedCells = selectionModel.getSelectedCells();
            TablePosition tablePosition = (TablePosition) selectedCells.get(0);
            Object val1 = tablePosition.getTableColumn().getCellData(newValue);
            System.out.println("Fee Type Value" + val1);
            TablePosition tablePosition1 = (TablePosition) selectedCells.get(1);
            Object val2 = tablePosition1.getTableColumn().getCellData(newValue);
            System.out.println("Charges Value" + val2);
        }

        document.close();
        String pdfFile = "report.pdf";
        try {
            printPDF(pdfFile);
        } catch (IOException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PrinterException ex) {
            Logger.getLogger(Controller_FXML_Receipt.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:dbedit.actions.ExportPdfAction.java

License:Open Source License

@Override
protected void performThreaded(ActionEvent e) throws Exception {
    boolean selection = false;
    JTable table = ResultSetTable.getInstance();
    if (table.getSelectedRowCount() > 0 && table.getSelectedRowCount() != table.getRowCount()) {
        Object option = Dialog.show("PDF", "Export", Dialog.QUESTION_MESSAGE,
                new Object[] { "Everything", "Selection" }, "Everything");
        if (option == null || "-1".equals(option.toString())) {
            return;
        }/*w  w w  .  j a v  a 2s  .c  o m*/
        selection = "Selection".equals(option);
    }
    List list = ((DefaultTableModel) table.getModel()).getDataVector();
    int columnCount = table.getColumnCount();
    PdfPTable pdfPTable = new PdfPTable(columnCount);
    pdfPTable.setWidthPercentage(100);
    pdfPTable.getDefaultCell().setPaddingBottom(4);
    int[] widths = new int[columnCount];

    // Row Header
    pdfPTable.getDefaultCell().setBorderWidth(2);
    for (int i = 0; i < columnCount; i++) {
        String columnName = table.getColumnName(i);
        pdfPTable.addCell(new Phrase(columnName, ROW_HEADER_FONT));
        widths[i] = Math.min(50000, Math.max(widths[i], ROW_HEADER_BASE_FONT.getWidth(columnName + " ")));
    }
    pdfPTable.getDefaultCell().setBorderWidth(1);
    if (!list.isEmpty()) {
        pdfPTable.setHeaderRows(1);
    }

    // Body
    for (int i = 0; i < list.size(); i++) {
        if (!selection || table.isRowSelected(i)) {
            List record = (List) list.get(i);
            for (int j = 0; j < record.size(); j++) {
                Object o = record.get(j);
                if (o != null) {
                    if (ResultSetTable.isLob(j)) {
                        o = Context.getInstance().getColumnTypeNames()[j];
                    }
                } else {
                    o = "";
                }
                PdfPCell cell = new PdfPCell(new Phrase(o.toString()));
                cell.setPaddingBottom(4);
                if (o instanceof Number) {
                    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                }
                pdfPTable.addCell(cell);
                widths[j] = Math.min(50000, Math.max(widths[j], BASE_FONT.getWidth(o.toString())));
            }
        }
    }

    // Size
    pdfPTable.setWidths(widths);
    int totalWidth = 0;
    for (int width : widths) {
        totalWidth += width;
    }
    Rectangle pageSize = PageSize.A4.rotate();
    pageSize.setRight(pageSize.getRight() * Math.max(1f, totalWidth / 53000f));
    pageSize.setTop(pageSize.getTop() * Math.max(1f, totalWidth / 53000f));

    // Document
    Document document = new Document(pageSize);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();
    pdfTemplate = writer.getDirectContent().createTemplate(100, 100);
    pdfTemplate.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    writer.setPageEvent(this);
    document.add(pdfPTable);
    document.close();
    FileIO.saveAndOpenFile("export.pdf", byteArrayOutputStream.toByteArray());
}

From source file:de.aidger.utils.pdf.ActivityReportConverter.java

License:Open Source License

/**
 * Writes the logos and the address of the institute.
 *//*from ww w .ja v  a  2s.  c  o m*/
private void writeLogo() {
    try {
        Font generatedByFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 8);
        Image aidger = Image.getInstance(getClass().getResource("/de/aidger/res/pdf/AidgerLogo.png"));
        aidger.scaleAbsolute(80.0f, 20.0f);
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(reader.getPageSize(1).getRight());
        PdfPCell cell = new PdfPCell(new Phrase(_("Generated by: "), generatedByFont));
        cell.setBorder(0);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setPaddingBottom(5);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        table.addCell(cell);
        cell = new PdfPCell(Image.getInstance(aidger));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(0);
        table.addCell(cell);
        table.writeSelectedRows(0, -1, 0, 25, contentByte);
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.beimax.talenttree.AbstractPageGenerator.java

License:Open Source License

/**
 * add footer information to page, copyright, etc.
 *//*from   ww  w. j a v  a 2s .com*/
protected void addFooter() throws Exception {
    // draw legend text
    canvas.beginText();
    canvas.setFontAndSize(generator.getFontRegular(), 6f);
    canvas.setColorFill(BaseColor.BLACK);
    canvas.showTextAligned(Element.ALIGN_LEFT, getLocalizedString("copyright"), getLeftX(),
            PDFGenerator.marginVertical, 0);
    canvas.showTextAligned(Element.ALIGN_RIGHT,
            "Version " + getLocalizedString("version") + "  " + getLocalizedString("date") + "  "
                    + getLocalizedString("game") + "  http://auxc.de/18w",
            getRightX(), PDFGenerator.marginVertical, 0);
    canvas.endText();
}