Example usage for com.lowagie.text FontFactory HELVETICA

List of usage examples for com.lowagie.text FontFactory HELVETICA

Introduction

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

Prototype

String HELVETICA

To view the source code for com.lowagie.text FontFactory HELVETICA.

Click Source Link

Document

This is a possible value of a base 14 type 1 font

Usage

From source file:displayStructureAsPDFTable.java

License:Open Source License

private void addTitle(IAtomContainer mol, Phrase phrase) {
    if (mol.getProperty(CDKConstants.TITLE) == null
            || mol.getProperty(CDKConstants.TITLE).toString().trim().length() == 0)
        return;//w  ww.j a va 2  s.  c om
    phrase.add(new Chunk(CDKConstants.TITLE + ": ", FontFactory.getFont(FontFactory.HELVETICA_BOLD)));
    phrase.add(
            new Chunk(mol.getProperty(CDKConstants.TITLE) + "\n", FontFactory.getFont(FontFactory.HELVETICA)));
}

From source file:displayStructureAsPDFTable.java

License:Open Source License

private void addProperty(Object propertyLabel, IAtomContainer mol, Phrase phrase) {
    if (mol.getProperty(propertyLabel) == null
            || mol.getProperty(propertyLabel).toString().trim().length() == 0)
        return;// w ww.j a  v a2  s.c  om

    phrase.add(new Chunk(propertyLabel + ": ", FontFactory.getFont(FontFactory.HELVETICA_BOLD)));
    String value;
    try {
        double tmp = Double.parseDouble(mol.getProperty(propertyLabel).toString());
        value = decimalFormat.format(tmp);
    } catch (NumberFormatException nfe) {
        value = mol.getProperty(propertyLabel).toString();
    }
    phrase.add(new Chunk(value + "\n", FontFactory.getFont(FontFactory.HELVETICA)));
}

From source file:appli_etudiants.ExportPDF.java

