Example usage for com.lowagie.text Phrase Phrase

List of usage examples for com.lowagie.text Phrase Phrase

Introduction

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

Prototype

private Phrase(boolean dummy) 

Source Link

Document

Constructs a Phrase that can be used in the static getInstance() method.

Usage

From source file:biblivre3.circulation.CirculationBO.java

License:Open Source License

public MemoryFileDTO createFileUserCardsPDF(ArrayList<UserCardDTO> cards, int startOffset, Properties i18n) {
    Document document = new Document();
    MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName("user_cards_" + new Date().getTime() + ".pdf");
    try {/*from   w  w w.j a  v  a2  s  .  com*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.setPageSize(PageSize.A4);
        document.setMargins(7.15f * ApplicationConstants.MM_UNIT, 7.15f * ApplicationConstants.MM_UNIT,
                9.09f * ApplicationConstants.MM_UNIT, 9.09f * ApplicationConstants.MM_UNIT);
        document.open();
        PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100f);
        PdfPCell cell;
        int i = 0;
        for (i = 0; i < startOffset; i++) {
            cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            table.addCell(cell);
        }
        for (UserCardDTO card : cards) {
            String userEnrollNumber = String.valueOf(card.getUserId());
            PdfContentByte cb = writer.getDirectContent();
            Barcode39 code39 = new Barcode39();
            code39.setExtended(true);
            while (userEnrollNumber.length() < 10) {
                userEnrollNumber = "0" + userEnrollNumber;
            }
            code39.setCode(userEnrollNumber);
            code39.setStartStopText(false);
            Image image39 = code39.createImageWithBarcode(cb, null, null);
            image39.scalePercent(110f);
            Paragraph para = new Paragraph();
            String name = card.getUserName();
            name = name.length() >= 30 ? name.substring(0, 30) : name;
            Phrase p1 = new Phrase(name + "\n");
            Phrase p2 = new Phrase(new Chunk(image39, 0, 0));
            Phrase p3 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_SERIAL") + ": " + card.getUserId() + "\n");
            Phrase p4 = new Phrase(
                    I18nUtils.getText(i18n, "LABEL_USER_TYPE") + ": " + card.getUserType() + "\n\n");
            para.add(p1);
            para.add(p3);
            para.add(p4);
            para.add(p2);
            cell = new PdfPCell(para);
            i++;
            cell.setFixedHeight(46.47f * ApplicationConstants.MM_UNIT);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
            cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }
        if ((i % 3) != 0) {
            while ((i % 3) != 0) {
                i++;
                cell = new PdfPCell();
                cell.setBorder(Rectangle.NO_BORDER);
                table.addCell(cell);
            }
        }
        document.add(table);
        writer.flush();
        document.close();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (DocumentException de) {
        System.out.println(de.getMessage());
    }
    return file;
}

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 {/*from   www . ja  v a 2  s .  c  om*/
        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 {//w ww . j  a v  a 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   w w  w  .  j a  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:ch.gpb.elexis.kgexporter.pdf.HeaderFooterPageEvent.java

License:Open Source License

public void onStartPage(PdfWriter writer, Document document) {
    Rectangle rect = writer.getBoxSize("art");

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(sbHeader),
            rect.getLeft(), rect.getTop(), 0);

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(sDate),
            rect.getRight(), rect.getTop(), 0);

    PdfContentByte cb = writer.getDirectContentUnder();

    //cb.rectangle(document.left(), document.top(),
    //   document.right() - document.left(), document.top() - 25);
    /*// w w  w .ja  v  a 2 s.  com
    System.out.println("l: " + document.left());
    System.out.println("r: " + document.right());
    System.out.println("t: " + document.top());
    System.out.println("b: " + document.bottom());
    l: 36.0
    r: 559.0
    t: 806.0
    b: 36.0
    */

    //Rectangle rect2 = new Rectangle(document.top() - 36, document.top() - 36, 559, 1);

    /*
    float l = 36f;
    float r = 36f;
    float t = 559f;
    float b = 2f;
            
    Rectangle rect2 = new Rectangle(l, r, t, b);
            
    //Rectangle rect2 = new Rectangle(36, 36, 559, 1);
    rect2.setBorder(Rectangle.BOTTOM);
    rect2.setBorderWidth(0.5f);
    cb.rectangle(rect2);
            
    //cb.setColorStroke(Color.BLACK);
    */

    /*
    for (int i = 30; i > 0; i--) {
        System.err.println((float) i / 10);
        cb.setLineWidth((float) i / 10);
        cb.moveTo(36, 806 - (5 * i));
        cb.lineTo(400, 806 - (5 * i));
        cb.stroke();
    }
    cb.moveTo(10, 50);
    cb.lineTo(559, 50);
     */
    cb.setLineWidth(0.5f);
    cb.moveTo(30, 791);
    cb.lineTo(559, 791);

    cb.stroke();

}

From source file:ch.gpb.elexis.kgexporter.pdf.HeaderFooterPageEvent.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    Rectangle rect = writer.getBoxSize("art");
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(this.sbFooter),
            rect.getLeft(), rect.getBottom(), 0);

    /*//  ww w .  j  ava2  s .c om
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Bottom Right"),
       rect.getRight(), rect.getBottom(), 0);
    */
    PdfContentByte cb = writer.getDirectContentUnder();

    cb.setLineWidth(0.5f);

    cb.moveTo(30, 50);
    cb.lineTo(559, 50);
    cb.stroke();

}

