Example usage for com.itextpdf.text.pdf PdfContentByte showText

List of usage examples for com.itextpdf.text.pdf PdfContentByte showText

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte showText.

Prototype

public void showText(final PdfTextArray text) 

Source Link

Document

Show an array of text.

Usage

From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java

License:Open Source License

private void writeCurrentDate(Document document, PdfContentByte contentByte) {
    contentByte.setTextMatrix(document.left() + textAdjustment, document.bottom());
    String dateText = DATE_FORMAT.format(new Date());
    contentByte.showText(dateText);
}

From source file:org.openlmis.web.view.pdf.PdfPageEventHandler.java

License:Open Source License

private void writePageNumber(PdfWriter writer, Document document, PdfContentByte contentByte) {
    String pageNumberText = messageService.message("label.page.of", writer.getPageNumber()) + " ";
    float pageNumberTextSize = baseFont.getWidthPoint(pageNumberText, FOOTER_TEXT_SIZE);
    contentByte.setTextMatrix(document.right() - pageNumberTextSize - textAdjustment, document.bottom());
    contentByte.showText(pageNumberText);
    contentByte.addTemplate(pageNumberTemplate, document.right() - textAdjustment, document.bottom());
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the text of the given page to the current PDF page
 * @param writer/*from   w w w.  j  a v  a2 s .  c  o  m*/
 * @param page
 */
private void addText(PdfWriter writer, Page page) {

    if (textLevel == null)
        return;

    int pageHeight = page.getLayout().getHeight();

    try {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        for (ContentIterator it = page.getLayout().iterator(textLevel); it.hasNext();) {
            ContentObject obj = it.next();
            if (obj == null || !(obj instanceof TextObject))
                continue;
            TextObject textObj = (TextObject) obj;

            if (textObj.getText() != null && !textObj.getText().isEmpty()) {

                List<String> strings = new ArrayList<String>();
                List<Rect> boxes = new ArrayList<Rect>();

                float fontSize = 1.0f;

                //Collect
                if (textObj instanceof LowLevelTextObject) {
                    strings.add(textObj.getText());
                    Rect boundingBox = obj.getCoords().getBoundingBox();
                    boxes.add(boundingBox);
                    fontSize = calculateFontSize(textObj.getText(), boundingBox.getWidth(),
                            boundingBox.getHeight());
                } else {
                    fontSize = splitTextRegion((TextRegion) obj, strings, boxes);
                }

                //Render
                for (int i = 0; i < strings.size(); i++) {
                    String text = strings.get(i);
                    Rect boundingBox = boxes.get(i);

                    //Calculate vertical transition (text is rendered at baseline -> descending bits are below the chosen position)
                    int descent = (int) font.getDescentPoint(text, fontSize);
                    int ascent = (int) font.getAscentPoint(text, fontSize);
                    int textHeight = Math.abs(descent) + ascent;
                    int transY = descent;

                    if (textHeight < boundingBox.getHeight()) {
                        transY = descent - (boundingBox.getHeight() - textHeight) / 2;
                    }

                    cb.beginText();
                    //cb.moveText(boundingBox.left, pageHeight - boundingBox.bottom);
                    cb.setTextMatrix(boundingBox.left, pageHeight - boundingBox.bottom - transY);
                    cb.setFontAndSize(font, fontSize);
                    cb.showText(text);
                    cb.endText();

                    //Debug
                    //cb.moveTo(boundingBox.left, pageHeight - boundingBox.bottom - transY);
                    //cb.lineTo(boundingBox.right, pageHeight - boundingBox.bottom - transY);
                    //cb.moveTo(boundingBox.left, pageHeight - boundingBox.bottom);
                    //cb.lineTo(boundingBox.right, pageHeight - boundingBox.bottom);
                }
            }
        }
        cb.restoreState();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:pdf.alterLetter.java

public static void main(String args[]) {
    try {//from  w ww  .  j  a va  2  s .c o m
        PdfReader pdfReader;
        pdfReader = new PdfReader("C:\\Users\\asus\\Desktop\\web\\Appointment letter.pdf");
        //pdfReader = new PdfReader("C:\\Users\\asus\\Desktop\\TFMsystem\\Appointment letter.pdf");   

        //Create PdfStamper instance.
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(
                "C:\\Users\\asus\\Desktop\\TFMsystem\\web\\Modified appointment letter.pdf"));

        //new FileOutputStream("C:\\Users\\asus\\Desktop\\TFMsystem\\Modified appointment letter.pdf"));

        //Create BaseFont instance.
        BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED);

        //Get the number of pages in pdf.
        int pages = pdfReader.getNumberOfPages();

        //Iterate the pdf through pages.
        for (int i = 1; i <= pages; i++) {
            //Contain the pdf data.
            PdfContentByte pageContentByte = pdfStamper.getOverContent(i);

            pageContentByte.beginText();
            //Set text font and size.
            pageContentByte.setFontAndSize(baseFont, 12);

            //Write text
            pageContentByte.setTextMatrix(120, 706);
            pageContentByte.showText("[no rujukan(enter by admin/opai)]");

            pageContentByte.setTextMatrix(500, 706);
            pageContentByte.showText("[current date]");
            //address
            pageContentByte.setTextMatrix(46, 641);
            pageContentByte.showText("[name]");
            pageContentByte.setTextMatrix(46, 629);
            pageContentByte.showText("[position]");
            pageContentByte.setTextMatrix(46, 617);
            pageContentByte.showText("[department]");

            pageContentByte.setTextMatrix(155, 493);
            pageContentByte.showText("[status(penyelaras/ahli),taskforce name]");

            pageContentByte.setTextMatrix(178, 433);
            pageContentByte.showText("[start date]");

            pageContentByte.setTextMatrix(290, 433);
            pageContentByte.showText("[end date] .");

            pageContentByte.setTextMatrix(46, 248);
            pageContentByte.showText("[name]");
            pageContentByte.setTextMatrix(46, 236);
            pageContentByte.showText("[post]");
            pageContentByte.setTextMatrix(46, 224);
            pageContentByte.showText("[faculty]");
            pageContentByte.setTextMatrix(46, 212);
            pageContentByte.showText("[email]");

            pageContentByte.endText();
        }

        //Close the pdfStamper.
        pdfStamper.close();

        System.out.println("PDF modified successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:pdf.letter.java

public boolean AlterLetter(String rujukan, String name, String position, String department, String gStatus,
        String sDate, String eDate, String taskName, String postHolderName, String postHolderEmail,
        String postName) {//ww w.  j av a 2s . co  m
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date today = Calendar.getInstance().getTime();
    String currDate = df.format(today);
    try {
        PdfReader pdfReader;
        pdfReader = new PdfReader("C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Appointment letter.pdf");
        //C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Appointment letter.pdf

        //Create PdfStamper instance.
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(
                "C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Modified appointment letter.pdf"));
        //C:\\Users\\on\\Desktop\\AD\\TFMsystem\\web\\Modified Appointment letter.pdf

        //Create BaseFont instance.
        BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED);

        //Get the number of pages in pdf.
        int pages = pdfReader.getNumberOfPages();

        //Iterate the pdf through pages.
        for (int i = 1; i <= pages; i++) {
            //Contain the pdf data.
            PdfContentByte pageContentByte = pdfStamper.getOverContent(i);

            pageContentByte.beginText();
            //Set text font and size.
            pageContentByte.setFontAndSize(baseFont, 11);

            //Write text
            pageContentByte.setTextMatrix(120, 706);
            pageContentByte.showText(rujukan);

            pageContentByte.setTextMatrix(500, 706);
            pageContentByte.showText(currDate);
            //address
            pageContentByte.setTextMatrix(46, 641);
            pageContentByte.showText(name);
            pageContentByte.setTextMatrix(46, 629);
            pageContentByte.showText(position);
            pageContentByte.setTextMatrix(46, 617);
            pageContentByte.showText(department);

            String gstatus;

            pageContentByte.setTextMatrix(157, 493);
            String changeCase = gStatus + ", " + taskName;
            pageContentByte.showText(changeCase.toUpperCase());

            pageContentByte.setTextMatrix(250, 444);
            pageContentByte.showText(gStatus + "  " + taskName + " .");

            pageContentByte.setTextMatrix(180, 432);
            pageContentByte.showText(sDate);

            pageContentByte.setTextMatrix(290, 432);
            pageContentByte.showText(eDate + " .");

            pageContentByte.setTextMatrix(46, 248);
            pageContentByte.showText(postHolderName);
            pageContentByte.setTextMatrix(46, 236);
            pageContentByte.showText(postName);
            pageContentByte.setTextMatrix(46, 224);
            pageContentByte.showText("Fakulti Komputeran");
            pageContentByte.setTextMatrix(46, 212);
            pageContentByte.showText(postHolderEmail);

            pageContentByte.endText();
        }
        //Close the pdfStamper.
        pdfStamper.close();
        System.out.println("PDF modified successfully.");

        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

From source file:pl.marcinmilkowski.hocrtopdf.Main.java

License:Open Source License

/**
 * @param args//  w w  w  .j a  va  2 s.c  o m
 */
public static void main(String[] args) {
    try {
        if (args.length < 1 || args[0] == "--help" || args[0] == "-h") {
            System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n"
                    + "\n" + "Converts hOCR files into PDF\n" + "\n"
                    + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n");
            if (args.length < 1)
                System.exit(-1);
            else
                System.exit(0);
        }
        URL inputHOCRFile = null;
        FileOutputStream outputPDFStream = null;
        try {
            File file = new File(args[0]);
            inputHOCRFile = file.toURI().toURL();
        } catch (MalformedURLException e) {
            System.out.println("The first parameter has to be a valid file.");
            System.out.println("We got an error: " + e.getMessage());
            System.exit(-1);
        }
        try {
            outputPDFStream = new FileOutputStream(args[1]);
        } catch (FileNotFoundException e) {
            System.out.println("The second parameter has to be a valid URL");
            System.exit(-1);
        }

        // The resolution of a PDF file (using iText) is 72pt per inch
        float pointsPerInch = 72.0f;

        // Using the jericho library to parse the HTML file
        Source source = new Source(inputHOCRFile);

        int pageCounter = 1;

        Document pdfDocument = null;
        PdfWriter pdfWriter = null;
        PdfContentByte cb = null;
        RandomAccessFileOrArray ra = null;

        // Find the tag of class ocr_page in order to load the scanned image
        StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE);
        while (pageTag != null) {
            int prevPos = pageTag.getEnd();
            Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
            Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
            if (!imageMatcher.find()) {
                System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
                System.exit(-1);
            }
            // Load the image
            Image pageImage = null;
            try {
                File file = new File(imageMatcher.group(1));
                pageImage = Image.getInstance(file.toURI().toURL());
            } catch (MalformedURLException e) {
                System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1)
                        + ", aborting.");
                System.exit(-1);
            }
            if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might
                                                                      // be
                                                                      // multipage
                                                                      // tiff!
                File file = new File(imageMatcher.group(1));
                if (pageCounter == 1 || ra == null) {
                    ra = new RandomAccessFileOrArray(file.toURI().toURL());
                }
                int nPages = TiffImage.getNumberOfPages(ra);
                if (nPages > 0 && pageCounter <= nPages) {
                    pageImage = TiffImage.getTiffImage(ra, pageCounter);
                }
            }
            int dpiX = pageImage.getDpiX();
            if (dpiX == 0) { // for images that don't set the resolution we assume
                             // 300 dpi
                dpiX = 300;
            }
            int dpiY = pageImage.getDpiY();
            if (dpiY == 0) { // as above for dpiX
                dpiY = 300;
            }
            float dotsPerPointX = dpiX / pointsPerInch;
            float dotsPerPointY = dpiY / pointsPerInch;
            float pageImagePixelHeight = pageImage.getHeight();
            if (pdfDocument == null) {
                pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
                pdfDocument.open();
                // Put the text behind the picture (reverse for debugging)
                // cb = pdfWriter.getDirectContentUnder();
                cb = pdfWriter.getDirectContent();
            } else {
                pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfDocument.newPage();
            }
            // first define a standard font for our text
            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font defaultFont = new Font(base, 8);
            // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,
            // CMYKColor.BLACK);

            cb.setHorizontalScaling(1.0f);

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
            pageImage.setAbsolutePosition(0, 0);
            // Put the image in front of the text (reverse for debugging)
            // pdfWriter.getDirectContent().addImage(pageImage);
            pdfWriter.getDirectContentUnder().addImage(pageImage);

            // In order to place text behind the recognised text snippets we are
            // interested in the bbox property
            Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
            // This pattern separates the coordinates of the bbox property
            Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
            // Only tags of the ocr_line class are interesting
            StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            while (ocrTag != null) {
                prevPos = ocrTag.getEnd();
                if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                    net.htmlparser.jericho.Element lineElement = ocrTag.getElement();
                    Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
                    if (bboxMatcher.find()) {
                        // We found a tag of the ocr_line class containing a bbox property
                        Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                        bboxCoordinateMatcher.find();
                        int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                                Integer.parseInt((bboxCoordinateMatcher.group(2))),
                                Integer.parseInt((bboxCoordinateMatcher.group(3))),
                                Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                        String line = lineElement.getContent().getTextExtractor().toString();
                        float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                        float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                        // Put the text into the PDF
                        cb.beginText();
                        // Comment the next line to debug the PDF output (visible Text)
                        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                        // height
                        cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1));
                        // width
                        cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false));
                        cb.moveText((coordinates[0] / dotsPerPointX),
                                ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                        cb.showText(line);
                        cb.endText();
                        cb.setHorizontalScaling(1.0f);
                    }
                } else {
                    if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                        pageCounter++;
                        pageTag = ocrTag;
                        break;
                    }
                }
                ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            }
            if (ocrTag == null) {
                pdfDocument.close();
                break;
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:printInv.GenerateInvoice.java

private void createHeadings(PdfContentByte cb, float x, float y, String text) {

    cb.beginText();//from  w w w  . ja v  a 2  s  .  c o  m
    cb.setFontAndSize(bfBold, 8);
    cb.setTextMatrix(x, y);
    //        System.out.println(text+"*****************");
    cb.showText(text.trim());
    //        System.out.println("***************************");
    cb.endText();

}

From source file:pw.core.pdf.PWPdfFile.java

License:Open Source License

public void addField(PWPdfField field) {
    PdfContentByte contentByte = writer.getDirectContent();
    contentByte.beginText();//from  ww w . j  a  v  a 2s .  co  m
    BaseFont baseFont = getFont(field.font, field.encoding, field.isEmbedded);
    contentByte.setFontAndSize(baseFont, field.fontSize);
    contentByte.setTextMatrix(field.x, field.y);
    contentByte.showText(field.text);
    contentByte.endText();
}

From source file:Report.ItextReport.java

public static void absText(PdfWriter writer, String text, int x, int y) {
    try {/*  w w w .j a v  a  2s  .c  o m*/
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.saveState();
        cb.beginText();
        cb.moveText(x, y);
        cb.setFontAndSize(bf, 12);
        cb.showText(text);
        cb.endText();
        cb.restoreState();
    } catch (DocumentException | IOException e) {
        e.getMessage();
    }
}

From source file:Report.RelatorioAluno.java

/**
 * funcao para gerar o stream do relatorio
 *
 * @return ByteArrayOutputStream/*from  w ww .  j  ava 2 s  .co  m*/
 */
public ByteArrayOutputStream relatorioAlunosMatriculados() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FacesContext faces = FacesContext.getCurrentInstance();
    // pega o contexto da aplicacao
    realPath = faces.getExternalContext().getRealPath("/");
    //realPath = "C:/Users/Alessandro/Desktop/TCC2/SisGES/build/web";

    try {
        BaseFont fHelvetica = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);

        //----------------------------------------------------------------------
        // creation of the document with a certain size and certain margins
        // may want to use PageSize.LETTER instead
        Document document = new Document(PageSize.A4, 40, 40, 20, 50);
        document.addAuthor("SisGES"); // optional
        document.addSubject("Relatrio"); // opcional
        document.addKeywords("SisGES");
        document.addCreator("iText");
        //----------------------------------------------------------------------
        // creation of the different writers
        //PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("web/resources/report/alunosMatriculados.pdf"));
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setBoxSize("header", new Rectangle(36, 54, 559, 788));
        //----------------------------------------------------------------------
        // ADICIONA HEADER E FOOTER
        //----------------------------------------------------------------------
        HeaderFooter headerFooter = new HeaderFooter();
        writer.setPageEvent(headerFooter);
        //----------------------------------------------------------------------
        // ABRE DOCUMENTO PARA ESCRITA
        //----------------------------------------------------------------------
        document.open();
        //----------------------------------------------------------------------
        //ADICIONAR LOGO NO DOCUMENTO
        //----------------------------------------------------------------------
        Image logoUfu = Image.getInstance(realPath + "/resources/images/logoUFU.png");
        logoUfu.scaleAbsolute(57, 56);//(largura,altura)
        logoUfu.isImgTemplate(); //add no template
        //logoUfu.setAbsolutePosition(30, 745); //x ,y por referencia do rodape
        document.add(logoUfu);

        Image logoFacom = Image.getInstance(realPath + "/resources/images/logoFacom.png");
        logoFacom.scaleAbsolute(62, 55);//(largura,altura)
        logoFacom.setAbsolutePosition(92, 767); //x ,y por referencia do rodape
        //logoFacom.isImgTemplate(); //add no template            
        document.add(logoFacom);

        //----------------------------------------------------------------------
        //ADICIONAR CABEALHO
        //----------------------------------------------------------------------
        PdfContentByte univ = writer.getDirectContentUnder();
        univ.beginText();
        univ.setFontAndSize(fHelvetica, 10);
        univ.setTextMatrix(349, 805); // x e y
        univ.showText("UNIVERSIDADE FEDERAL DE UBERLNDIA");
        univ.setTextMatrix(405, 790); // x e y
        univ.showText("FACULDADE DE COMPUTAO");
        univ.setTextMatrix(403, 775); // x e y
        univ.showText("COORDENADORIA DE ESTGIO ");
        univ.endText();

        PdfContentByte univEnd = writer.getDirectContentUnder();
        univEnd.beginText();
        univEnd.setFontAndSize(fHelvetica, 7);
        univEnd.setTextMatrix(326, 761); // x e y
        univEnd.showText("Campus Universitrio - Santa Mnica - CEP 38408-100 - Uberlndia - MG");
        univEnd.setTextMatrix(432, 750); // x e y
        univEnd.showText("Telefone: (34) 3239-4144 ou 3239-4393");
        univEnd.endText();

        //----------------------------------------------------------------------
        //ADICIONAR TITULO
        //----------------------------------------------------------------------
        PdfContentByte titulo = writer.getDirectContentUnder();
        titulo.beginText();
        titulo.setFontAndSize(fHelvetica, 16);
        titulo.setTextMatrix(210, 700); // x e y
        titulo.showText("Alunos Matrculados");
        titulo.endText();
        //----------------------------------------------------------------------

        //----------------------------------------------------------------------
        AlunoDAO aDAO = new AlunoDAO();
        List<Aluno> allAlunos = aDAO.getAllAlunos();
        aDAO.closeSession();

        PdfPTable table = new PdfPTable(5);

        table.setTotalWidth(100f);
        table.setWidthPercentage(100);
        float[] widths = { 10, 30, 30, 13, 17 };//largura das colunas
        table.setWidths(widths);
        table.setHeaderRows(1);

        Paragraph cabecalho = new Paragraph("Matricula");
        PdfPCell cellMatricula = new PdfPCell(cabecalho); // celula
        cabecalho.getFont().setStyle(Font.BOLD);
        cabecalho.getFont().setSize(8);
        cellMatricula.setBackgroundColor(BaseColor.LIGHT_GRAY);
        cellMatricula.setBorderColor(BaseColor.LIGHT_GRAY);
        cellMatricula.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cellMatricula);

        cabecalho = new Paragraph("Nome");
        cabecalho.getFont().setStyle(Font.BOLD);
        cabecalho.getFont().setSize(8);
        PdfPCell cellNome = new PdfPCell(cabecalho); // celula
        cellNome.setBackgroundColor(BaseColor.LIGHT_GRAY);
        cellNome.setBorderColor(BaseColor.LIGHT_GRAY);
        cellNome.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cellNome);

        cabecalho = new Paragraph("Email");
        cabecalho.getFont().setStyle(Font.BOLD);
        cabecalho.getFont().setSize(8);
        PdfPCell cellEmail = new PdfPCell(cabecalho); // celula
        cellEmail.setBackgroundColor(BaseColor.LIGHT_GRAY);
        cellEmail.setBorderColor(BaseColor.LIGHT_GRAY);
        cellEmail.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cellEmail);

        cabecalho = new Paragraph("Telefone");
        cabecalho.getFont().setStyle(Font.BOLD);
        cabecalho.getFont().setSize(8);
        PdfPCell cellTelefone = new PdfPCell(cabecalho); // celula
        cellTelefone.setBackgroundColor(BaseColor.LIGHT_GRAY);
        cellTelefone.setBorderColor(BaseColor.LIGHT_GRAY);
        cellTelefone.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cellTelefone);

        cabecalho = new Paragraph("Curso");
        cabecalho.getFont().setStyle(Font.BOLD);
        cabecalho.getFont().setSize(8);
        PdfPCell cellCurso = new PdfPCell(cabecalho); // celula
        cellCurso.setBackgroundColor(BaseColor.LIGHT_GRAY);
        cellCurso.setBorderColor(BaseColor.LIGHT_GRAY);
        cellCurso.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cellCurso);

        for (int i = 0; i < allAlunos.size(); i++) {
            Aluno aluno = allAlunos.get(i);
            Paragraph texto = new Paragraph(aluno.getMatricula());
            cellMatricula = new PdfPCell(texto); // celula
            cellMatricula.setBorderColor(BaseColor.LIGHT_GRAY);
            texto.getFont().setSize(8);
            table.addCell(cellMatricula);
            texto = new Paragraph(aluno.getNome());
            texto.getFont().setSize(8);
            cellNome = new PdfPCell(texto); // celula
            cellNome.setBorderColor(BaseColor.LIGHT_GRAY);
            table.addCell(cellNome);
            texto = new Paragraph(aluno.getEmail());
            texto.getFont().setSize(8);
            cellEmail = new PdfPCell(texto); // celula
            cellEmail.setBorderColor(BaseColor.LIGHT_GRAY);
            table.addCell(cellEmail);
            texto = new Paragraph(aluno.getTelefone());
            texto.getFont().setSize(8);
            cellTelefone = new PdfPCell(texto); // celula
            cellTelefone.setBorderColor(BaseColor.LIGHT_GRAY);
            table.addCell(cellTelefone);
            texto = new Paragraph(aluno.getCursoidcurso().getNomecurso());
            texto.getFont().setSize(8);
            cellCurso = new PdfPCell(texto); // celula
            cellCurso.setBorderColor(BaseColor.LIGHT_GRAY);
            table.addCell(cellCurso);

        }
        table.setSpacingBefore(100);
        table.setSpacingAfter(10);
        table.completeRow();

        document.add(table);
        //add nova pagina
        document.newPage();
        //close document
        document.close();
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(RelatorioAluno.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(RelatorioAluno.class.getName()).log(Level.SEVERE, null, ex);
    }
    //return stream
    return baos;
}