public static void main(Etudiants etudiant)
        throws SQLException, FileNotFoundException, BadElementException, IOException {
    try {/* w  w  w .j a v a 2  s . c  om*/
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/tesPDF.pdf"));
        document.open();
        PdfContentByte canvas = writer.getDirectContentUnder();
        Image image = Image.getInstance("c:/fond_cv.jpg");
        image.setAbsolutePosition(0, 80);
        canvas.saveState();
        PdfGState state = new PdfGState();
        state.setFillOpacity(0.6f);
        canvas.setGState(state);
        canvas.addImage(image);
        canvas.restoreState();

        LineSeparator lineSepa = new LineSeparator();
        lineSepa.setLineColor(new Color(21, 96, 189));
        Paragraph para1 = new Paragraph();
        Paragraph para2 = new Paragraph(etudiant.getAdresse_rue());
        Paragraph para3 = new Paragraph(etudiant.getAdresse_cp() + " " + etudiant.getAdresse_ville());
        Paragraph para4 = new Paragraph(etudiant.getCourriel(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189)));
        Paragraph para5 = new Paragraph(etudiant.getTel_personnel());
        Paragraph para6 = new Paragraph(etudiant.getTel_professionnel());
        Paragraph para7 = new Paragraph(etudiant.getSite_web());
        para1.add(new Chunk(etudiant.getPrenom(),
                FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD, new Color(21, 96, 189))));
        para1.add(
                new Chunk(" " + etudiant.getNom(), FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD)));

        Image image1 = Image.getInstance(DaoS4.getPhoto());
        image1.scalePercent(50);
        image1.setAlignment(Image.RIGHT | Image.TEXTWRAP);
        image1.scaleAbsolute(94, 94);
        document.add(image1);

        document.add(para1);
        document.add(para2);
        document.add(para3);
        document.add(para4);
        document.add(para5);
        document.add(para6);
        para7.setSpacingAfter(25f);
        document.add(para7);
        Paragraph para8 = new Paragraph(DaoS4.getLibelleTitre());
        para8.setSpacingBefore(25f);
        para8.setSpacingAfter(20f);
        document.add(para8);

        Paragraph para9 = new Paragraph(new Chunk("EXPERIENCE PROFESSIONELLE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para9.setSpacingBefore(15f);
        para9.setSpacingAfter(15f);
        document.add(para9);
        document.add(lineSepa);
        Paragraph para10 = new Paragraph(DaoS4.getLibelleExpPro());
        para10.setSpacingAfter(15f);
        document.add(para10);

        Paragraph para11 = new Paragraph(new Chunk("FORMATION",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para11.setSpacingBefore(15f);
        para11.setSpacingAfter(15f);
        document.add(para11);
        document.add(lineSepa);
        Paragraph para12 = new Paragraph(DaoS4.getLibelleFormation());
        para12.setSpacingAfter(15f);
        document.add(para12);

        Paragraph para13 = new Paragraph(new Chunk("INFORMATIQUE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para13.setSpacingBefore(15f);
        para13.setSpacingAfter(15f);
        document.add(para13);
        document.add(lineSepa);
        Paragraph para14 = new Paragraph(DaoS4.getLibelleInformatique());
        para14.setSpacingAfter(15f);
        document.add(para14);

        Paragraph para15 = new Paragraph(new Chunk("LANGUE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para15.setSpacingBefore(15f);
        para15.setSpacingAfter(15f);
        document.add(para15);
        document.add(lineSepa);
        Paragraph para16 = new Paragraph(DaoS4.getLibelleLangue());
        para16.setSpacingAfter(15f);
        document.add(para16);

        Paragraph para17 = new Paragraph(new Chunk("CENTRES D'INTERET",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para17.setSpacingBefore(15f);
        para17.setSpacingAfter(15f);
        document.add(para17);
        document.add(lineSepa);
        Paragraph para18 = new Paragraph(DaoS4.getLibelleInteret());
        para18.setSpacingAfter(15f);
        document.add(para18);

        document.close();
    } catch (DocumentException ex) {
        Logger.getLogger(ExportPDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.com.moises.servlet.Embarque.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    out.print("Pasou auqe");

    try {/*w  w  w.j av  a 2s. co  m*/
        Document document = new Document(PageSize.A4, 30, 20, 20, 30);
        OutputStream outputStream = new FileOutputStream("embarque.pdf");
        //   response.setContentType("application/pdf");
        Long id = Long.parseLong(request.getParameter("num_embarque"));
        //recupera o embarque
        embarque = embarqueSuport.getEmbarqueById(id);
        itens = itSuport.itensEmbarquePorEmbarque(embarque);
        out.print(itens.size());

        PdfWriter.getInstance(document, response.getOutputStream());

        document.open();
        // Titulo

        document.addTitle("Comprovante de Coleta");

        Paragraph titulo = new Paragraph("Comprovante de Coleta");
        //            //
        document.add(titulo);
        document.add(new Paragraph("\n\n"));
        PdfPTable topo = new PdfPTable(2);
        Image image = Image.getInstance("E:\\icons\\32\\cliente.png");

        topo.getDefaultCell().setBorder(0);
        topo.getDefaultCell().addElement(image);
        topo.addCell(image);
        topo.addCell("MOISES JUVENAL DA SILVA\n" + "Rua.: Bertioga N 49" + "Jardim Amrica I"
                + "Vrzea Paulista SP");

        document.add(topo);
        document.add(new Paragraph(
                "-------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph(
                "TRANSP.: " + embarque.getTransportadora().getId() + " - "
                        + embarque.getTransportadora().getNome(),
                FontFactory.getFont(FontFactory.HELVETICA, 14, Color.BLUE)));
        document.add(new Paragraph(
                "-------------------------------------------------------------------------------------------------------------------"));
        document.add(new Paragraph(new Date().toString()));

        PdfPTable table = new PdfPTable(2);
        table.addCell("");

        for (ItensEmbarque l : itens) {
            document.add(new Paragraph(String.valueOf(l.getId())));
        }
        // step 5
        document.close();
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }

}

From source file:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito,
        boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal,
        Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException {

    PdfReader pdfIn = new PdfReader(abPdf);
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    // final SimpleDateFormat sdf = new SimpleDateFormat(
    // "EEE MMM dd HH:mm:ss zzz yyyy");
    // doc.add(new Meta("creationdate", sdf.format(new Date(0L))));
    final ByteArrayOutputStream boA4 = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(doc, boA4);
    doc.open();//  w ww  .j a va2s.c  o  m
    PdfContentByte cb = writer.getDirectContent();

    // Resize every page to A4 size
    //
    // double thetaRotation = 0.0;
    for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) {
        int rot = pdfIn.getPageRotation(i);
        float left = pdfIn.getPageSize(i).getLeft();
        float bottom = pdfIn.getPageSize(i).getBottom();
        float top = pdfIn.getPageSize(i).getTop();
        float right = pdfIn.getPageSize(i).getRight();

        PdfImportedPage page = writer.getImportedPage(pdfIn, i);
        float w = page.getWidth();
        float h = page.getHeight();

        // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w
        // + ", " + h);

        doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4);
        doc.newPage();

        cb.saveState();

        if (rot != 0 && rot != 180) {
            float swap = w;
            w = h;
            h = swap;
        }

        float pw = doc.getPageSize().getWidth();
        float ph = doc.getPageSize().getHeight();
        double scale = Math.min(pw / w, ph / h);

        // do my transformations :
        cb.transform(AffineTransform.getScaleInstance(scale, scale));

        if (!internoProduzido) {
            cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN));
            cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN));
        }

        if (rot != 0) {
            double theta = -rot * (Math.PI / 180);
            if (rot == 180) {
                cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2));
            } else {
                cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2));
            }
            if (rot == 90) {
                cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2));
            } else if (rot == 270) {
                cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2));
            }
        }

        // Logger.getRootLogger().error(
        // "----- dimensoes: " + rot + ", " + w + ", " + h);
        // Logger.getRootLogger().error("----- page: " + pw + ", " + ph);

        // cb.transform(AffineTransform.getTranslateInstance(
        // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2));

        // put the page
        cb.addTemplate(page, 0, 0);

        // draw a red rectangle at the page borders
        //
        // cb.saveState();
        // cb.setColorStroke(Color.red);
        // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i)
        // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn
        // .getPageSize(i).getTop());
        // cb.stroke();
        // cb.restoreState();

        cb.restoreState();
    }
    doc.close();

    abPdf = boA4.toByteArray();

    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();

    final PdfReader reader = new PdfReader(abPdf);

    final int n = reader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(reader, bo2);

    // adding content to each page
    int i = 0;
    PdfContentByte under;
    PdfContentByte over;
    final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    // Image img = Image.getInstance("watermark.jpg");
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    byte maskr[] = { (byte) 0xff };
    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
    mask.makeMask();
    mask.setInverted(true);

    while (i < n) {
        i++;
        // watermark under the existing page
        under = stamp.getUnderContent(i);
        over = stamp.getOverContent(i);

        final Barcode39 code39 = new Barcode39();
        // code39.setCode(doc.getCodigo());
        code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", ""));
        code39.setStartStopText(false);
        final Image image39 = code39.createImageWithBarcode(over, null, null);
        Rectangle r = stamp.getReader().getPageSizeWithRotation(i);

        image39.setInitialRotation((float) Math.PI / 2.0f);
        image39.setAbsolutePosition(
                r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT,
                BARCODE_HEIGHT_IN_CM * CM_UNIT);

        image39.setBackgroundColor(Color.green);
        image39.setBorderColor(Color.RED);
        image39.setBorderWidth(0.5f * CM_UNIT);

        image39.setImageMask(mask);

        over.setRGBColorFill(255, 255, 255);
        mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT,
                (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
        mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT,
                image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT);
        over.addImage(mask);

        over.setRGBColorFill(0, 0, 0);
        over.addImage(image39);

        // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0,
        // mask.getScaledHeight() * 8, 100, 450);

        if (qrCode != null) {
            java.awt.Image imgQRCode = createQRCodeImage(qrCode);
            Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true);
            imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT);
            imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT);
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            over.addImage(imageQRCode);
        }

        if (mensagem != null) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM
                    + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT);
            PdfPCell cell = new PdfPCell(new Paragraph(mensagem,
                    FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK)));
            cell.setBorderWidth(0);
            table.addCell(cell);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition(
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(),
                    2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight());
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            table.writeSelectedRows(0, -1,
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over);
        }

        if (cancelado) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (rascunho) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (semEfeito) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // if (!rascunho
        // && request.getRequestURL().indexOf("http://laguna/") == -1) {

        if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false"))
                || (!Contexto.resource("isBaseTest").equals("false")))) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // Imprime um circulo com o numero da pagina dentro.

        if (paginaInicial != null) {
            String sFl = String.valueOf(paginaInicial + i - 1);
            // Se for a ultima pagina e o numero nao casar, acrescenta "-" e
            // pagina final
            if (n == i) {
                if (paginaFinal != paginaInicial + n - 1) {
                    sFl = sFl + "-" + String.valueOf(paginaFinal);
                }
            }
            if (i > cOmitirNumeracao) {

                // Raio do circulo interno
                final float radius = 18f;

                // Distancia entre o circulo interno e o externo
                final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT),
                        helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT))
                        - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT),
                                helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT))
                        + 2 * TEXT_TO_CIRCLE_INTERSPACE;

                // Centro do circulo
                float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace);
                float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace);

                over.saveState();
                final PdfGState gs = new PdfGState();
                gs.setFillOpacity(1f);
                over.setGState(gs);
                over.setColorFill(Color.BLACK);

                over.saveState();
                over.setColorStroke(Color.black);
                over.setLineWidth(1f);
                over.setColorFill(Color.WHITE);

                // Circulo externo
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.fill();
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.stroke();

                // Circulo interno
                over.circle(xCenter, yCenter, radius);
                over.stroke();
                over.restoreState();

                {
                    over.saveState();
                    over.beginText();
                    over.setFontAndSize(helv, TEXT_HEIGHT);

                    // Escreve o texto superior do carimbo
                    float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT);
                    showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true);

                    // Escreve o texto inferior
                    float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT);
                    showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false);
                    over.endText();
                    over.restoreState();
                }

                over.beginText();
                int textHeight = 23;

                // Diminui o tamanho do font ate que o texto caiba dentro do
                // circulo interno
                while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
                    textHeight--;
                float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
                over.setFontAndSize(helv, textHeight);
                over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
                over.endText();
                over.restoreState();
            }
        }

    }
    stamp.close();
    return bo2.toByteArray();
}

