Example usage for com.lowagie.text.pdf PdfWriter getDirectContentUnder

List of usage examples for com.lowagie.text.pdf PdfWriter getDirectContentUnder

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getDirectContentUnder.

Prototype


public PdfContentByte getDirectContentUnder() 

Source Link

Document

Use this method to get the direct content under for this document.

Usage

From source file:appli_etudiants.ExportPDF.java

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

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

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

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

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

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

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

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

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

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

From source file: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.  c  o  m*/
    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);

    /*/*from  ww w. ja va  2  s  .co m*/
    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:classroom.filmfestival_c.Movies19.java

protected static void drawMovie(PdfWriter writer, FestivalScreening screening, List<String> places,
        float minute, float left, float top, float row_height) throws DocumentException {
    FilmTitle movie = screening.getFilmTitle();
    // defining the rectangle
    int place = places.indexOf(screening.getId().getPlace());
    float llx, urx, lly, ury;
    llx = left + minute * getMinutesAfter930(screening);
    urx = llx + minute * (screening.getShortfilm() + movie.getDuration());
    ury = top - place * row_height;/*from  w w  w .  j  av a  2  s .c o  m*/
    lly = top - ((place + 1) * row_height);

    // FOREGROUND
    PdfContentByte foreground = writer.getDirectContent();

    // rectangle
    foreground.setColorStroke(BLACK);
    foreground.setLineWidth(1);
    foreground.moveTo(urx, lly);
    foreground.lineTo(llx, lly);
    foreground.lineTo(llx, ury);
    foreground.lineTo(urx, ury);
    foreground.closePathStroke();
    // title
    ColumnText ct = new ColumnText(foreground);
    ct.setSimpleColumn(new Phrase(movie.getTitle(), SMALLEST), llx, lly, urx, ury, 14, Element.ALIGN_CENTER);
    ct.go();

    // BACKGROUND
    PdfContentByte background = writer.getDirectContentUnder();

    // draw background
    background.setColorFill(getColor(movie));
    background.moveTo(urx, lly);
    background.lineTo(llx, lly);
    background.lineTo(llx, ury);
    background.lineTo(urx, ury);
    background.fill();

    // draw a white P for press screenings
    if (screening.getPress() == 1) {
        background.saveState();
        background.beginText();
        background.setFontAndSize(FONT, 24);
        background.setColorFill(WHITE);
        background.showTextAligned(Element.ALIGN_CENTER, "P", (llx + urx) / 2f, (lly + ury) / 2f - 12, 0);
        background.endText();
        background.restoreState();
    }

    // draw shortfilm
    background.setColorStroke(WHITE);
    if (screening.getShortfilm() > 0) {
        background.moveTo(llx + (minute * screening.getShortfilm()), lly);
        background.lineTo(llx + (minute * screening.getShortfilm()), ury);
        background.stroke();
    }
}

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

License:Open Source License

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

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

    PdfContentByte canvas = writer.getDirectContentUnder();

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

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

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

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

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

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

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

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

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

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

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

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

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

}

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

License:Apache License

/**
 * ??//w  w w  .j av  a 2 s  .  c  o m
 * 
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)
 */
@Override
public void onOpenDocument(PdfWriter writer, Document doc) {
    canvas = writer.getDirectContentUnder();
}

From source file:fr.opensagres.xdocreport.itext.extension.ExtendedHeaderFooter.java

License:Open Source License

/**
 * Adds a header/footer to every page/*from   ww w  . j ava2  s  .co m*/
 * 
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
 *      com.itextpdf.text.Document)
 */
public void onStartPage(PdfWriter writer, Document doc) {
    if (masterPage == null) {
        masterPage = document.getDefaultMasterPage();
    }

    if (masterPage != null) {
        // Master page is defined

        IMasterPageHeaderFooter header = masterPage.getHeader();
        IMasterPageHeaderFooter footer = masterPage.getFooter();

        // Add header
        if (header != null) {
            // compute upper-left corner coordinates
            float x = document.getOriginMarginLeft();
            float y = getHeaderY(header);

            header.writeSelectedRows(0, -1, x, y, writer.getDirectContentUnder());
        }

        // Add footer
        if (footer != null) {
            // compute upper-left corner coordinates
            float x = document.getOriginMarginLeft();
            float y = getFooterY(footer);

            footer.writeSelectedRows(0, -1, x, y, writer.getDirectContentUnder());
        }
    }
}

From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java

License:Open Source License

