Example usage for com.lowagie.text.pdf PdfContentByte endText

List of usage examples for com.lowagie.text.pdf PdfContentByte endText

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte endText.

Prototype

public void endText() 

Source Link

Document

Ends the writing of text and makes the current font invalid.

Usage

From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java

License:Open Source License

private void buildFooter(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();

    cb.saveState();//from w w w  .  j a  va  2  s.c  o m

    String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " ";

    float textBase = document.bottom() - 25;
    float textSize = FontUtils.getDejavu().getWidthPoint(text, 7);

    cb.setColorFill(ColorUtils.getLightColor());
    cb.setColorStroke(ColorUtils.getLightColor());
    cb.setLineWidth(1);
    cb.setLineDash(2, 2, 1);
    cb.moveTo(document.left(), document.bottom() - 10);
    cb.lineTo(document.right(), document.bottom() - 10);
    cb.stroke();
    cb.beginText();
    cb.setFontAndSize(FontUtils.getDejavu(), 7);

    float adjust = FontUtils.getDejavu().getWidthPoint("0", 7);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);

    textSize = FontUtils.getDejavu().getWidthPoint(footer.getGeneratedBy(), 7);

    cb.setTextMatrix(document.right() - textSize, textBase - 10);
    cb.showText(footer.getGeneratedBy());

    textSize = FontUtils.getDejavu().getWidthPoint(generationDate, 7);

    cb.setTextMatrix(document.right() - textSize, textBase - 20);
    cb.showText(generationDate);
    cb.endText();

    try {
        textSize = FontUtils.getDejavu().getWidthPoint(footer.getAdditionalText(), 7);

        ColumnText ct = new ColumnText(cb);

        ct.setSimpleColumn(new Phrase(footer.getAdditionalText(), FontUtils.getDejavuRegular7Light()),
                document.left() + 240, textBase + 10, document.left() + 390, textBase - 25, 10,
                Element.ALIGN_LEFT);
        ct.go();
    } catch (DocumentException e) {
        LOG.warn("Problem with additional text generation in report footer.");
    }

    try {
        ColumnText ct = new ColumnText(cb);

        ct.setSimpleColumn(document.left(), textBase + 10, document.left() + 230, textBase - 25, 10,
                Element.ALIGN_LEFT);
        ct.addText(new Phrase(footer.getCompanyName() + "\n", FontUtils.getDejavuRegular7Light()));

        if (!"".equals(footer.getAddress())) {
            ct.addText(new Phrase(footer.getAddress() + "\n", FontUtils.getDejavuRegular7Light()));
        }
        if (!"".equals(footer.getPhoneEmail())) {
            ct.addText(new Phrase(footer.getPhoneEmail(), FontUtils.getDejavuRegular7Light()));
        }

        ct.go();
    } catch (DocumentException e) {
        LOG.warn("Problem with company text generation in report footer.");
    }

    cb.addTemplate(total, document.right() - adjust, textBase);
    cb.restoreState();

}

From source file:com.qcadoo.report.api.pdf.PdfPageNumbering.java

License:Open Source License

private void buildHeader(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();/* w ww.j a  v a2 s.  c  o m*/
    String text = footer.getPage() + " " + writer.getPageNumber() + " " + footer.getIn() + " ";

    float textBase = document.top() + 22;
    float textSize = FontUtils.getDejavu().getWidthPoint(text, 7);

    cb.setColorFill(ColorUtils.getLightColor());
    cb.setColorStroke(ColorUtils.getLightColor());
    cb.beginText();
    cb.setFontAndSize(FontUtils.getDejavu(), 7);

    float adjust = FontUtils.getDejavu().getWidthPoint("0", 7);

    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(total, document.right() - adjust, textBase);
    cb.setLineWidth(1);
    cb.setLineDash(2, 2, 1);
    cb.moveTo(document.left(), document.top() + 12);
    cb.lineTo(document.right(), document.top() + 12);
    cb.stroke();
    cb.restoreState();

}

From source file:com.square.adherent.noyau.service.implementations.RelevePrestationServiceImpl.java

