Example usage for com.itextpdf.text.pdf BaseFont CP1250

List of usage examples for com.itextpdf.text.pdf BaseFont CP1250

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf BaseFont CP1250.

Prototype

String CP1250

To view the source code for com.itextpdf.text.pdf BaseFont CP1250.

Click Source Link

Document

A possible encoding.

Usage

From source file:fattura.Fattura.java

public void inserisciDatiPubb(String cliente, String data, PdfStamper s)
        throws SQLException, IOException, DocumentException {
    ArrayPubblicita arraypubb = new ArrayPubblicita();
    arraypubb.ArrayIDpubb(cliente, data);
    float importo;

    PdfContentByte content = s.getUnderContent(1);//1 for the first page
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
    content.setFontAndSize(bf, 7);/*ww  w. j  av  a2s .co  m*/

    for (int j = 0; j < arraypubb.IDpubb.length; j++) {
        arraypubb.accessoPubb(j);
        importo = arraypubb.importoPubblicita(j);
        String convertitore = String.valueOf(importo); //Serve per convertire il ritorno del metodo importoUnitarioMaglia (float) a string per stamparlo,  solo un appoggio
        importi.add(importo); //salva l'importo maglia nella prima posizione array i cui elementi poi andranno sommati per calcolare il totale

        for (int z = 0; z < arraypubb.riga.length; z++) {
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, arraypubb.riga[z] + "   ", 95 + x, 538 - y, 0);
            x += 97; //sposta la coordinata y ad ogni stampa
        }

        content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Mat. Pubb.", 95 + x, 538 - y, 0);
        x += 101;
        content.showTextAligned(PdfContentByte.ALIGN_LEFT, convertitore, 95 + x, 538 - y, 0);

        x = 0;
        y += 20;
    }

}

From source file:gravabncertificado.GerandoArquivoCarimbado_1.java

public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN) throws InvalidPdfException {
    //Copiando arquivo informado.
    try {/*w  w w.java2s  . c om*/

        // Adicionado parametro para nao retornar erro quando o documento for protegido.
        PdfReader.unethicalreading = true;
        //Cria o reader para o primeiro PDF

        PdfReader reader = new PdfReader(caminhoarquivo);

        // n recebe o numero total de paginas
        int n = reader.getNumberOfPages();

        //Tamanho da primeira Pagina
        ;

        //Cria Segundo PDF

        Document document = new Document(PageSize.A4, 36, 36, 36, 36);

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));

        document.open();

        // Adiciona conteudo ao PDF Carimbado.
        PdfContentByte cb = writer.getDirectContent();
        int i = 0;
        int p = 0;
        String caminhodestino = (caminhoarquivo.substring(0, caminhoarquivo.length() - BN.length()));

        // DESABILITADO PORQUE O MOVER NAO ESTAVA FUNCIONANDO.
        File destinooriginal = new File(caminhodestino + "ORIGINAL\\");
        if (!destinooriginal.exists()) {
            destinooriginal.mkdir();
        }

        caminhodestino = (caminhodestino + "ORIGINAL\\" + BN);

        //TESTANDO NOVA FORMA DE COPIAR

        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);

        FileInputStream fis = new FileInputStream(origem);
        FileOutputStream fos = new FileOutputStream(destino);

        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();

        long transferFrom = outChannel.transferFrom(inChannel, 0, inChannel.size());

        fis.close();
        fos.close();
        inChannel.close();
        outChannel.close();

        // Thread.sleep(10);

        BN = BN.substring(0, BN.length() - 4);

        while (i < n) {
            document.newPage();
            p++;
            i++;

            PdfContentByte under = writer.getDirectContentUnder();
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 0, i * 0.2f);

            // Page 1: a rectangle
            /* RETANGULO DESATIVADO
            drawRectangle(under, 100, 50);
            under.setRGBColorFill(255, 220, 220);
            under.rectangle(width /50, 5, 118, 40);
            under.fill();
            */

            //CARIMBO DA BN

            BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            cb.beginText();
            cb.setFontAndSize(bf, 14);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
            cb.endText();

        }

        document.close();
        writer.close();
        reader.close();
        origem.delete();

        /* PdfContentByte under = writer.getDirectContentUnder();
                 
         // Page 1: a rectangle
             drawRectangle(under, 20, 20);
             under.setRGBColorFill(0xFF, 0xD7, 0x00);
             under.rectangle(5, 5, 15, 15);
             under.fill(); */
        //document.newPage();

        //COPIANDO ARQUIVO CARIMBADO

        /* DESABILITADO PORQUE NAO ESTAVA FUNCIONANDO.
        boolean bool;
                
         //caminhoarquivo = caminhoarquivo.replace("\\", "\\\\");
         //caminhodestino = caminhodestino.replace("\\", "\\\\");
                    
        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);
                
                    
        bool = origem.renameTo(destino);
        System.out.println(origem);
        System.out.println(caminhodestino);
        */

    } catch (IOException | DocumentException ex) {
    }

}

