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:fr.opensagres.odfdom.converter.pdf.internal.stylable.StylableTab.java

License:Open Source License

public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
    if (font.getBaseFont() != null && font.getSize() > 0.0 && leaderText.trim().length() > 0) {
        // create text to fit tab width
        float width = urx - llx;
        String txt = "";
        while (true) {
            Chunk tmp = new Chunk(txt + leaderText, font);
            if (tmp.getWidthPoint() <= width) {
                txt += leaderText;//  w ww.j ava2  s  . c  om
            } else {
                break;
            }
        }
        // compute x offset - as if tab were right aligned
        float xoffset = width - new Chunk(txt, font).getWidthPoint();
        // compute y offset - use StylableParagraph mechanism
        Chunk tmp = StylableParagraph.createAdjustedChunk(txt, font, lineHeight, lineHeightProportional);
        float yoffset = tmp.getTextRise();
        // draw
        canvas.saveState();
        canvas.beginText();
        canvas.setFontAndSize(font.getBaseFont(), font.getSize());
        canvas.showTextAligned(Element.ALIGN_LEFT, txt, llx + xoffset, y + yoffset, 0.0f);
        canvas.endText();
        canvas.restoreState();
    }
}

From source file:gov.anl.aps.cdb.portal.plugins.support.icmsLink.IcmsWatermarkUtility.java

License:Open Source License

/**
 * Adds a stamp of some metadata to ICMS documents.
 *
 * Function Credit: Thomas Fors//ww w  .j  a  va  2 s .  c o m
 *     
 * @return byte array ologgerf the stamped PDF file
 * @throws DocumentException - Error loading pdfstamper or creating font
 * @throws IOException - Error performing IO operation 
 * @throws Base64DecodingException - Error converting downloadContent string to byte[]
 */
private byte[] addWatermarkToPDFFile() throws Base64DecodingException, DocumentException, IOException {
    byte[] pdfBytes = Base64.decode(downloadContentBase64Encoded);

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yy hh:mm:ss a");
    LocalDateTime now = LocalDateTime.now();
    String downloadTime = dtf.format(now);

    UserInfo user = (UserInfo) SessionUtility.getUser();
    String username = null;
    if (user != null) {
        username = user.getUsername();
    } else {
        username = "unknown user";
    }
    String bottomMessage = "Downloaded via APS CDB by: " + username + " at " + downloadTime;

    controlledRev = updateOptionalValue(controlledRev);
    dnsCollectionId = updateOptionalValue(dnsCollectionId);
    dnsDocNumber = updateOptionalValue(dnsDocNumber);

    String watermarkContents = "Content ID: " + docName;
    watermarkContents += "      Rev: " + controlledRev;
    watermarkContents += "      Released: " + date;
    watermarkContents += "      DNS Collection ID: " + dnsCollectionId;
    watermarkContents += "      DNS Document ID: " + dnsDocNumber;

    PdfReader pdfReader = new PdfReader(pdfBytes);
    int n = pdfReader.getNumberOfPages();

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PdfStamper stamp = new PdfStamper(pdfReader, out);

    PdfContentByte over;
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    for (int i = 0; i < n; i++) {
        over = stamp.getOverContent(i + 1);
        over.beginText();
        over.setTextMatrix(30, 30);
        over.setFontAndSize(bf, 10);
        over.setColorFill(new Color(0x80, 0x80, 0x80));
        over.showTextAligned(Element.ALIGN_LEFT, watermarkContents, 25, 25, 90);
        over.showTextAligned(Element.ALIGN_LEFT, bottomMessage, 50, 10, 0);
        if (status.equals(ICMS_UNDER_REV_STATUS)) {
            over.setColorFill(new Color(0xFF, 0x00, 0x00));
        }
        //over.showTextAligned(Element.ALIGN_LEFT, status, 25, 25 + bf.getWidthPoint(watermarkContents + " - ", 10), 90);

        over.endText();
    }
    stamp.close();

    return out.toByteArray();
}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public void createHeaderDate(Document document, PdfWriter writer, String dateString) throws DocumentException {
    /*//from w  ww  .jav  a 2  s .co  m
     * final PdfPTable header = new PdfPTable(new float[]{1}); header.setWidthPercentage(100f); final PdfPCell defaultCell = header.getDefaultCell();
     * defaultCell.setBorder(0); //defaultCell.setFixedHeight(getPointsFromMM(40)); defaultCell.setPadding(0); defaultCell.setNoWrap(true);
     * defaultCell.setVerticalAlignment(align); header.addCell(new Phrase(new Chunk(dateString, getDefaultParagraphFont()))); document.add(header);
     */
    PdfContentByte cb = writer.getDirectContent();
    cb.beginText();
    Font font = getDefaultParagraphFont();

    try {
        BaseFont bf = BaseFont.createFont(font.getFamilyname(), BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, font.size());
        // we show some text starting on some absolute position with a given
        // alignment
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, dateString, getPointsFromMM(210 - 20),
                getPointsFromMM(297 - 20), 0);
        cb.endText();
    }

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