License:Open Source License

@Override
public FichierDto getRelevePrestationByteArray(Long idRelevePrestation, Long idPersonne, boolean duplicata) {
    logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_CONVERSION_RELEVE_PRESTATION,
            new String[] { String.valueOf(idRelevePrestation) }));
    final CritereSelectionRelevePrestationDto critereSelectionRelevePrestationDto = new CritereSelectionRelevePrestationDto();
    critereSelectionRelevePrestationDto.setRelevePrestationId(idRelevePrestation);
    if (idPersonne != null) {
        critereSelectionRelevePrestationDto.setIdPersonne(idPersonne);
    }//www .j a v a 2  s.c  om
    final List<RelevePrestation> lstReleves = relevePrestationDao
            .getListeReleveParCriteres(critereSelectionRelevePrestationDto, null);
    if (lstReleves.size() == 1) {
        final RelevePrestation releve = lstReleves.get(0);
        final String error = messageSourceUtil.get(MessageKeyUtil.ERROR_RECUPERATION_FICHIER);
        FichierDto fichier;
        final String cheminFichier = serveurEmcRepReleve + File.separator + releve.getNomFichier();
        try {
            fichier = new FichierDto();
            fichier.setNomFichier(releve.getNomFichierCommercial());
            if (duplicata) {
                // On appose la mention "DUPLICATA" sur toutes les pages du relev.
                try {
                    final PdfReader reader = new PdfReader(cheminFichier);
                    final int nombrePages = reader.getNumberOfPages();
                    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.WINANSI,
                            BaseFont.EMBEDDED);
                    final PdfStamper stamp = new PdfStamper(reader,
                            new FileOutputStream(FICHIER_DUPLICATA_TEMP));
                    final int taillePolice = 56;
                    final int positionX = ((int) PageSize.A4.getWidth()) / 2;
                    final int positionY = ((int) PageSize.A4.getHeight()) / 2;
                    final int rotation = 30;
                    for (int i = 1; i <= nombrePages; i++) {
                        final PdfContentByte over = stamp.getOverContent(i);
                        over.beginText();
                        over.setColorFill(Color.GRAY);
                        final PdfGState gs1 = new PdfGState();
                        gs1.setFillOpacity(NIVEAU_TRANSPARENCE);
                        over.setGState(gs1);
                        over.setFontAndSize(bf, taillePolice);
                        over.showTextAligned(PdfContentByte.ALIGN_CENTER, "DUPLICATA", positionX, positionY,
                                rotation);
                        over.endText();
                    }
                    stamp.close();
                    reader.close();
                    fichier.setContenu(IOUtils.toByteArray(new FileInputStream(FICHIER_DUPLICATA_TEMP)));
                    final File file = new File(FICHIER_DUPLICATA_TEMP);
                    file.delete();
                } catch (DocumentException e) {
                    throw new TechnicalException(
                            messageSourceUtil.get(MessageKeyUtil.ERROR_IMPOSSIBLE_AJOUTER_MENTION_DUPLICATA,
                                    new String[] { releve.getNomFichier() }));
                }
            } else {
                fichier.setContenu(IOUtils.toByteArray(new FileInputStream(cheminFichier)));
            }
            fichier.setTypeMime(Magic.getMagicMatch(fichier.getContenu()).getMimeType());
        } catch (FileNotFoundException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (IOException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicParseException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicMatchNotFoundException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        } catch (MagicException e) {
            logger.error(error + releve.getNomFichier(), e);
            throw new TechnicalException(error + cheminFichier);
        }
        return fichier;
    } else {
        throw new TechnicalException(
                messageSourceUtil.get(MessageKeyUtil.ERROR_ABSCENCE_RELEVE_PRESTATION_PERSONNE));
    }
}

From source file:com.t2.compassionMeditation.ViewSessionsActivity.java

License:Open Source License

/**
 * Create a PDF file based on the contents of the graph
 *///from w  w  w . j  ava  2 s .  c  o m