From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java

License:Open Source License

public static boolean geraRelatorio(File file) {
    TradGeraRelatorioPDF.carregaTexto(TokenLang.LANG);
    Document document = new Document(PageSize.A4);
    try {//ww  w  . j  a  v  a2  s . c  o m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setPageEvent(new HeaderAndFooter());
        document.open();
        int linha = 0, j, tot_pg = ResumoDoRelatorio.getTotPage();
        //calcula o total de htmls
        float tot_link = 0.0f;
        for (j = 1; j <= tot_pg; j++) {
            String conteudo = ResumoDoRelatorio.getPage(j);
            String arr[] = conteudo.split("\n");
            tot_link += arr.length;
        }
        PainelStatusBar.showProgTarReq();
        //loop por todas as pginas da paginacao
        for (j = 1; j <= tot_pg; j++) {
            String conteudo = ResumoDoRelatorio.getPage(j);
            String arr[] = conteudo.split("\n");
            int tot = arr.length;
            int i;
            //loop por todos os links
            for (i = 0; i < tot; i++) {
                progresso = (linha++ / tot_link) * 100.0f;
                PainelStatusBar.setValueProgress((int) progresso);
                String arr2[] = arr[i].split("\t");

                if (arr2.length == 8) {

                    String strUrl = arr2[7];// URL
                    /*
                    int ap1 = Integer.parseInt(arr2[4]);// Aviso1
                    int ep1 = Integer.parseInt(arr2[1]);// Erro1
                    int ap2 = Integer.parseInt(arr2[5]);// Aviso2
                    int ep2 = Integer.parseInt(arr2[2]);// Erro2
                    int ap3 = Integer.parseInt(arr2[6]);// Aviso3
                    int ep3 = Integer.parseInt(arr2[3]);// Erro3
                    */
                    String myHash = arr2[0];

                    RelatorioDaUrl relatorio = new RelatorioDaUrl();
                    relatorio.recarregaArquivoRelatorioEmXml2(myHash);

                    document.add(new Phrase("\n"));
                    Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);

                    Chunk url = new Chunk(strUrl, font);
                    Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL);
                    p1.add(url);
                    p1.setAlignment(Paragraph.ALIGN_LEFT);
                    document.add(p1);
                    document.add(new Phrase("\n\n"));

                    if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0
                            && relatorio.getErrosPrioridade3() <= 0) {
                        Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS);
                        p2.setAlignment(Paragraph.ALIGN_CENTER);
                        document.add(p2);

                    } else {

                        if (relatorio.getErrosPrioridade1() > 0) {
                            Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1, font);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            document.add(p);
                            document.add(new Chunk("\n"));
                            PdfPTable table = geraLista(relatorio.getListaErrosP1());
                            if (table != null) {
                                document.add(table);
                            }
                            document.add(new Phrase("\n\n"));
                        }

                        if (relatorio.getErrosPrioridade2() > 0) {
                            Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2, font);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            document.add(p);
                            document.add(new Chunk("\n"));
                            PdfPTable table = geraLista(relatorio.getListaErrosP2());
                            if (table != null) {
                                document.add(table);
                            }
                            document.add(new Phrase("\n\n"));
                        }

                        if (relatorio.getErrosPrioridade3() > 0) {
                            Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3, font);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            document.add(p);
                            document.add(new Chunk("\n"));
                            PdfPTable table = geraLista(relatorio.getListaErrosP3());
                            if (table != null) {
                                document.add(table);
                            }
                            document.add(new Phrase("\n\n"));
                        }
                        document.newPage();
                    }
                }
            }
        }
        writer.flush();
        document.close();
    } catch (DocumentException de) {
        log.error(de.getMessage(), de);
        PainelStatusBar.hideProgTarReq();
        return false;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        PainelStatusBar.hideProgTarReq();
        return false;
    }
    PainelStatusBar.hideProgTarReq();
    return true;
}

