Example usage for com.itextpdf.text Element ALIGN_LEFT

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

Introduction

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

Prototype

int ALIGN_LEFT

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

Click Source Link

Document

A possible value for paragraph alignment.

Usage

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 www  . j  a va  2s .c om

    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.CrearPDF.java

/**
 * We create a PDF document with iText using different elements to learn 
 * to use this library.//from  w  w w .j av  a2 s. c o m
 * Creamos un documento PDF con iText usando diferentes elementos para aprender 
 * a usar esta librera.
 * @param pdfNewFile  <code>String</code> 
 *      pdf File we are going to write. 
 *      Fichero pdf en el que vamos a escribir. 
 */
//    public void createPDF(File pdfNewFile, ReparacionEntity reparacion) throws Exception {
public void createPDF(File pdfNewFile) throws Exception {
    // We create the document and set the file name.        
    // Creamos el documento e indicamos el nombre del fichero.
    try {
        //            ClienteController cc = new ClienteController();
        //            Cliente cliente = cc.buscarPorId(reparacion.getCliente());
        Document document = new Document();
        try {

            PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));

        } catch (FileNotFoundException fileNotFoundException) {
            System.out.println("No such file was found to generate the PDF "
                    + "(No se encontr el fichero para generar el pdf)" + fileNotFoundException);
        }
        document.open();
        // We add metadata to PDF
        // Aadimos los metadatos del PDF
        document.addTitle("Table export to PDF (Exportamos la tabla a PDF)");
        document.addSubject("Using iText (usando iText)");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Cdigo Xules");
        document.addCreator("Cdigo Xules");

        // First page
        // Primera pgina 
        Chunk chunk = new Chunk("RDEN DE TRABAJO", categoryFont);
        Chunk c2 = new Chunk("\n\n\nCentro de Formacin SATCAR6\n" + "Calle Artes Grficas n1 Nave 12 A\n"
                + "Pinto (28320), Madrid", smallFont);

        Chunk c3 = new Chunk("Datos del Cliente", smallBold);
        //            Chunk c4 = new Chunk("Nombre: "+cliente.getRazonSocial(),smallBold);
        //            Chunk c5 = new Chunk("Poblacin: "+cliente.getPoblacion(),smallBold);
        //            Chunk c6 = new Chunk("Provincia: "+cliente.getProvincia(),smallBold);
        //            Chunk c7 = new Chunk("Cdigo Postal: "+cliente.getCp(),smallBold);
        //            Chunk c8 = new Chunk("Num Telfono: Pepito"+cliente.getTlf1(),smallBold);
        Chunk c4 = new Chunk("Nombre: Jesus Eduardo Garcia Toril", smallBold);
        Chunk c5 = new Chunk("Poblacin: Pinto", smallBold);
        Chunk c6 = new Chunk("Provincia: Madrid", smallBold);
        Chunk c7 = new Chunk("Cdigo Postal: 28320", smallBold);
        Chunk c8 = new Chunk("Num Telfono: 659408182", smallBold);

        Paragraph parrafo = new Paragraph(chunk);
        Paragraph p2 = new Paragraph(c2);
        Paragraph p3 = new Paragraph(c3);
        Phrase ph1 = new Phrase(c4);
        Phrase ph2 = new Phrase(c5);
        Phrase ph3 = new Phrase(c6);
        Phrase ph4 = new Phrase(c7);
        Phrase ph5 = new Phrase(c8);

        // Let's create de first Chapter (Creemos el primer captulo)

        // We add an image (Aadimos una imagen)
        Image image;
        try {
            parrafo.setAlignment(Element.ALIGN_CENTER);
            image = Image.getInstance(iTextExampleImage);
            image.setAbsolutePosition(0, 750);
            p2.setAlignment(Element.ALIGN_LEFT);
            document.add(parrafo);
            document.add(image);
            document.add(p2);
            document.add(p3);
            document.add(ph1);
            document.add(ph2);
            document.add(ph3);
            document.add(ph4);
            document.add(ph5);

        } catch (BadElementException ex) {
            System.out.println("Image BadElementException" + ex);
        }

        // Second page - some elements
        // Segunda pgina - Algunos elementos

        // List by iText (listas por iText)
        String text = "test 1 2 3 ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        List list = new List(List.UNORDERED);
        ListItem item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "a b c align ";
        for (int i = 0; i < 5; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);
        text = "supercalifragilisticexpialidocious ";
        for (int i = 0; i < 3; i++) {
            text = text + text;
        }
        item = new ListItem(text);
        item.setAlignment(Element.ALIGN_JUSTIFIED);
        list.add(item);

        // How to use PdfPTable
        // Utilizacin de PdfPTable

        // We use various elements to add title and subtitle
        // Usamos varios elementos para aadir ttulo y subttulo
        Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont);
        anchor.setName("Table export to PDF (Exportamos la tabla a PDF)");
        Chapter chapTitle = new Chapter(new Paragraph(anchor), 1);
        Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont);
        Section paragraphMore = chapTitle.addSection(paragraph);
        paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)"));
        Integer numColumns = 6;
        Integer numRows = 120;
        // We create the table (Creamos la tabla).
        PdfPTable table = new PdfPTable(numColumns);
        // Now we fill the PDF table 
        // Ahora llenamos la tabla del PDF
        PdfPCell columnHeader;
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int column = 0; column < numColumns; column++) {
            columnHeader = new PdfPCell(new Phrase("COL " + column));
            columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(columnHeader);
        }
        table.setHeaderRows(1);
        // Fill table rows (rellenamos las filas de la tabla).                
        for (int row = 0; row < numRows; row++) {
            for (int column = 0; column < numColumns; column++) {
                table.addCell("Row " + row + " - Col" + column);
            }
        }
        // We add the table (Aadimos la tabla)
        paragraphMore.add(table);
        // We add the paragraph with the table (Aadimos el elemento con la tabla).
        document.add(chapTitle);
        document.close();
        System.out.println("Your PDF file has been generated!(Se ha generado tu hoja PDF!");
    } catch (DocumentException documentException) {
        System.out.println(
                "The file not exists (Se ha producido un error al generar un documento): " + documentException);
    }
}