void CreatePdf() {

    // Run the export on a separate thread.
    new Thread(new Runnable() {
        @Override
        public void run() {

            Document document = new Document();
            try {
                Date calendar = Calendar.getInstance().getTime();
                mResultsFileName = "BioZenResults_";
                mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-"
                        + calendar.getDate() + "_";
                mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-"
                        + calendar.getSeconds() + ".pdf";

                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(android.os.Environment.getExternalStorageDirectory()
                                + java.io.File.separator + mResultsFileName));
                document.open();
                PdfContentByte contentByte = writer.getDirectContent();
                BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                // Note top of PDF = 900
                float chartWidth = 332;
                float chartHeight = 45;

                float spaceHeight = chartHeight + 30;
                int horizontalPos = 180;
                float verticalPos = 780;

                // Write document header
                contentByte.beginText();
                contentByte.setFontAndSize(baseFont, 20);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER,
                        "Generated on: " + calendar.toLocaleString(), 300, 770, 0);
                contentByte.endText();

                contentByte.setLineWidth(1f);
                verticalPos -= spaceHeight;
                long startTime = startCal.getTimeInMillis();
                long endTime = endCal.getTimeInMillis();

                float maxChartValue = 0;
                float chartYAvg;

                BioSession tmpSession = sessionItems.get(0);
                int maxKeys = tmpSession.keyItemNames.length;

                // Loop through all of the the keys
                for (int key = 0; key < maxKeys; key++) {

                    //Draw a border rect
                    contentByte.setRGBColorStrokeF(0, 0, 0);
                    contentByte.setLineWidth(1f);
                    contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight);
                    contentByte.stroke();

                    // Write band name
                    contentByte.beginText();
                    contentByte.setFontAndSize(baseFont, 12);
                    BioSession tmpSession1 = sessionItems.get(0);
                    contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170,
                            (verticalPos + (chartHeight / 2)) - 5, 0);
                    contentByte.endText();

                    maxChartValue = 0;
                    // First find the max Y
                    for (BioSession session : sessionItems) {
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            if (chartYAvg > maxChartValue)
                                maxChartValue = chartYAvg;
                        }
                    }

                    float lastY = -1;
                    float xIncrement = 0;
                    if (sessionItems.size() > 0) {
                        xIncrement = chartWidth / sessionItems.size();
                    }

                    float yIncrement = 0;
                    if (maxChartValue > 0) {
                        yIncrement = chartHeight / maxChartValue;
                    }

                    float highValue = 0;
                    int highTime = 0;
                    float highY = 0;
                    float highX = 0;
                    int lowTime = 0;
                    float lowY = 100;
                    float lowX = chartWidth;
                    float lowValue = maxChartValue;

                    int lCount = 0;
                    String keyName = "";

                    ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>();

                    // Loop through the session points of this key
                    String rawYValues = "";
                    for (BioSession session : sessionItems) {
                        keyName = session.keyItemNames[key];
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            rawYValues += chartYAvg + ", ";
                            if (lastY < 0)
                                lastY = (float) chartYAvg;

                            contentByte.setLineWidth(3f);
                            contentByte.setRGBColorStrokeF(255, 0, 0);

                            float graphXFrom = horizontalPos + (lCount * xIncrement);
                            float graphYFrom = verticalPos + (lastY * yIncrement);
                            float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement));
                            float graphYTo = verticalPos + (chartYAvg * yIncrement);
                            //                     Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]");
                            // Draw the actual graph
                            contentByte.moveTo(graphXFrom, graphYFrom);
                            contentByte.lineTo(graphXTo, graphYTo);
                            contentByte.stroke();

                            //Add regression Item
                            ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement)));

                            if (chartYAvg > highValue) {
                                highValue = chartYAvg;
                                highY = graphYTo;
                                highX = graphXTo;
                                highTime = (int) (session.time / 1000);
                            }

                            if (chartYAvg < lowValue) {
                                lowValue = chartYAvg;
                                lowY = graphYTo;
                                lowX = graphXTo;
                                lowTime = (int) (session.time / 1000);
                            }

                            lCount++;
                            lastY = (float) chartYAvg;

                        } // End if (session.time >= startTime && session.time <= endTime )
                    } // End for (BioSession session : sessionItems)            

                    //Draw high low dates
                    if (highY != 0 && lowY != 0) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
                        String hDate = dateFormat.format(new Date((long) highTime * 1000L));
                        String lDate = dateFormat.format(new Date((long) lowTime * 1000L));
                        contentByte.beginText();
                        contentByte.setFontAndSize(baseFont, 8);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0);
                        contentByte.endText();
                    }

                    //Draw Regression Line
                    RegressionResult regression = calculateRegression(ritems);
                    contentByte.saveState();
                    contentByte.setRGBColorStrokeF(0, 0, 250);
                    contentByte.setLineDash(3, 3, 0);
                    contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept);
                    contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept)
                            + (float) (regression.slope * (chartWidth / xIncrement))));
                    contentByte.stroke();
                    contentByte.restoreState();
                    contentByte.setRGBColorStrokeF(0, 0, 0);

                    //               Log.e(TAG, keyName + ": [" + rawYValues + "]");
                    // Get ready for the next key (and series of database points )
                    verticalPos -= spaceHeight;

                    if (verticalPos < 30) {
                        document.newPage();
                        verticalPos = 780 - spaceHeight;
                    }

                } // End for (int key = 0; key < maxKeys; key++)

                //document.add(new Paragraph("You can also write stuff directly tot he document like this!"));
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
                Log.e(TAG, de.toString());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
                Log.e(TAG, ioe.toString());
            } catch (Exception e) {
                System.err.println(e.getMessage());
                Log.e(TAG, e.toString());
            }

            // step 5: we close the document
            document.close();
            fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS);

        }
    }).start();

}