From source file:br.org.acessobrasil.silvinha.util.GeraRelatorioPDF.java

License:Open Source License

public static boolean geraRelatorio_bkp(File file, ResumoDoRelatorio resumo) {

    Document document = new Document(PageSize.A4);
    try {/*ww w. j  a  va  2 s .  c o m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setPageEvent(new HeaderAndFooter());
        document.open();

        ArrayList<RelatorioDaUrl> relatorios = resumo.getRelatorios();
        loop: for (RelatorioDaUrl relatorio : relatorios) {
            document.add(new Phrase("\n"));
            Font font = FontFactory.getFont(FontFactory.HELVETICA, Font.DEFAULTSIZE, Font.BOLD);

            Chunk url = new Chunk(relatorio.getUrl(), font);
            Paragraph p1 = new Paragraph(TradGeraRelatorioPDF.RELATORIO_URL);
            p1.add(url);
            p1.setAlignment(Paragraph.ALIGN_LEFT);
            document.add(p1);
            document.add(new Phrase("\n\n"));

            if (relatorio.getErrosPrioridade1() <= 0 && relatorio.getErrosPrioridade2() <= 0
                    && relatorio.getErrosPrioridade3() <= 0) {
                Paragraph p2 = new Paragraph(TradGeraRelatorioPDF.PAGINAS_SEM_ERROS);
                p2.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(p2);
                continue loop;
            }

            if (relatorio.getErrosPrioridade1() > 0) {
                Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P1_SEM_TAB, font);
                p1.setAlignment(Paragraph.ALIGN_LEFT);
                document.add(p);
                document.add(new Chunk("\n"));
                PdfPTable table = geraLista(relatorio.getListaErrosP1());
                if (table != null) {
                    document.add(table);
                }
                document.add(new Phrase("\n\n"));
            }

            if (relatorio.getErrosPrioridade2() > 0) {
                Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P2_SEM_TAB, font);
                p1.setAlignment(Paragraph.ALIGN_LEFT);
                document.add(p);
                document.add(new Chunk("\n"));
                PdfPTable table = geraLista(relatorio.getListaErrosP2());
                if (table != null) {
                    document.add(table);
                }
                document.add(new Phrase("\n\n"));
            }

            if (relatorio.getErrosPrioridade3() > 0) {
                Paragraph p = new Paragraph(TradGeraRelatorioPDF.ERROS_P3_SEM_TAB, font);
                p1.setAlignment(Paragraph.ALIGN_LEFT);
                document.add(p);
                document.add(new Chunk("\n"));
                PdfPTable table = geraLista(relatorio.getListaErrosP3());
                if (table != null) {
                    document.add(table);
                }
                document.add(new Phrase("\n\n"));
            }
            document.newPage();
        }

        writer.flush();
        document.close();
    } catch (DocumentException de) {
        log.error(de.getMessage(), de);
        return false;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        return false;
    }
    return true;
}

From source file:ch.gpb.elexis.cst.view.CstResultPart.java

License:Open Source License

private void makeActions(final Control viewer) {

    actionScreenshot = new Action() {
        public void run() {
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }//from  www  .ja  v  a  2 s. c o m

            GC gc = null;
            Image image = null;
            try {

                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.png", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }

                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                //if (profile.getAnzeigeTyp().toLowerCase().equals("effektiv")) {
                if (profile.getAnzeigeTyp().toLowerCase().equals(CstProfile.ANZEIGETYP_EFFEKTIV)) {

                    if (profile.getAusgabeRichtung()) {
                        image = new Image(viewer.getDisplay(), 1123, viewer.getBounds().height);

                    } else {
                        image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                    }
                } else {
                    image = new Image(viewer.getDisplay(), 794, viewer.getBounds().height);

                }

                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);

                gc.dispose();

                loader.data = new ImageData[] { image.getImageData() };
                loader.save(selected, SWT.IMAGE_PNG);

            } catch (Exception e) {
                log.error("Error saving png: " + e.toString());
                showMessage("Error while saving PNG", e.getMessage());
            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
            }

        }
    };
    actionScreenshot.setText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setToolTipText(Messages.Cst_Text_Save_as_png);
    actionScreenshot.setImageDescriptor(
            PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJ_ELEMENT));
    actionScreenshot.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PNG_PATH));

    // TODO: die pdf ausgabe ist eine ziemliche Baustelle - berarbeiten
    actionPdf = new Action() {
        public void run() {

            //////////////////////////
            if (profile == null) {
                SWTHelper.alert("No profile", "Ohne Profil kann kein Resultat erzeugt werden");
                return;
            }

            GC gc = null;
            Image image = null;
            try {
                String latestPath = CoreHub.userCfg.get(CstPreference.CST_IDENTIFIER_LATESTPATH, null);
                if (latestPath == null) {
                    latestPath = System.getProperty("user.home");
                }

                FileDialog fd = new FileDialog(baseComposite.getShell(), SWT.SAVE);
                fd.setText("Save");
                fd.setFilterPath(latestPath);
                String[] filterExt = { "*.pdf", "*.*" };
                fd.setFilterExtensions(filterExt);
                fd.setFileName(CstService.generateFilename(patient));
                String selected = fd.open();

                if (selected == null) {
                    return;
                }
                File selFile = new File(selected);

                CoreHub.userCfg.set(CstPreference.CST_IDENTIFIER_LATESTPATH,
                        selFile.getParentFile().getAbsolutePath());

                int printHeigth = 1123;
                int printWidth = 794;
                if (profile.getAusgabeRichtung()) {
                    printHeigth = 794;
                    printWidth = 1123;

                }

                // get the image from the viewport
                image = new Image(viewer.getDisplay(), printWidth, viewer.getBounds().height);
                ImageLoader loader = new ImageLoader();

                gc = new GC(image);
                viewer.print(gc);
                gc.dispose();

                // prepare title data
                //Date date = new Date();
                //SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy  HH:mm");

                Patient patient = Patient.load(profile.getKontaktId());
                //String sTitle = "Gemeinschaftspraxis Brunnmatt Dr. Beat Knzi ";
                String sTitle;
                sTitle = profile.getOutputHeader() == null ? "No header configured!"
                        : profile.getOutputHeader();

                if (sTitle == null || sTitle.length() == 0) {
                    sTitle = "No header configured!";
                }
                sTitle = sTitle + " Datum: " + CstService.getReadableDateAndTime();

                // get option (paging to A4/ in one piece)
                int pdfOutputOption = 0;
                boolean onePage = true;

                PdfOptionsDialog dialog = new PdfOptionsDialog(baseComposite.getShell());
                dialog.create();

                if (dialog.open() == Window.OK) {
                    pdfOutputOption = dialog.getPdfOutputOption();
                    if (pdfOutputOption == PdfOptionsDialog.OPTION_ONE_PAGE) {
                        onePage = true;
                    } else {

                        onePage = false;
                    }
                }

                float docHeight = viewer.getBounds().height;
                docHeight = docHeight / 7.5f;

                float fontSize = 12f;

                if (docHeight < 360f) {
                    docHeight = 360f;
                }

                BufferedImage bimage = ImageUtils.convertToAWT(image.getImageData());

                // create an Itextt Image from AWT BufferedImage
                com.lowagie.text.Image itextImage = null;
                java.awt.Image awtImage = null;

                try {
                    awtImage = Toolkit.getDefaultToolkit().createImage(bimage.getSource());
                    itextImage = com.lowagie.text.Image.getInstance(awtImage, null);

                } catch (Exception e) {
                    log.error("Error on image loading: " + e.toString());
                    e.printStackTrace();
                }

                // only for debugging

                //loader.data = new ImageData[] { image.getImageData() };
                //loader.save("C:\\Users\\daniel\\tmp\\debug.png", SWT.IMAGE_PNG);

                Rectangle pagesize = new Rectangle(595f, itextImage.getHeight() * 0.75f);

                // is it a4 quer?
                if (profile.getAusgabeRichtung()) {
                    pagesize = new Rectangle(842f, itextImage.getHeight() * 0.75f);

                }

                //System.out.println("pagesize: " + pagesize.toString());

                Document document;
                if (onePage) {
                    document = new Document(pagesize);

                } else {
                    document = new Document(PageSize.A4);
                    if (profile.getAusgabeRichtung()) {
                        document = new Document(PageSize.A4.rotate());
                    }

                }

                document.addCreationDate();

                try {
                    // creation of the different writers
                    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(selected));

                    // various fonts
                    BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", true);
                    BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", true);
                    BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", true);

                    com.lowagie.text.Font fontHelv12 = new com.lowagie.text.Font(bf_helv, fontSize);

                    com.lowagie.text.Font fontTimes = new com.lowagie.text.Font(bf_times, fontSize);

                    fontTimes.setSize(fontSize);
                    fontTimes.setStyle(com.lowagie.text.Font.ITALIC);

                    Chunk chunkHeader = new Chunk(sTitle, FontFactory.getFont(FontFactory.HELVETICA, fontSize,
                            com.lowagie.text.Font.NORMAL, new java.awt.Color(255, 0, 0)));

                    com.lowagie.text.Phrase phraseHeader = new com.lowagie.text.Phrase(chunkHeader);

                    // headers and footers must be added before the document
                    // is opened

                    Chunk chunkFooter = new Chunk("Seite: ", FontFactory.getFont(FontFactory.HELVETICA,
                            fontSize, com.lowagie.text.Font.BOLD, new java.awt.Color(0, 0, 0)));

                    Phrase phraseFooter = new Phrase(chunkFooter);
                    phraseFooter.setFont(fontHelv12);

                    HeaderFooter footer = new HeaderFooter(phraseFooter, true);
                    footer.setBorder(Rectangle.NO_BORDER);
                    footer.setAlignment(Element.ALIGN_CENTER);

                    document.setFooter(footer);

                    Phrase headerPhrase = new Phrase(sTitle);
                    headerPhrase.setFont(fontTimes);

                    HeaderFooter header = new HeaderFooter(phraseHeader, false);
                    header.setBorder(Rectangle.BOTTOM);
                    header.setBorderWidth(0.5f);
                    header.setAlignment(Element.ALIGN_LEFT);
                    document.setHeader(header);

                    document.open();

                    //System.out.println("itext image w: " + itextImage.getWidth() + " h:" + itextImage.getHeight());

                    if (onePage) {

                        int scale = 66;
                        itextImage.scalePercent(scale);

                        document.add(itextImage);

                    } else {

                        BufferedImage[] imageChunks = ImageUtils.splitImageByHeigth(bimage, printHeigth);

                        for (int i = 0; i < imageChunks.length; i++) {

                            com.lowagie.text.Image itextImage2 = com.lowagie.text.Image.getInstance(
                                    Toolkit.getDefaultToolkit().createImage(imageChunks[i].getSource()), null);

                            // width becomes typically 523 (595 - 72) for a4Hoch or 770 (842 - 72) for A4Quer
                            float imgWidth = document.getPageSize().getWidth() - document.leftMargin()
                                    - document.rightMargin();
                            float imgHeigth = itextImage.getHeight() * 0.75f;

                            itextImage2.setAbsolutePosition(30, 20);
                            int scale = 66;
                            itextImage2.scalePercent(scale);

                            document.add(itextImage2);
                            document.newPage();

                        }

                    }

                    // we're done!
                    document.close();

                    ///////////////////////////////

                } catch (Exception ex) {
                    log.error(ex.getMessage());
                    showMessage("Error while generating PDF", ex.getMessage());
                }

            } finally {
                if (image != null) {
                    image.dispose();
                }
                if (gc != null) {
                    gc.dispose();
                }
                /*
                image.dispose();
                gc.dispose();
                */
            }

        }
    };

    actionPdf.setText(Messages.Cst_Text_Save_as_pdf);
    actionPdf.setToolTipText(Messages.Cst_Text_Save_as_pdf);
    /*
     * actionPdf.setImageDescriptor(PlatformUI.getWorkbench() .getSharedImages()
     * .getImageDescriptor(ISharedImages.IMG_OBJ_FILE));
     */
    actionPdf.setImageDescriptor(Activator.getImageDescriptor(Activator.IMG_PDF_PATH));

}

