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

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

Introduction

In this page you can find the example usage for com.itextpdf.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:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Writes text watermark to one of the 5 preconfigured locations
 * /*from   www .ja va  2 s. c o m*/
 * @param pcb
 * @param r
 * @param tokens
 * @param size
 * @param position
 */
private void writeAlignedText(PdfContentByte pcb, Rectangle r, Vector<String> tokens, float size,
        String position) {
    // get the dimensions of our 'rectangle' for text
    float height = size * tokens.size();
    float width = 0;
    float centerX = 0, startY = 0;
    for (int i = 0; i < tokens.size(); i++) {
        if (pcb.getEffectiveStringWidth(tokens.get(i), false) > width) {
            width = pcb.getEffectiveStringWidth(tokens.get(i), false);
        }
    }

    // now that we have the width and height, we can calculate the center
    // position for
    // the rectangle that will contain our text.
    if (position.equals(POSITION_BOTTOMLEFT)) {
        centerX = width / 2 + PAD;
        startY = 0 + PAD + height;
    } else if (position.equals(POSITION_BOTTOMRIGHT)) {
        centerX = r.getWidth() - (width / 2) - PAD;
        startY = 0 + PAD + height;
    } else if (position.equals(POSITION_TOPLEFT)) {
        centerX = width / 2 + PAD;
        startY = r.getHeight() - (PAD * 2);
    } else if (position.equals(POSITION_TOPRIGHT)) {
        centerX = r.getWidth() - (width / 2) - PAD;
        startY = r.getHeight() - (PAD * 2);
    } else if (position.equals(POSITION_CENTER)) {
        centerX = r.getWidth() / 2;
        startY = (r.getHeight() / 2) + (height / 2);
    }

    // apply text to PDF
    pcb.beginText();

    for (int t = 0; t < tokens.size(); t++) {
        pcb.showTextAligned(PdfContentByte.ALIGN_CENTER, tokens.get(t), centerX, startY - (size * t), 0);
    }

    pcb.endText();

}

From source file:org.gephi.preview.plugin.renderers.EdgeLabelRenderer.java

License:Open Source License

public void renderPDF(PDFTarget target, String label, float x, float y, Color color, float outlineSize,
        Color outlineColor) {//  ww w .  j  ava 2s  .  co  m
    PdfContentByte cb = target.getContentByte();
    cb.setRGBColorFill(color.getRed(), color.getGreen(), color.getBlue());
    BaseFont bf = target.getBaseFont(font);
    float textHeight = getTextHeight(bf, font.getSize(), label);
    if (outlineSize > 0) {
        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
        cb.setRGBColorStroke(outlineColor.getRed(), outlineColor.getGreen(), outlineColor.getBlue());
        cb.setLineWidth(outlineSize);
        cb.setLineJoin(PdfContentByte.LINE_JOIN_ROUND);
        cb.setLineCap(PdfContentByte.LINE_CAP_ROUND);
        if (outlineColor.getAlpha() < 255) {
            cb.saveState();
            float alpha = outlineColor.getAlpha() / 255f;
            PdfGState gState = new PdfGState();
            gState.setStrokeOpacity(alpha);
            cb.setGState(gState);
        }
        cb.beginText();
        cb.setFontAndSize(bf, font.getSize());
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, label, x, -y - (textHeight / 2f), 0f);
        cb.endText();
        if (outlineColor.getAlpha() < 255) {
            cb.restoreState();
        }
    }
    cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    cb.beginText();
    cb.setFontAndSize(bf, font.getSize());
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, label, x, -y - (textHeight / 2f), 0f);
    cb.endText();
}

From source file:org.gephi.preview.plugin.renderers.NodeLabelRenderer.java

License:Open Source License

public void renderPDF(PDFTarget target, Node node, String label, float x, float y, int fontSize, Color color,
        float outlineSize, Color outlineColor, boolean showBox, Color boxColor) {
    Font font = fontCache.get(fontSize);
    PdfContentByte cb = target.getContentByte();
    BaseFont bf = target.getBaseFont(font);

    //Box//from   w w w  . java  2s .  c om
    if (showBox) {
        cb.setRGBColorFill(boxColor.getRed(), boxColor.getGreen(), boxColor.getBlue());
        if (boxColor.getAlpha() < 255) {
            cb.saveState();
            float alpha = boxColor.getAlpha() / 255f;
            PdfGState gState = new PdfGState();
            gState.setFillOpacity(alpha);
            cb.setGState(gState);
        }
        float textWidth = getTextWidth(bf, fontSize, label);
        float textHeight = getTextHeight(bf, fontSize, label);

        //A height of just textHeight seems to be half the text height sometimes
        //BaseFont getAscentPoint and getDescentPoint may be not very precise
        cb.rectangle(x - textWidth / 2f - outlineSize / 2f, -y - outlineSize / 2f - textHeight,
                textWidth + outlineSize, textHeight * 2f + outlineSize);

        cb.fill();
        if (boxColor.getAlpha() < 255) {
            cb.restoreState();
        }
    }

    cb.setRGBColorFill(color.getRed(), color.getGreen(), color.getBlue());
    float textHeight = getTextHeight(bf, fontSize, label);
    if (outlineSize > 0) {
        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
        cb.setRGBColorStroke(outlineColor.getRed(), outlineColor.getGreen(), outlineColor.getBlue());
        cb.setLineWidth(outlineSize);
        cb.setLineJoin(PdfContentByte.LINE_JOIN_ROUND);
        cb.setLineCap(PdfContentByte.LINE_CAP_ROUND);
        if (outlineColor.getAlpha() < 255) {
            cb.saveState();
            float alpha = outlineColor.getAlpha() / 255f;
            PdfGState gState = new PdfGState();
            gState.setStrokeOpacity(alpha);
            cb.setGState(gState);
        }
        cb.beginText();
        cb.setFontAndSize(bf, font.getSize());
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, label, x, -y - (textHeight / 2f), 0f);
        cb.endText();
        if (outlineColor.getAlpha() < 255) {
            cb.restoreState();
        }
    }
    cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    cb.beginText();
    cb.setFontAndSize(bf, font.getSize());
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, label, x, -y - (textHeight / 2f), 0f);
    cb.endText();
}