public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception {
    URL inputHOCRFile = null;// w w w  .j  av a  2 s .com
    FileOutputStream outputPDFStream = null;
    // The resolution of a PDF file (using iText) is 72pt per inch
    float pointsPerInch = 72.0f;
    Source source = null;
    StartTag pageTag = null;
    Pattern imagePattern = null;
    Matcher imageMatcher = null;
    // Load the image
    Image pageImage = null;
    float dotsPerPointX;
    float dotsPerPointY;
    float pageImagePixelHeight;
    Document pdfDocument = null;
    PdfWriter pdfWriter = null;
    Font defaultFont = null;
    PdfContentByte cb = null;
    Pattern bboxPattern = null;
    Pattern bboxCoordinatePattern = null;
    StartTag ocrLineTag = null;

    try {
        try {
            inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath());
        } catch (MalformedURLException e) {
            throw e;
        }
        try {
            outputPDFStream = new FileOutputStream(fPdf);
        } catch (FileNotFoundException e) {
            throw e;
        }

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

        // Find the tag of class ocr_page in order to load the scanned image
        pageTag = source.findNextStartTag(0, "class", "ocr_page", false);
        imagePattern = Pattern.compile("image\\s+([^;]+)");
        imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
        if (!imageMatcher.find()) {
            throw new Exception("Could not find a tag of class \"ocr_page\", aborting.");
        }

        try {
            pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath()));
        } catch (MalformedURLException e) {
            throw e;
        }
        dotsPerPointX = pageImage.getDpiX() / pointsPerInch;
        dotsPerPointY = pageImage.getDpiY() / pointsPerInch;
        pageImagePixelHeight = pageImage.getHeight();
        pdfDocument = new Document(
                new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY));
        pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
        pdfDocument.open();

        // first define a standard font for our text
        defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

        // Put the text behind the picture (reverse for debugging)
        cb = pdfWriter.getDirectContentUnder();
        //PdfContentByte cb = pdfWriter.getDirectContent();

        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      
        bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
        // This pattern separates the coordinates of the bbox property
        bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
        // Only tags of the ocr_line class are interesting
        ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false);
        while (ocrLineTag != null) {
            au.id.jericho.lib.html.Element lineElement = ocrLineTag.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().extractText();
                //               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);
                // TODO: Scale the text width to fit the OCR bbox
                cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt));
                cb.moveText((float) (coordinates[0] / dotsPerPointX),
                        (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                cb.showText(line);
                cb.endText();
            }
            ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false);
        }
    } catch (NumberFormatException e) {
        throw e;
    } catch (MalformedURLException e) {
        throw e;
    } catch (FileNotFoundException e) {
        throw e;
    } catch (BadElementException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (DocumentException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    } finally {
        if (pdfDocument != null) {
            pdfDocument.close();
        }
        if (outputPDFStream != null) {
            outputPDFStream.close();
        }
    }
}

From source file:org.kuali.kfs.module.purap.pdf.PurapPdf.java

License:Open Source License

/**
 * Overrides the method in PdfPageEventHelper from itext to include our watermark text to indicate that
 * this is a Test document and include the environment, if the environment is not a production environment.
 *
 * @param writer    The PdfWriter for this document.
 * @param document  The document./*from www. j av  a  2 s .  c o m*/
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
@Override
public void onStartPage(PdfWriter writer, Document document) {
    if (!KRADUtils.isProductionEnvironment()) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        String watermarkText = "Test document (" + environment + ")";
        cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2,
                document.getPageSize().height() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
    if (GlobalVariables.getUserSession() != null
            && GlobalVariables.getUserSession().retrieveObject("isPreview") != null) {
        GlobalVariables.getUserSession().removeObject("isPreview");
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        String watermarkText = "DRAFT";
        cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2,
                document.getPageSize().height() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}

From source file:org.kuali.ole.module.purap.pdf.PurapPdf.java

License:Educational Community License

/**
 * Overrides the method in PdfPageEventHelper from itext to include our watermark text to indicate that
 * this is a Test document and include the environment, if the environment is not a production environment.
 *
 * @param writer   The PdfWriter for this document.
 * @param document The document./*from  w  w  w. j  av  a  2  s .  co  m*/
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onStartPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onStartPage(PdfWriter writer, Document document) {
    if (!KRADUtils.isProductionEnvironment()) {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        String watermarkText = "Test document (" + environment + ")";
        cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2,
                document.getPageSize().height() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
    if (GlobalVariables.getUserSession() != null
            && GlobalVariables.getUserSession().retrieveObject("isPreview") != null) {
        GlobalVariables.getUserSession().removeObject("isPreview");
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        cb.beginText();
        cb.setFontAndSize(helv, 48);
        String watermarkText = "DRAFT";
        cb.showTextAligned(Element.ALIGN_CENTER, watermarkText, document.getPageSize().width() / 2,
                document.getPageSize().height() / 2, 45);
        cb.endText();
        cb.restoreState();
    }
}