From source file:gravabncertificado007.CarimboCertificado.java

public void aplicaCarimboBin(String BN, String caminhoarquivo)
        throws DocumentException, IOException, RuntimeException {

    PdfReader.unethicalreading = true;/*  w w  w . j  av a2s.c o m*/
    //Cria o reader para o primeiro PDF

    PdfReader reader = new PdfReader(caminhoarquivo);
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getWidth();
    float height = psize.getHeight();

    Document document = new Document(new Rectangle(width, height));

    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));

    document.open();

    int i = 0;
    BN = BN.substring(BN.length() - 13, BN.length() - 4);
    PdfContentByte cb = writer.getDirectContent();
    while (i < reader.getNumberOfPages()) {
        i++;

        document.newPage();

        PdfContentByte under = writer.getDirectContentUnder();
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, 0, i * 0.2f);

        //CARIMBO DA BN
        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
        cb.endText();

    }

    document.close();
    writer.close();
    reader.close();

}

From source file:gravabncertificado007.CarimboCertificado.java

public void aplicaCariboGedi(String BN, String caminhoarquivo)
        throws DocumentException, IOException, RuntimeException {

    PdfReader.unethicalreading = true;//from   w w  w.  j  ava2  s.  c  o m
    //Cria o reader para o primeiro PDF

    PdfReader reader = new PdfReader(caminhoarquivo);
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getWidth();
    float height = psize.getHeight();

    Document document = new Document(new Rectangle(width, height));

    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-G.pdf"));

    document.open();

    int i = 0;
    BN = BN.substring(BN.length() - 13, BN.length() - 4);
    PdfContentByte cb = writer.getDirectContent();
    while (i < reader.getNumberOfPages()) {
        i++;

        document.newPage();

        PdfContentByte under = writer.getDirectContentUnder();
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, 0, i * 0.2f);

        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "  _________________  ", width / 6, 44, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 32, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 22, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |Copia Controlada |", width / 6, 28, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 16, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |                 |", width / 6, 12, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |_________________|", width / 6, 14, 0);
        cb.endText();
    }

    document.close();
    writer.close();
    reader.close();

}

From source file:hr.ws4is.tn3812.drivers.listeners.PdfListener.java

License:Open Source License

public PdfListener() {
    super();//from  www.  j  a v  a  2 s. c  o m
    try {
        courier = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException documentException) {
        LOGGER.error(documentException.getMessage(), documentException);
    } catch (IOException ioException) {
        LOGGER.error(ioException.getMessage(), ioException);
    }
}

From source file:htmlparser.pdf.PDFFile.java

public PDFFile(Parser parser) {

    this.parser = parser;
    this.document = new Document();

    try {//from  w  w  w  . j a  v  a2  s .c o  m

        PdfWriter.getInstance(this.document, new FileOutputStream(this.parser.getCompetitionName() + ".pdf"));
        this.document.open();
        this.fonttype = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        this.opened = true;

    } catch (Exception ex) {
        this.opened = false;
    }
}

From source file:jati.GerandoArquivoCarimbado.java