From source file:com.actelion.research.spiritapp.print.CagePrinterPDF.java

License:Open Source License

public static void printCages(List<Container> cages, boolean printGroupsTreatments, boolean printTreatmentDesc,
        boolean whiteBackground) throws Exception {
    final int margin = 15;
    File f = File.createTempFile("cages__", ".pdf");
    Document doc = new Document(PageSize.A4.rotate());
    Image maleImg, femaleImg, nosexImg;
    try {//from  ww w. j a  va2 s .  c om
        maleImg = Image.getInstance(CagePrinterPDF.class.getResource("male.png"));
        femaleImg = Image.getInstance(CagePrinterPDF.class.getResource("female.png"));
        nosexImg = Image.getInstance(CagePrinterPDF.class.getResource("nosex.png"));
    } catch (Exception e) {
        throw new Exception("Could not find images in the classpath: " + e);
    }

    FileOutputStream os = new FileOutputStream(f);
    PdfWriter writer = PdfWriter.getInstance(doc, os);
    doc.open();

    PdfContentByte canvas = writer.getDirectContentUnder();

    float tileW = (doc.getPageSize().getWidth()) / 4;
    float tileH = (doc.getPageSize().getHeight()) / 2;
    for (int i = 0; i < cages.size(); i++) {
        Container cage = cages.get(i);

        Study study = cage.getStudy();
        Set<Group> groups = cage.getGroups();
        Group group = cage.getGroup();
        Set<Biosample> animals = new TreeSet<>(Biosample.COMPARATOR_NAME);
        animals.addAll(cage.getBiosamples());

        //Find the treatments applied to this group
        Set<NamedTreatment> allTreatments = new LinkedHashSet<>();
        for (Group gr : groups) {
            allTreatments.addAll(gr.getAllTreatments(-1));
        }

        //Draw
        if (i % 8 == 0) {
            if (i > 0)
                doc.newPage();
            drawCageSeparation(doc, canvas);
        }

        int col = (i % 8) % 4;
        int row = (i % 8) / 4;

        float x = margin + tileW * col;
        float x2 = x + tileW - margin;
        float baseY = tileH * row;
        float y;

        //Display Sex
        canvas.moveTo(tileW * col - 50, doc.getPageSize().getHeight() - (tileH * row + 50));
        Image img = null;
        String sex = getMetadata(animals, "Sex");
        if (study.isBlindAll()) {
            img = nosexImg;
        } else if (sex.equals("M")) {
            img = maleImg;
        } else if (sex.equals("F")) {
            img = femaleImg;
        } else if (sex.length() > 0) {
            img = nosexImg;
        }
        if (img != null) {
            img.scaleToFit(20, 20);
            img.setAbsolutePosition(tileW * (col + 1) - 33,
                    doc.getPageSize().getHeight() - (tileH * row + 12 + margin));
            doc.add(img);
        }
        if (group != null && group.getColor() != null && (study != null && !study.isBlind())
                && !whiteBackground) {
            Color c = group.getColor();
            canvas.saveState();
            canvas.setRGBColorFill(c.getRed() / 3 + 170, c.getGreen() / 3 + 170, c.getBlue() / 3 + 170);
            canvas.rectangle(x - margin + 1, doc.getPageSize().getHeight() - baseY - tileH + 1, tileW - 2,
                    tileH - 2);
            canvas.fill();
            canvas.restoreState();
        }
        Color treatmentColor = Color.BLACK;
        if (allTreatments.size() > 0 && !study.isBlind() && printGroupsTreatments) {
            int offset = 0;
            for (NamedTreatment t : allTreatments) {
                if (t.getColor() != null) {
                    if (allTreatments.size() == 1)
                        treatmentColor = new Color(t.getColor().getRed() / 2, t.getColor().getGreen() / 2,
                                t.getColor().getBlue() / 2);
                    canvas.saveState();
                    canvas.setColorStroke(Color.BLACK);
                    canvas.setRGBColorFill(t.getColor().getRed(), t.getColor().getGreen(),
                            t.getColor().getBlue());
                    y = baseY + 42 + 15 + 86 + 13 + 22 + 14 + 23 + 28;
                    canvas.rectangle(x + 20 + offset * 5, doc.getPageSize().getHeight() - y - (offset % 2) * 4,
                            22, 22);
                    canvas.fillStroke();
                    canvas.restoreState();
                    offset++;
                }
            }
        }

        canvas.beginText();
        canvas.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA_BOLD, "Cp1252", false), 16f);
        canvas.showTextAligned(Element.ALIGN_LEFT, cage.getContainerId(), x,
                doc.getPageSize().getHeight() - (baseY + 23), 0);

        canvas.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, "Cp1252", false), 11f);
        y = 42 + baseY;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Type: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 15;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Animals_ID: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 86;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Delivery date: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 13;
        canvas.showTextAligned(Element.ALIGN_LEFT, "PO Number: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 22;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Study: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 14;
        if (study != null && !study.isBlind() && printGroupsTreatments)
            canvas.showTextAligned(Element.ALIGN_LEFT, "Group: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 23;
        if (study != null && !study.isBlind() && printGroupsTreatments)
            canvas.showTextAligned(Element.ALIGN_LEFT, "Treatment: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 50;
        canvas.showTextAligned(Element.ALIGN_LEFT, "License: ", x, doc.getPageSize().getHeight() - y, 0);
        y += 13;
        canvas.showTextAligned(Element.ALIGN_LEFT, "Experimenter: ", x, doc.getPageSize().getHeight() - y, 0);
        canvas.endText();

        y = 42 + baseY;
        print(canvas, study.isBlindAll() ? "Blinded" : getMetadata(animals, "Type"), x + 65,
                doc.getPageSize().getHeight() - y, x2, 11, 11, FontFactory.HELVETICA, Color.BLACK, 11f);
        y += 15;

        if (animals.size() <= 6) {
            int n = 0;
            for (Biosample animal : animals) {
                print(canvas, animal.getSampleId(), x + 75, doc.getPageSize().getHeight() - y - 12 * n, x2 - 50,
                        12, 12, FontFactory.HELVETICA, Color.BLACK, 11f);
                if (animal.getSampleName() != null && animal.getSampleName().length() > 0) {
                    print(canvas, "[ " + animal.getSampleName() + " ]", x2 - 60,
                            doc.getPageSize().getHeight() - y - 12 * n, x2, 12, 12, FontFactory.HELVETICA_BOLD,
                            Color.BLACK, 11f);
                }
                n++;
            }
        } else {
            int nPerRow = animals.size() / 2;
            int n = 0;
            for (Biosample animal : animals) {
                int nx = n / nPerRow;
                int ny = n % nPerRow;
                print(canvas, animal.getSampleId(), x + nx * (x2 - x) / 2,
                        doc.getPageSize().getHeight() - y - 12 * ny - 12, x + (1 + nx) * (x2 - x) / 2, 12, 12,
                        FontFactory.HELVETICA, Color.BLACK, 10f);
                if (animal.getSampleName() != null && animal.getSampleName().length() > 0) {
                    print(canvas, "[ " + animal.getSampleName() + " ]", x + (1 + nx) * (x2 - x) / 2 - 35,
                            doc.getPageSize().getHeight() - y - 12 * ny - 12, x + (1 + nx) * (x2 - x) / 2, 12,
                            12, FontFactory.HELVETICA_BOLD, Color.BLACK, 10f);
                }
                n++;
            }
        }

        y += 86;
        print(canvas, getMetadata(animals, "Delivery Date"), x + 75, doc.getPageSize().getHeight() - y, x2, 0,
                10, FontFactory.HELVETICA, Color.BLACK, 10f);
        y += 13;
        print(canvas, getMetadata(animals, "PO Number"), x + 75, doc.getPageSize().getHeight() - y, x2, 0, 10,
                FontFactory.HELVETICA, Color.BLACK, 10f);
        y += 22;
        print(canvas, study.getStudyIdAndInternalId(), x + 40, doc.getPageSize().getHeight() - y, x2, 0, 11,
                BaseFont.HELVETICA_BOLD, Color.BLACK, 11f);
        y += 14;
        if (!study.isBlind() && printGroupsTreatments)
            print(canvas, getGroups(animals), x + 40, doc.getPageSize().getHeight() - y, x2, 22, 11,
                    BaseFont.HELVETICA_BOLD, Color.BLACK, 11f);
        y += 23;
        if (!study.isBlind() && printGroupsTreatments)
            print(canvas, getTreatments(animals, printTreatmentDesc), x + 62, doc.getPageSize().getHeight() - y,
                    x2, 50, printTreatmentDesc ? 9 : 12, FontFactory.HELVETICA, treatmentColor,
                    printTreatmentDesc ? 9f : 10f);
        y += 50;
        print(canvas, study.getMetadataMap().get("LICENSENO"), x + 74, doc.getPageSize().getHeight() - y, x2,
                15, 10, FontFactory.HELVETICA, Color.BLACK, 10f);
        y += 13;
        print(canvas, study.getMetadataMap().get("EXPERIMENTER"), x + 74, doc.getPageSize().getHeight() - y, x2,
                20, 10, FontFactory.HELVETICA, Color.BLACK, 10f);
    }

    doc.close();
    os.close();
    Desktop.getDesktop().open(f);
    try {
        Thread.sleep(500);
    } catch (Exception e) {
    }

}

From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java

License:Open Source License

public static boolean functionsToUse(Project project, Wiki wiki, File file, HashMap imageList)
        throws Exception {
    // remove this.
    Document document = new Document();

    // Parse each line to see if paragraph, table, section heading, list
    // Parse within the line to see if bold, italic, links, code fragment, images

    // Define styles
    Font exampleFont = FontFactory.getFont(FontFactory.HELVETICA, 24, Font.NORMAL, new Color(255, 0, 0));

    // Add title and paragraphs

    // TODO: Construct a title page... with logo
    Paragraph title = new Paragraph(wiki.getSubject(), exampleFont);

    //Chunk title = new Chunk(wiki.getSubject());
    //title.setBackground(new Color(0xFF, 0xDE, 0xAD));
    ////title.setUnderline(new Color(0xFF, 0x00, 0x00), 3.0f, 0.0f, -4.0f, 0.0f, PdfContentByte.LINE_CAP_ROUND);
    //title.setUnderline(0.2f, -2f);
    LOG.debug("document.add(title)");
    document.add(title);//from   w ww.  j av  a 2s . co m

    // Link from
    // a paragraph with a local goto
    //Paragraph p1 = new Paragraph("We will do something special with this paragraph. If you click on ", FontFactory.getFont(FontFactory.HELVETICA, 12));
    //p1.add(new Chunk("this word", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 255))).setLocalGoto("test"));
    //p1.add(" you will automatically jump to another location in this document.");

    // a paragraph with a local destination
    //Paragraph p3 = new Paragraph("This paragraph contains a ");
    //p3.add(new Chunk("local destination", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 255, 0))).setLocalDestination("test"));

    // Ext A Href
    //Paragraph paragraph = new Paragraph("Please visit my ");
    //Anchor anchor1 = new Anchor("website (external reference)", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, new Color(0, 0, 255)));
    //anchor1.setReference("http://www.lowagie.com/iText/");
    //anchor1.setName("top");
    //paragraph.add(anchor1);

    //Image jpg = Image.getInstance("otsoe.jpg");
    //document.add(jpg);

    return false;
}