From source file:managedbean.aas.reportController.java

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {//ww  w . ja  va 2 s  .c  o  m
        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 outputstream            
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        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()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

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;//from   w  w w.ja  v  a2s  . c  o m
    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:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java

License:Open Source License

public void buildBook(List<File> inputFileList, File outputFile) {

    try {//  www  .  j  ava 2  s.c  o  m

        float pageWidth = getConfig().getPageWidth();
        float pageHeight = getConfig().getPageHeight();

        // Create new Document

        /*
        float marginLeft = 36;
        float marginRight = 36;
        float marginTop = 36;
        float marginBottom = 36;
        */

        if (isVerboseEnabled()) {
            verbose("Building output PDF file " + outputFile);
        }

        // TableOfContents toc = new TableOfContents();

        ProgressMonitor progressMonitor = getConfig().getProgressMonitor();
        TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener();

        Document outputDocument = new Document(getConfig().getPageSize());
        // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom );

        PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile));

        // TODO - review PDF page event forwarder
        PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger();
        pdfWriter.setPageEvent(pdfPageEventLogger);

        outputDocument.open();

        String metaTitle = getConfig().getMetaTitle();
        if (!StringUtils.isEmpty(metaTitle)) {
            outputDocument.addTitle(metaTitle);
        }
        String metaAuthor = getConfig().getMetaAuthor();
        if (!StringUtils.isEmpty(metaAuthor)) {
            outputDocument.addAuthor(metaAuthor);
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        // Loop through and pull pages
        int outputPageCount = 0;
        int currentSourceFileIndex = 0;
        int maxSourceFileIndex = inputFileList.size();

        // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED );
        BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250,
                BaseFont.EMBEDDED);
        if (isVerboseEnabled()) {
            verbose("Using page label font " + pageLabelFont);
        }

        if (isVerboseEnabled()) {
            verbose("Assembling pages using n-up " + getConfig().getNup());
        }

        for (File sourceFile : inputFileList) {

            currentSourceFileIndex++;

            // TODO - refactor current file PDF page processing to another method
            // TODO - handle failover to ensure processing continues ???

            if (sourceFile.isFile()) {

                if (isVerboseEnabled()) {
                    verbose("Reading source PDF file " + sourceFile);
                }

                int sourcePageIndex = 0;

                PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath());
                PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader);
                if (isVerboseEnabled()) {
                    verbose("PDF reader is " + sourcePdfReader);
                    verbose("PDF reader helper is " + sourcePdfReaderHelper);
                }

                String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName());
                String currentSourcePdfAuthor = getSystemUserName();
                if (isVerboseEnabled()) {
                    verbose("PDF title is " + currentSourcePdfTitle);
                    verbose("PDF author is " + currentSourcePdfAuthor);
                }

                currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle);
                currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor);
                if (isVerboseEnabled()) {
                    verbose("PDF info title is " + currentSourcePdfTitle);
                    verbose("PDF info author is " + currentSourcePdfAuthor);
                }

                boolean firstPageOfCurrentSource = true;

                int maxSourcePages = sourcePdfReader.getNumberOfPages();
                if (isVerboseEnabled()) {
                    verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile);
                }

                // process all pages from source doc
                while (sourcePageIndex < maxSourcePages) {

                    // add new page to current document
                    outputDocument.newPage();

                    outputPageCount++;
                    if (isVerboseEnabled()) {
                        verbose("Building output PDF page " + outputPageCount + " ...");
                    }

                    // add first page of current source to TOC listener
                    if (firstPageOfCurrentSource) {
                        int currentPageIndex = outputPageCount;
                        if (tocRowChangeListener != null) {
                            TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex);
                            tocRowChangeListener.addTocRow(tocEntry);
                            if (isVerboseEnabled()) {
                                verbose("Added TOC entry " + tocEntry + " to listener");
                            }
                        }
                        firstPageOfCurrentSource = false;
                    }

                    // extract first page from source document
                    sourcePageIndex++;
                    if (isVerboseEnabled()) {
                        verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                + " from source to output");
                    }
                    PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);

                    // n-up is 1
                    if (config.getNup() == 1) {
                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        // TODO - calculate scaling/transform based on page rect and template rect
                        float p1a = 0.65f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.65f;
                        float p1e = 20;
                        float p1f = 160;
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // n-up is 2 (default)
                    } else {

                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        float p1a = 0.5f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.5f;
                        float p1e = (125);
                        float p1f = ((pageWidth / 2) + 120 + 20);
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // extract second page from source document ?
                        PdfImportedPage page2 = null;
                        if (sourcePageIndex < maxSourcePages) {
                            sourcePageIndex++;
                            if (isVerboseEnabled()) {
                                verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                        + " from source to output");
                            }
                            page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);
                        }

                        // add second page to bottom half of current page
                        if (page2 != null) {
                            // TODO - review magic transformation matrix numbers and offsets
                            float p2a = 0.5f;
                            float p2b = 0;
                            float p2c = 0;
                            float p2d = 0.5f;
                            float p2e = 125;
                            float p2f = 120;
                            pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f);
                        }
                    }

                    /*
                    // add first page to top half of current page
                    // TODO - review magic transformation matrix numbers and offsets
                    float p1a = 0.5f;
                    float p1b = 0;
                    float p1c = 0;
                    float p1d = 0.5f;
                    float p1e = (125);
                    float p1f = ((pageWidth / 2) + 120 + 20);
                    pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f );
                            
                    // add second page to bottom half of current page
                    if (page2 != null) {
                       // TODO - review magic transformation matrix numbers and offsets
                       float p2a = 0.5f; 
                       float p2b = 0;
                       float p2c = 0;
                       float p2d = 0.5f;
                       float p2e = 125;
                       float p2f = 120;
                       pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f );
                    }
                    */

                    // Add current page number to page footer
                    String pageCountLabel = "Page " + outputPageCount;
                    pdfContent.beginText();
                    pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE);
                    pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40,
                            0);
                    pdfContent.endText();
                }

                if (isVerboseEnabled()) {
                    verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file "
                            + sourceFile);
                }

                // update progress
                if (isVerboseEnabled()) {
                    if (progressMonitor != null) {
                        int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex,
                                maxSourceFileIndex);
                        progressMonitor.setProgressPercentage(fileProgressPercentage);
                    }
                }
            }
        }

        // close document
        outputDocument.close();

        if (isVerboseEnabled()) {
            verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)");
        }

        // TODO - output ODT page stats summary

    } catch (Exception e) {

        String msg = "Error building PDF book: " + e.getMessage();
        e.printStackTrace(System.err);
        System.err.println(msg);

    }

}