From source file:org.javad.pdf.util.PdfUtil.java

License:Apache License

protected static void improveRenderText(PdfContentByte content, String str, Font f, float x, float y) {

    BaseFont bf = f.getCalculatedBaseFont(false);
    if (i18Font == null && (System.currentTimeMillis() - LAST_CHECK_TIME > 10000)) {
        i18Font = FontRegistry.getInstance().getFont(PdfFontDefinition.ExtendedCharacters)
                .getCalculatedBaseFont(false);
        LAST_CHECK_TIME = System.currentTimeMillis();
    }/*from ww w .j  a va  2s. co  m*/
    StringBuilder buf = new StringBuilder(str.length());
    boolean extendedCodePoint = false;
    float effWidth = 0.0f;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        int codePoint = Character.codePointAt("" + c, 0);
        boolean curCodePoint = (!bf.charExists(codePoint)) ? true : false;
        if (curCodePoint != extendedCodePoint) {
            content.setFontAndSize((extendedCodePoint) ? i18Font : bf, f.getSize());
            effWidth += content.getEffectiveStringWidth(buf.toString(), false);
            buf = new StringBuilder();
            extendedCodePoint = curCodePoint;
        }
        buf.append(c);
    }
    content.setFontAndSize(bf, f.getSize());
    effWidth += content.getEffectiveStringWidth(buf.toString(), false);
    float x_pos = x - (effWidth / 2.0f); // eq. to showTextAligned

    content.beginText();
    content.setTextMatrix(x_pos, y);
    BaseFont lastFont = bf;
    @SuppressWarnings("UnusedAssignment")
    BaseFont currentFont = lastFont;
    buf = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        int codePoint = Character.codePointAt("" + c, 0);
        if (!bf.charExists(codePoint)) {
            currentFont = i18Font;
        } else {
            currentFont = bf;
        }
        if (currentFont != lastFont) {
            content.showText(buf.toString());
            buf = new StringBuilder();
            content.setFontAndSize(currentFont, f.getSize());
            lastFont = currentFont;
        }
        buf.append(c);
    }
    if (buf.length() > 0) {
        content.showText(buf.toString());
    }
    content.endText();

}

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

License:Open Source License

private void addPageFooterInfo(PdfWriter writer, Document document) {
    PdfContentByte contentByte = writer.getDirectContent();
    contentByte.saveState();//from w  ww. j  a va2s  . c  o  m

    contentByte.setFontAndSize(baseFont, FOOTER_TEXT_SIZE);

    contentByte.beginText();
    writeCurrentDate(document, contentByte);
    writePageNumber(writer, document, contentByte);
    contentByte.endText();

    contentByte.restoreState();
}

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//  w  w  w  .  ja  v a2s . 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 w  w  .j  a  va2 s.  c om*/
        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) {/*from   w  w w  .  j a  va  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:pdf.PdfCreator.java

public String createPdf(String path, String ingredients, String recipeTitle, String recipeDescription)
        throws DocumentException, IOException {
    path += "shoppingList.pdf";
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
    document.open();//  ww w  .  j av  a  2  s .  c o  m
    String[] ings = ingredients.split(";");

    PdfContentByte cb = writer.getDirectContent();
    BaseFont bf = BaseFont.createFont();
    cb.beginText();
    Paragraph p = new Paragraph("Ingredients you'll need to buy:",
            new Font(FontFamily.HELVETICA, 20, Font.BOLD, new BaseColor(38, 165, 154)));
    p.add(Chunk.NEWLINE);
    document.add(p);

    cb.moveText(36, 750);
    cb.setFontAndSize(bf, 15);
    cb.endText();

    p = new Paragraph();
    for (String str : ings) {
        p.add(" ");
        p.add(str);
        p.add(Chunk.NEWLINE);
    }
    p.add(Chunk.NEWLINE);
    p.add(Chunk.NEWLINE);
    document.add(p);

    p = new Paragraph(recipeTitle, new Font(FontFamily.HELVETICA, 20, Font.BOLD, new BaseColor(38, 165, 154)));
    p.add(Chunk.NEWLINE);
    document.add(p);
    p = new Paragraph(recipeDescription, new Font(bf, 12));
    p.add(Chunk.NEWLINE);
    document.add(p);

    document.close();
    return path;
}

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

License:Open Source License

/**
 * @param args/*www  .j av a 2 s  .  co 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();
    }
}