From source file:com.teag.reports.CashFlows.java

private void drawLifeExp() {
    PdfContentByte cb = writer.getDirectContentUnder();
    char c = userInfo.getClientFirstName().charAt(0);
    char s = ' ';
    if (!userInfo.isSingle()) {
        s = userInfo.getSpouseFirstName().charAt(0);
    }/*  ww w.ja  va  2  s.co  m*/

    String cText = Character.toString(c) + ": " + userInfo.getClientFirstName()
            + " actuarial life expectancy - " + userInfo.getClientLifeExpectancy() + " years";
    String sText = Character.toString(s) + ": " + userInfo.getSpouseFirstName()
            + " actuarial life expectancy - " + userInfo.getSpouseLifeExpectancy() + " years";
    try {
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);

        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(255, 0, 0);
        cb.setTextMatrix(72 * .5F, .5f * 72);
        cb.showText(cText);
        cb.endText();
        if (!userInfo.isSingle()) {
            cb.beginText();
            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(255, 0, 0);
            cb.setTextMatrix(72 * .5F, .35f * 72);
            cb.showText(sText);
            cb.endText();
        }
    } catch (Exception e) {
        System.err.println("Error printing Life Expectancy");
    }
}

From source file:com.teag.reports.EstatePlan.java

private void drawLifeExp() {
    PdfContentByte cb = writer.getDirectContentUnder();

    char c = userInfo.getClientFirstName().charAt(0);
    char s = ' ';
    if (!userInfo.isSingle()) {
        s = userInfo.getSpouseFirstName().charAt(0);
    }//from   w ww  . ja  v a  2  s  .co  m

    String cText = Character.toString(c).toUpperCase() + ": " + userInfo.getClientFirstName()
            + " actuarial life expectancy - " + userInfo.getClientLifeExpectancy() + " years";
    String sText = Character.toString(s).toUpperCase() + ": " + userInfo.getSpouseFirstName()
            + " actuarial life expectancy - " + userInfo.getSpouseLifeExpectancy() + " years";
    try {
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);

        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(255, 0, 0);
        cb.setTextMatrix(72 * .5F, .4f * 72);
        cb.showText(cText);
        cb.endText();
        if (!userInfo.isSingle()) {
            cb.beginText();
            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(255, 0, 0);
            cb.setTextMatrix(72 * .5F, .25f * 72);
            cb.showText(sText);
            cb.endText();
        }
    } catch (Exception e) {
        System.err.println("Error printing Life Expectancy");
    }
}