From source file:net.sf.jasperreports.engine.export.PdfGlyphGraphics2D.java

License:Open Source License

@Override
public void drawGlyphVector(GlyphVector glyphVector, float x, float y) {
    Font awtFont = glyphVector.getFont();
    Map<Attribute, Object> fontAttrs = new HashMap<Attribute, Object>();
    Map<TextAttribute, ?> awtFontAttributes = awtFont.getAttributes();
    fontAttrs.putAll(awtFontAttributes);

    //the following relies on FontInfo.getFontInfo matching the face/font name
    com.lowagie.text.Font currentFont = pdfExporter.getFont(fontAttrs, locale, false);
    boolean bold = (currentFont.getStyle() & com.lowagie.text.Font.BOLD) != 0;
    boolean italic = (currentFont.getStyle() & com.lowagie.text.Font.ITALIC) != 0;

    PdfContentByte text = pdfContentByte.getDuplicate();
    text.beginText();//from   www  .  j  av  a 2  s .  c  o  m

    float[] originalCoords = new float[] { x, y };
    float[] transformedCoors = new float[2];
    getTransform().transform(originalCoords, 0, transformedCoors, 0, 1);
    text.setTextMatrix(1, 0, italic ? ITALIC_ANGLE : 0f, 1, transformedCoors[0],
            pdfExporter.getCurrentPageFormat().getPageHeight() - transformedCoors[1]);

    double scaleX = awtFont.getTransform().getScaleX();
    double scaleY = awtFont.getTransform().getScaleY();
    double minScale = Math.min(scaleX, scaleY);
    text.setFontAndSize(currentFont.getBaseFont(), (float) (minScale * awtFont.getSize2D()));

    if (bold) {
        text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
        text.setLineWidth(currentFont.getSize() * BOLD_STRIKE_FACTOR);
        text.setColorStroke(getColor());
    }

    text.setColorFill(getColor());
    //FIXME find a way to determine the characters that correspond to this glyph vector
    // so that we can map the font glyphs that do not directly map to a character
    text.showText(glyphVector);
    text.resetRGBColorFill();

    if (bold) {
        text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        text.setLineWidth(1f);
        text.resetRGBColorStroke();
    }

    text.endText();
    pdfContentByte.add(text);
}