public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN)
        throws InvalidPdfException, IOException {
    //Copiando arquivo informado.

    try {//from  w  w w.j a  v a2  s  .  c o m

        // Adicionado parametro para nao retornar erro quando o documento for protegido.
        PdfReader.unethicalreading = true;

        PdfWriter writer = PdfWriter.getInstance(montaraAquivo(caminhoarquivo),
                new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));
        // ABRE O DOCUMENTO CRIADO PARA MANUSEIO
        montaraAquivo(caminhoarquivo).open();

        //SUBSTRING RETIRA PARTE DO TEXTO ENTRE OS INDICES ESPECIFICADOS 
        //caminhoDestino RECEBE UM NOVO CAMINHO RESULTANTE DOS INDICES DE CAMINHO.LENGTH - BN.LENGTH
        // QUE FORMAM UMA NOVA STRING
        String caminhodestino = (caminhoarquivo.substring(0, caminhoarquivo.length() - BN.length()));

        File destinooriginal = new File(caminhodestino + "ORIGINAL\\");
        if (!destinooriginal.exists()) {
            destinooriginal.mkdir();
        }

        caminhodestino = (caminhodestino + "ORIGINAL\\" + BN);

        //TESTANDO NOVA FORMA DE COPIAR
        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);

        FileInputStream fis = new FileInputStream(origem);
        FileOutputStream fos = new FileOutputStream(destino);

        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();

        long transferFrom = outChannel.transferFrom(inChannel, 0, inChannel.size());

        fis.close();
        fos.close();
        inChannel.close();
        outChannel.close();

        // Thread.sleep(10);
        BN = BN.substring(0, BN.length() - 4);

        PdfContentByte cb = writer.getDirectContent();

        int i = 0;
        while (i < reader.getNumberOfPages()) {
            montaraAquivo(caminhodestino).newPage();

            i++;

            //PDFCONTETBYTE GERA UMA ESPECIE DE CODIGO DE BARRAS 
            PdfContentByte under = writer.getDirectContentUnder();
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 0, i * 0.2f);

            //CARIMBO DA BN
            BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            cb.beginText();
            cb.setFontAndSize(bf, 14);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
            cb.endText();

        }

        montaraAquivo(caminhodestino).close();
        writer.close();
        reader.close();
        origem.delete();

    } catch (IOException | DocumentException ex) {
    }

}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Applies a text watermark (current date, user name, etc, depending on
 * options)/*from   ww  w  . ja v  a2s. com*/
 * 
 * @param reader
 * @param writer
 * @param options
 */
private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader,
        Map<String, Object> options) {

    PdfStamper stamp = null;
    File tempDir = null;
    ContentWriter writer = null;
    String watermarkText;
    StringTokenizer st;
    Vector<String> tokens = new Vector<String>();

    try {
        // get a temp file to stash the watermarked PDF in before moving to
        // repo
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        // get the PDF input stream and create a reader for iText
        PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream());
        stamp = new PdfStamper(reader, new FileOutputStream(file));
        PdfContentByte pcb;

        // get the PDF pages and position
        String pages = (String) options.get(PARAM_PAGE);
        String position = (String) options.get(PARAM_POSITION);
        String depth = (String) options.get(PARAM_WATERMARK_DEPTH);

        // create the base font for the text stamp
        BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250,
                BaseFont.EMBEDDED);

        // get watermark text and process template with model
        String templateText = (String) options.get(PARAM_WATERMARK_TEXT);
        Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef);
        StringWriter watermarkWriter = new StringWriter();
        freemarkerProcessor.processString(templateText, model, watermarkWriter);
        watermarkText = watermarkWriter.getBuffer().toString();

        // tokenize watermark text to support multiple lines and copy tokens
        // to vector for re-use
        st = new StringTokenizer(watermarkText, "\r\n", false);
        while (st.hasMoreTokens()) {
            tokens.add(st.nextToken());
        }

        // stamp each page
        int numpages = reader.getNumberOfPages();
        for (int i = 1; i <= numpages; i++) {
            Rectangle r = reader.getPageSizeWithRotation(i);

            // if this is an under-text stamp, use getUnderContent.
            // if this is an over-text stamp, use getOverContent.
            if (depth.equals(DEPTH_OVER)) {
                pcb = stamp.getOverContent(i);
            } else {
                pcb = stamp.getUnderContent(i);
            }

            // set the font and size
            float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE));
            pcb.setFontAndSize(bf, size);

            // only apply stamp to requested pages
            if (checkPage(pages, i, numpages)) {
                writeAlignedText(pcb, r, tokens, size, position);
            }
        }

        stamp.close();

        // Get a writer and prep it for putting it back into the repo
        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);

        // Put it in the repo
        writer.putContent(file);

        // delete the temp file
        file.delete();
    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }

        if (stamp != null) {
            try {
                stamp.close();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

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

License:Open Source License

/**
 * @param args//from ww w  . ja  va2s.  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:windows.wzListWindow.java

public PdfPCell createCell(String content, int alignment) throws IOException, DocumentException {
    BaseFont ft = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
    Font ffont = new Font(ft, 9);
    Phrase ph = new Phrase(content);
    ph.setFont(ffont);//www  . j av  a 2  s  . c om
    PdfPCell cell = new PdfPCell(Phrase.getInstance(Element.ALIGN_CENTER, content, ffont));
    cell.setHorizontalAlignment(alignment);
    return cell;
}