From source file:com.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file./* w w w  .  j  av a  2  s.  co m*/
 *
 * @param streamOfPDFFiles - a list of inputStreams
 * @param outputStream - an instance of outputStream
 * @param paginate - a boolean
 * @throws AkuraAppException - The exception details that occurred when processing
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate)
        throws AkuraAppException {

    final int fontSize = 8, leftRightAlignment = 8;
    final int min = 0;
    final int max = 5;
    final int size = 300;
    final int xAxis = -150;
    final int pageHeight = 550;
    final int pageHieghtfromBottom = 16;
    final int pageRecHeight = 580;
    final int recHeightFromBottom = 14;
    Document document = new Document(PageSize.A4);
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the output stream
        PdfWriter writer = null;
        BaseFont bf = null;
        try {
            writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                if (currentPageNumber != 2) {
                    document.newPage();
                }
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                if (currentPageNumber == 1) {
                    cb.addTemplate(page, 0, xAxis);
                } else if (currentPageNumber != 2) {
                    cb.addTemplate(page, 0, 0);
                }

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, fontSize);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size,
                            max, min);
                    cb.newlineText();
                    cb.endText();

                    if (currentPageNumber != 2) {
                        int pageNo = currentPageNumber;
                        if (currentPageNumber != 1) {
                            pageNo = currentPageNumber - 1;
                        }

                        // write the page number inside a rectangle.
                        cb.fillStroke();
                        cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight,
                                leftRightAlignment);
                        cb.beginText();
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight,
                                pageHieghtfromBottom, 0);
                        cb.endText();
                        cb.stroke();
                    }
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();

        document.close();

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:corner.orm.tapestry.pdf.PdfOutputPageEvent.java

License:Apache License

private void createBurdenText(PdfWriter writer) {
    PdfContentByte content = writer.getDirectContent();
    content.beginText();
    content.endText();
}

From source file:de.cuseb.bilderbuch.pdf.PdfController.java

License:Open Source License

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) {

    try {//ww w .  j  av a2 s . c om
        PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest");
        httpServletResponse.setContentType("application/pdf");

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream());
        writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB);

        //document.addAuthor(pdfRequest.getAuthor());
        //document.addTitle(pdfRequest.getTitle());
        document.setPageSize(
                new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148)));
        document.open();

        FontFactory.defaultEmbedding = true;
        FontFactory.register("IndieRock.ttf", "IndieRock");
        Font font = FontFactory.getFont("IndieRock");
        BaseFont baseFont = font.getBaseFont();
        PdfContentByte cb = writer.getDirectContent();

        Iterator<PdfPage> pages = pdfRequest.getPages().iterator();
        while (pages.hasNext()) {

            PdfPage page = pages.next();
            if (page.getImage() != null) {

                Image image = Image.getInstance(new URL(page.getImage().getUrl()));
                image.setDpi(300, 300);
                image.setAbsolutePosition(0f, 0f);
                image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                document.add(image);

                cb.saveState();
                cb.beginText();
                cb.setColorFill(Color.WHITE);
                cb.moveText(10f, 10f);
                cb.setFontAndSize(baseFont, 18);
                cb.showText(page.getSentence());
                cb.endText();
                cb.restoreState();

                if (pages.hasNext()) {
                    document.newPage();
                }
            }
        }
        document.close();

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

From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java

License:GNU General Public License

/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)/*  w w  w.  j ava  2 s .  c  om*/
 */
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headertable
    table.setTotalWidth(document.right() - document.left());
    table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 20, cb);
    // compose the footer
    String text = writer.getPageNumber() + " / ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 49;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust - 5, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
    // draw a Rectangle around the page
    cb.setLineWidth(1);
    cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40);
    cb.stroke();
    cb.restoreState();
}