From source file:org.caisi.tickler.web.TicklerPrinter.java

License:Open Source License

public void footer() {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();//w w w  .  j a  va2  s. c  o m

    Date now = new Date();
    String promoTxt = OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT");
    if (promoTxt == null) {
        promoTxt = new String();
    }

    String strFooter = promoTxt + " " + formatter.format(now);

    float textBase = document.bottom();
    cb.beginText();
    cb.setFontAndSize(font.getBaseFont(), FONTSIZE);
    Rectangle page = document.getPageSize();
    float width = page.getWidth();

    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 20, 0);

    strFooter = "-" + writer.getPageNumber() + "-";
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 10, 0);

    cb.endText();
    cb.restoreState();
}

From source file:org.eclipse.birt.report.engine.layout.pdf.font.FontCacheUtils.java

License:Open Source License

static void createUnicodePDF(String format, Locale locale, String fileName) throws Exception {
    FontMappingManager manager = FontMappingManagerFactory.getInstance().getFontMappingManager(format, locale);

    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();/*ww  w  .  j a  va  2s  . c om*/
    for (int seg = 0; seg < 0xFF; seg++) {
        PdfContentByte cb = writer.getDirectContent();
        cb.beginText();
        for (int hi = 0; hi < 16; hi++) {
            for (int lo = 0; lo < 16; lo++) {
                int x = 100 + hi * 32;
                int y = 100 + lo * 32;
                char ch = (char) (seg * 0xFF + hi * 16 + lo);

                String fontFamily = manager.getDefaultPhysicalFont(ch);
                BaseFont bf = manager.createFont(fontFamily, Font.NORMAL);
                cb.setFontAndSize(bf, 16);
                cb.setTextMatrix(x, y);
                cb.showText(new String(new char[] { ch }));
            }
        }
        cb.endText();
    }
    document.close();
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void stampText(int pageCount, PdfPageData currentPageData, final StampTextToPDFPages stampText) {
    File tempFile = null;/*from w  w w .  j  av a2s.  co  m*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = stampText.getPages();

        if (pgsToEdit == null)
            return;

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                String chosenText = stampText.getText();

                if (!chosenText.equals("")) {

                    String chosenFont = stampText.getFontName();
                    Color chosenFontColor = stampText.getFontColor();
                    int chosenFontSize = stampText.getFontSize();

                    int chosenRotation = stampText.getRotation();
                    String chosenPlacement = stampText.getPlacement();

                    String chosenHorizontalPosition = stampText.getHorizontalPosition();
                    String chosenVerticalPosition = stampText.getVerticalPosition();

                    float chosenHorizontalOffset = stampText.getHorizontalOffset();
                    float chosenVerticalOffset = stampText.getVerticalOffset();

                    BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false);

                    PdfContentByte cb;
                    if (chosenPlacement.equals("Overlay"))
                        cb = stamp.getOverContent(page);
                    else
                        cb = stamp.getUnderContent(page);

                    cb.beginText();
                    cb.setColorFill(chosenFontColor);
                    cb.setFontAndSize(font, chosenFontSize);

                    int currentRotation = currentPageData.getRotation(page);
                    Rectangle pageSize;
                    if (currentRotation == 90 || currentRotation == 270)
                        pageSize = reader.getPageSize(page).rotate();
                    else
                        pageSize = reader.getPageSize(page);

                    float startx;
                    float starty;

                    if (chosenVerticalPosition.equals("From the top")) {
                        starty = pageSize.height();
                    } else if (chosenVerticalPosition.equals("Centered")) {
                        starty = pageSize.height() / 2;
                    } else {
                        starty = 0;
                    }

                    if (chosenHorizontalPosition.equals("From the left")) {
                        startx = 0;
                    } else if (chosenHorizontalPosition.equals("Centered")) {
                        startx = pageSize.width() / 2;
                    } else {
                        startx = pageSize.width();
                    }

                    cb.showTextAligned(Element.ALIGN_CENTER, chosenText, startx + chosenHorizontalOffset,
                            starty + chosenVerticalOffset, chosenRotation);
                    cb.endText();
                }
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}