From source file:controller.DownloadCVServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from ww  w. j a  v  a2 s . co m*/
 * @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 {
    //protect servlet
    HttpSession session = request.getSession();
    Admin loggedInAdmin = (Admin) session.getAttribute("admin");

    //check if admin is logged in
    if (loggedInAdmin == null) {
        response.sendRedirect("login.jsp");
        return;
    }

    String[] appIDs = request.getParameterValues("download");

    ServletOutputStream sOut = response.getOutputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    //prepare fonts
    Font font = FontFactory.getFont("Arial", 10);

    for (String appIDStr : appIDs) {
        int appID = Integer.parseInt(appIDStr);
        Application application = ApplicationDAO.retrieveByAppID(appID);
        Job job = JobDAO.retrieveJobById(application.getJobID());

        ZipEntry entry = new ZipEntry(application.getFullname() + "_CV.pdf");
        zos.putNextEntry(entry);

        String path = System.getenv("OPENSHIFT_DATA_DIR");

        if (path == null) {
            path = getServletContext().getRealPath("/templates/Personal_Particulars_Form.pdf");
        } else {
            path += "Personal_Particulars_Form.pdf";
        }

        try {
            //Prepare PdfStamper
            PdfReader reader = new PdfReader(path);
            PdfStamper stamper = new PdfStamper(reader, zos);
            stamper.setRotateContents(false);
            stamper.getWriter().setCloseStream(false);

            //Get first page
            PdfContentByte canvas = stamper.getOverContent(1);

            //Application ID
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getAppID() + "", font), 110, 555, 0);

            //Date Applied
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getDateApplied(), font), 110, 526, 0);

            //Position Applied
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(job.getPostingTitle(), font), 36,
                    442, 0);

            //Job ID
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getJobID() + "", font), 405, 442, 0);

            //Name
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getFullname(), font),
                    36, 350, 0);

            //Street
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getBlkStreetUnit(), font), 36, 305, 0);

            //Postal Code
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getPostalCode(), font), 377, 305, 0);

            //Nationality
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNricType(), font),
                    36, 260, 0);

            //NRIC
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getNric(), font), 289,
                    260, 0);

            //DOB
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getDob(), font), 36,
                    215, 0);

            //Gender
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getGender(), font),
                    379, 215, 0);

            //Contact Number
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(application.getContactNo(), font),
                    36, 170, 0);

            //Email Address
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(application.getEmailAddress(), font), 36, 125, 0);

            //Declaration
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("X", font), 50, 80, 0);

            //Generated on
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
            Date date = new Date();
            String today = dateFormat.format(date);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(today, font), 437, 15, 0);

            stamper.close();
            reader.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    zos.close();
    response.setContentType("application/zip");
    response.addHeader("Content-Disposition", "attachment; filename=CVs.zip");

    sOut.write(baos.toByteArray());
    sOut.close();
}