From source file:ch.gpb.elexis.kgexporter.pdf.PdfHandler.java

License:Open Source License

private static HeaderFooter getHeader(String headerText) {
    Phrase headerPhrase = new Phrase(headerText);
    headerPhrase.setFont(fontTimes);//  www .  j a  v  a2  s  . co  m

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

    return header;
}

From source file:classroom.newspaper_a.Newspaper04.java

public static void main(String[] args) {
    try {//from  www .  ja va2 s .  c o  m
        PdfReader reader = new PdfReader(NEWSPAPER);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        PdfContentByte canvas = stamper.getOverContent(1);
        canvas.saveState();
        canvas.setRGBColorFill(0xFF, 0xFF, 0xFF);
        canvas.rectangle(LLX1, LLY1, W1, H1);
        canvas.rectangle(LLX2, LLY2, W2, H2);
        canvas.fillStroke();
        canvas.restoreState();
        Phrase p = new Phrase(MESSAGE);
        putText(canvas, p, LLX1, LLY1, URX1, URY1);
        putText(canvas, p, LLX2, LLY2, URX2, URY2);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:classroom.newspaper_a.Newspaper05.java

public static void main(String[] args) {
    try {//from w  w w.jav  a 2 s .  co  m
        PdfReader reader = new PdfReader(NEWSPAPER);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        PdfContentByte canvas = stamper.getOverContent(1);
        canvas.saveState();
        canvas.setRGBColorFill(0xFF, 0xFF, 0xFF);
        canvas.rectangle(LLX1, LLY1, W1, H1);
        canvas.rectangle(LLX2, LLY2, W2, H2);
        canvas.fillStroke();
        canvas.restoreState();
        Phrase p = new Phrase(MESSAGE);
        putText(canvas, p, LLX1, LLY1, W1, H1);
        putText(canvas, p, LLX2, LLY2, W2, H2);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java

License:Open Source License

public static void convertHSSF2Pdf(Workbook wb, String header, File reportFile) throws Exception {
    assert wb != null;
    assert reportFile != null;

    //Precompute formula
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        Sheet sheet = wb.getSheetAt(i);//from   w  w w  .  java2  s  .  com

        for (Row r : sheet) {
            for (Cell c : r) {
                if (c.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
                    try {
                        evaluator.evaluateFormulaCell(c);
                    } catch (Exception e) {
                        System.err.println(e);
                    }
                }
            }
        }
    }

    File tmp = File.createTempFile("tmp_", ".xlsx");
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tmp))) {
        wb.write(out);
    }

    //Find page orientation
    int maxColumnsGlobal = 0;
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            maxColumnsGlobal = Math.max(maxColumnsGlobal, row.getLastCellNum());
        }
    }

    Rectangle pageSize = maxColumnsGlobal < 10 ? PageSize.A4 : PageSize.A4.rotate();
    Document pdfDocument = new Document(pageSize, 10f, 10f, 20f, 20f);

    PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(reportFile));
    addHeader(writer, header);
    pdfDocument.open();
    //we have two columns in the Excel sheet, so we create a PDF table with two columns
    //Note: There are ways to make this dynamic in nature, if you want to.
    //Loop through sheets
    for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
        Sheet sheet = wb.getSheetAt(sheetNo);

        //Loop through rows, to find number of columns
        int minColumns = 1000;
        int maxColumns = 0;
        for (Iterator<Row> rowIterator = sheet.iterator(); rowIterator.hasNext();) {
            Row row = rowIterator.next();
            if (row.getFirstCellNum() >= 0)
                minColumns = Math.min(minColumns, row.getFirstCellNum());
            if (row.getLastCellNum() >= 0)
                maxColumns = Math.max(maxColumns, row.getLastCellNum());
        }
        if (maxColumns == 0)
            continue;

        //Loop through first rows, to find relative width
        float[] widths = new float[maxColumns];
        int totalWidth = 0;
        for (int c = 0; c < maxColumns; c++) {
            int w = sheet.getColumnWidth(c);
            widths[c] = w;
            totalWidth += w;
        }

        for (int c = 0; c < maxColumns; c++) {
            widths[c] /= totalWidth;
        }

        //Create new page and a new chapter with the sheet's name
        if (sheetNo > 0)
            pdfDocument.newPage();
        Chapter pdfSheet = new Chapter(sheet.getSheetName(), sheetNo + 1);

        PdfPTable pdfTable = null;
        PdfPCell pdfCell = null;
        boolean inTable = false;

        //Loop through cells, to create the content
        //         boolean leftBorder = true;
        //         boolean[] topBorder = new boolean[maxColumns+1];
        for (int r = 0; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);

            //Check if we exited a table (empty line)
            if (row == null) {
                if (pdfTable != null) {
                    addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
                    pdfTable = null;
                }
                inTable = false;
                continue;
            }

            //Check if we start a table (>MIN_COL_IN_TABLE columns)
            if (row.getLastCellNum() >= MIN_COL_IN_TABLE) {
                inTable = true;
            }

            if (!inTable) {
                //Process the data outside table, just add the text
                boolean hasData = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
                        continue;
                    Chunk chunk = getChunk(wb, cell);
                    pdfSheet.add(chunk);
                    pdfSheet.add(new Chunk(" "));
                    hasData = true;
                }
                if (hasData)
                    pdfSheet.add(Chunk.NEWLINE);

            } else {
                //Process the data in table
                if (pdfTable == null) {
                    //Create table
                    pdfTable = new PdfPTable(maxColumns);
                    pdfTable.setWidths(widths);
                    //                  topBorder = new boolean[maxColumns+1];
                }

                int cellNumber = minColumns;
                //               leftBorder = false;
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    for (; cellNumber < cell.getColumnIndex(); cellNumber++) {
                        pdfCell = new PdfPCell();
                        pdfCell.setBorder(0);
                        pdfTable.addCell(pdfCell);
                    }

                    Chunk phrase = getChunk(wb, cell);
                    pdfCell = new PdfPCell(new Phrase(phrase));
                    pdfCell.setFixedHeight(row.getHeightInPoints() - 3);
                    pdfCell.setNoWrap(!cell.getCellStyle().getWrapText());
                    pdfCell.setPaddingLeft(1);
                    pdfCell.setHorizontalAlignment(
                            cell.getCellStyle().getAlignment() == CellStyle.ALIGN_CENTER ? PdfPCell.ALIGN_CENTER
                                    : cell.getCellStyle().getAlignment() == CellStyle.ALIGN_RIGHT
                                            ? PdfPCell.ALIGN_RIGHT
                                            : PdfPCell.ALIGN_LEFT);
                    pdfCell.setUseBorderPadding(false);
                    pdfCell.setUseVariableBorders(false);
                    pdfCell.setBorderWidthRight(cell.getCellStyle().getBorderRight() == 0 ? 0 : .5f);
                    pdfCell.setBorderWidthBottom(cell.getCellStyle().getBorderBottom() == 0 ? 0
                            : cell.getCellStyle().getBorderBottom() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthLeft(cell.getCellStyle().getBorderLeft() == 0 ? 0
                            : cell.getCellStyle().getBorderLeft() > 1 ? 1 : .5f);
                    pdfCell.setBorderWidthTop(cell.getCellStyle().getBorderTop() == 0 ? 0
                            : cell.getCellStyle().getBorderTop() > 1 ? 1 : .5f);
                    String color = cell.getCellStyle().getFillForegroundColorColor() == null ? null
                            : ((XSSFColor) cell.getCellStyle().getFillForegroundColorColor()).getARGBHex();
                    if (color != null)
                        pdfCell.setBackgroundColor(new Color(Integer.decode("0x" + color.substring(2))));
                    pdfTable.addCell(pdfCell);
                    cellNumber++;
                }
                for (; cellNumber < maxColumns; cellNumber++) {
                    pdfCell = new PdfPCell();
                    pdfCell.setBorder(0);
                    pdfTable.addCell(pdfCell);
                }
            }

            //Custom code to add all images on the first sheet (works for reporting)
            if (sheetNo == 0 && row.getRowNum() == 0) {
                for (PictureData pd : wb.getAllPictures()) {
                    try {
                        Image pdfImg = Image.getInstance(pd.getData());
                        pdfImg.scaleToFit(
                                pageSize.getWidth() * .8f - pageSize.getBorderWidthLeft()
                                        - pageSize.getBorderWidthRight(),
                                pageSize.getHeight() * .8f - pageSize.getBorderWidthTop()
                                        - pageSize.getBorderWidthBottom());
                        pdfSheet.add(pdfImg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (pdfTable != null) {
            addTable(pdfDocument, pdfSheet, totalWidth, widths, pdfTable);
        }

        pdfDocument.add(pdfSheet);
    }
    pdfDocument.close();

}