From source file:Controller.PrintOrderManagedBean.java

public void executePDF(String maDH) {
    try {/*from w  w  w. ja  va  2s.  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 w w w.j av a  2  s .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:de.aidger.utils.pdf.ActivityReportConverter.java

License:Open Source License

/**
 * Writes the logos and the address of the institute.
 *///from  w  w w . j  a v  a2  s.  com
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.
 *//*w  w  w .  j  a  v a  2  s .c o  m*/
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();
}

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

License:Open Source License

/**
 * Add single talent in box/*from w w w  .j  a  v a  2s . co  m*/
 * @param row row to print talent in
 * @param col column to print talent in
 * @param key key for talent information
 * @param multiCols span multiple columns or 1
 * @param customCost custom cost of talent (instead of default) - 0 means box will not be printed
 */
protected void addTalent(int row, int col, String key, int multiCols, int customCost) throws Exception {
    // get data
    HeaderProperties headerProperties = parseHeaderProperty(key);

    // define color
    BaseColor bgColor = headerProperties.active ? PDFGenerator.activeColor : PDFGenerator.passiveColor;
    boolean headerTwoLine = headerProperties.title.contains("\n");

    // calculate offsets
    float x = calculateColOffset(col);
    float y = calculateRowOffset(row);

    // sanity check for multiple columns
    if (multiCols < 1)
        multiCols = 1;
    else if (multiCols > 4)
        multiCols = 4;

    // box width and height
    float talentBoxWidth = PDFGenerator.talentBoxWidth * multiCols
            + calculateHorizontalSpacing() * (multiCols - 1);
    float talentBoxHeight = PDFGenerator.talentBoxHeight;

    // draw shapes
    canvas.saveState();
    // draw outer rectangle
    drawTalentRectangle(bgColor, x, y, talentBoxWidth, talentBoxHeight);
    // draw left footer shape
    float yFooterBoxOffset = y - talentBoxHeight + PDFGenerator.talentBoxStroke;
    if (customCost != 0) {
        drawFooterShape(bgColor, x + PDFGenerator.wedgeOffset + PDFGenerator.talentBoxStroke,
                y - talentBoxHeight + PDFGenerator.talentBoxStroke, 25);
    }
    // draw right footer shape
    drawFooterShape(bgColor, x + talentBoxWidth - PDFGenerator.wedgeOffset - PDFGenerator.talentBoxStroke - 50,
            y - talentBoxHeight + PDFGenerator.talentBoxStroke, 50);
    // draw header shape
    drawHeaderShape(bgColor, x + PDFGenerator.talentBoxStroke * 2.5f, y - PDFGenerator.talentBoxStroke * 2.5f,
            talentBoxWidth - PDFGenerator.talentBoxStroke * 5, headerTwoLine, headerProperties.status);
    canvas.restoreState();

    // draw text
    canvas.beginText();
    canvas.setColorFill(BaseColor.WHITE);
    // title
    canvas.setFontAndSize(generator.getFontHeader(), 13);
    float offSetYTalentText;
    if (headerTwoLine) {
        String[] parts = headerProperties.title.split("\\n");
        canvas.showTextAligned(Element.ALIGN_LEFT, parts[0], x + PDFGenerator.talentBoxStroke * 3.5f,
                y - PDFGenerator.talentBoxStroke * 2 - 14f, 0);
        canvas.showTextAligned(Element.ALIGN_LEFT, parts[1], x + PDFGenerator.talentBoxStroke * 3.5f,
                y - PDFGenerator.talentBoxStroke * 2 - 27f, 0);
        offSetYTalentText = y - PDFGenerator.talentBoxStroke * 2 - 28f;
    } else {
        canvas.showTextAligned(Element.ALIGN_LEFT, headerProperties.title,
                x + PDFGenerator.talentBoxStroke * 3.5f, y - PDFGenerator.talentBoxStroke * 2 - 14f, 0);
        offSetYTalentText = y - PDFGenerator.talentBoxStroke * 2 - 15f;
    }
    // mini text
    canvas.setFontAndSize(generator.getFontBold(), 6.25f);
    float textOffsetY = yFooterBoxOffset + 8 - 6.25f / 2 + 0.5f;
    // draw page
    canvas.showTextAligned(Element.ALIGN_CENTER, headerProperties.page,
            x + PDFGenerator.wedgeOffset + PDFGenerator.talentBoxStroke + 25f / 2, textOffsetY, 0);
    // draw costs
    if (customCost != 0) {
        if (customCost == -1)
            customCost = (row + 1) * 5;
        canvas.showTextAligned(Element.ALIGN_LEFT, getLocalizedString("Cost") + " " + customCost,
                x + talentBoxWidth - PDFGenerator.talentBoxStroke - 50, textOffsetY, 0);
    }
    canvas.endText();

    // draw talent text
    canvas.setColorFill(BaseColor.BLACK);
    PdfPTable table = getTalentCell(key, talentBoxWidth, 9f);
    // too large?
    float max = y - talentBoxHeight;
    if (table.getRowHeight(0) > offSetYTalentText - max - 2 * PDFGenerator.wedgeOffset)
        table = getTalentCell(key, talentBoxWidth, 8.5f); // create smaller cell
    if (table.getRowHeight(0) > offSetYTalentText - max - 2 * PDFGenerator.wedgeOffset)
        table = getTalentCell(key, talentBoxWidth, 7.5f); // create tiny cell
    table.writeSelectedRows(0, -1, x + PDFGenerator.talentBoxStroke * 1.5f, offSetYTalentText, canvas);
}

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

License:Open Source License

/**
 * get celled talent text//from   ww  w .  j  a va  2 s. co  m
 * @param key
 * @param talentBoxWidth
 * @param fontSize
 * @return
 * @throws Exception
 */
protected PdfPTable getTalentCell(String key, float talentBoxWidth, float fontSize) throws Exception {
    // get phrase
    Phrase phrase = parseTextProperty(key, fontSize, true);

    // table text
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(talentBoxWidth - PDFGenerator.talentBoxStroke * 3);
    table.setLockedWidth(true);
    PdfPCell cell = new PdfPCell(phrase);
    cell.setBorder(0);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.addCell(cell);
    table.completeRow();

    return table;
}

From source file:de.fau.osr.util.matrix.MatrixTools.java

License:Open Source License

/**
 * /**//from w w  w. j  a v  a 2  s  . com
 * saves matrix to {@code path} in pdf format
 * @param matrix matrix to save
 * @param path file where matrix will be saved
 */
public static boolean SaveMatrixToPdf(RequirementsTraceabilityMatrixByImpact matrix, File path,
        String matrixTitle) {
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(path));
        document.open();
        document.addTitle(matrixTitle);

        Paragraph headerPar = new Paragraph("Traceability Matrix");
        headerPar.add(new Paragraph(" ")); //new line
        document.add(headerPar);

        java.util.List<String> reqs = matrix.getRequirements();

        //table setup
        PdfPTable table = new PdfPTable(reqs.size() + 1); //reqs + "file name" col
        table.setHeaderRows(1);
        table.setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
        table.setWidthPercentage(100);
        table.setSpacingBefore(0);
        table.setSpacingAfter(0);

        //file name col width/req col width 4:1
        float[] widths = new float[reqs.size() + 1];
        widths[0] = 4;
        for (int i = 0; i < reqs.size(); i++) {
            widths[i + 1] = 1;
        }
        table.setWidths(widths);

        //header row
        //add filename col to header
        addCell(table, "File name", 10, Element.ALIGN_LEFT);
        //add req cols to header
        for (String req : reqs) {
            addCell(table, "req-" + req, 8, Element.ALIGN_CENTER);
        }
        //content, row by row:
        for (int i = 0; i < matrix.getFiles().size(); i++) {
            //filename col
            String fileName = matrix.getFiles().get(i);
            addCell(table, fileName, 5, Element.ALIGN_LEFT, 18);

            //impact value cols
            for (String req : reqs) {
                RequirementFileImpactValue value = matrix
                        .getImpactValue(new RequirementFilePair(req, fileName));
                if (value == null) {
                    value = new RequirementFileImpactValue(0);
                }
                //round
                DecimalFormat df = new DecimalFormat("#.##");
                df.setRoundingMode(RoundingMode.CEILING);
                String valString = df.format(value.getImpactPercentage());

                addCell(table, valString, 10, Element.ALIGN_CENTER);
            }
        }

        document.add(table);

    } catch (DocumentException | FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } finally {
        document.close();
    }
    return true;

}