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

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

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfContentByte saveState.

Prototype

public void saveState() 

Source Link

Document

Saves the graphic state.

Usage

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ??//from  w ww . ja  v a  2  s  .c om
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

    if (waterMarkText == null && waterMarkImage == null)
        throw new FileNotFoundException(waterMarkText + " " + waterMarkImage + " all null.");

    if (srcPdf == null || !srcPdf.exists() || !srcPdf.isFile())
        throw new FileNotFoundException("pdf file :  '" + srcPdf + "' does not exsit.");

    if (!FilenameUtils.getExtension(srcPdf.getAbsolutePath()).toLowerCase().equals("pdf"))
        return;

    if (waterMarkImage != null) {
        if (!waterMarkImage.exists() || !waterMarkImage.isFile())
            throw new FileNotFoundException("img file :  '" + srcPdf + "' does not exsit.");

        if (!FilenameUtils.getExtension(waterMarkImage.getAbsolutePath()).toLowerCase().equals("png"))
            throw new FileNotFoundException("image file '" + srcPdf
                    + "'  not png.(???? pdf )");
    }

    PdfReader reader = getPdfReader(srcPdf);

    int n = reader.getNumberOfPages();
    PdfStamper stamper = getPdfStamper(srcPdf, destPdf);

    //
    //        HashMap<String, String> moreInfo = new HashMap<String, String>();
    //        moreInfo.put("Author", "H819 create");
    //        moreInfo.put("Producer", "H819 Producer");
    //        Key = CreationDate, Value = D:20070425182920
    //        Key = Producer, Value = TH-OCR 2000 (C++/Win32)
    //        Key = Author, Value = TH-OCR 2000
    //        Key = Creator, Value = TH-OCR PDF Writer

    // stamp.setMoreInfo(moreInfo);

    // text
    Phrase text = null;
    if (waterMarkText != null) {
        //
        Font bfont = getPdfFont();
        bfont.setSize(35);
        bfont.setColor(new BaseColor(192, 192, 192));
        text = new Phrase(waterMarkText, bfont);
    }
    // image watermark
    Image img = null;
    float w = 0;
    float h = 0;
    if (waterMarkImage != null) {
        img = Image.getInstance(waterMarkImage.getAbsolutePath());
        w = img.getScaledWidth();
        h = img.getScaledHeight();
        //  img.
        img.setRotationDegrees(45);

    }

    // transparency
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.5f);
    // properties
    PdfContentByte over;
    Rectangle pageSize;
    float x, y;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageSize = reader.getPageSizeWithRotation(i);
        x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        //  pdf pdf ???
        over = stamper.getOverContent(i);
        // ?
        // over = stamp.getUnderContent(i);
        // ?? over.beginText(); over.endText(); ?
        // ,?,:????
        over.saveState(); //??
        over.setGState(gs1);

        if (waterMarkText != null && waterMarkImage != null) { // 
            if (i % 2 == 1) {
                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            } else
                over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        } else if (waterMarkText != null) { //?

            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            //?? ,?, :?????
            // ...

        } else { //?
            over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        }

        over.restoreState();//???
    }

    stamper.close();
    reader.close();

}

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

License:Open Source License

private void addPageFooterInfo(PdfWriter writer, Document document) {
    PdfContentByte contentByte = writer.getDirectContent();
    contentByte.saveState();

    contentByte.setFontAndSize(baseFont, FOOTER_TEXT_SIZE);

    contentByte.beginText();//w  w  w.  j  a  v  a 2  s .  c om
    writeCurrentDate(document, contentByte);
    writePageNumber(writer, document, contentByte);
    contentByte.endText();

    contentByte.restoreState();
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the text of the given page to the current PDF page
 * @param writer/*  w ww  .j  av a2 s. c  o  m*/
 * @param page
 */
private void addText(PdfWriter writer, Page page) {

    if (textLevel == null)
        return;

    int pageHeight = page.getLayout().getHeight();

    try {
        PdfContentByte cb = writer.getDirectContentUnder();
        cb.saveState();
        for (ContentIterator it = page.getLayout().iterator(textLevel); it.hasNext();) {
            ContentObject obj = it.next();
            if (obj == null || !(obj instanceof TextObject))
                continue;
            TextObject textObj = (TextObject) obj;

            if (textObj.getText() != null && !textObj.getText().isEmpty()) {

                List<String> strings = new ArrayList<String>();
                List<Rect> boxes = new ArrayList<Rect>();

                float fontSize = 1.0f;

                //Collect
                if (textObj instanceof LowLevelTextObject) {
                    strings.add(textObj.getText());
                    Rect boundingBox = obj.getCoords().getBoundingBox();
                    boxes.add(boundingBox);
                    fontSize = calculateFontSize(textObj.getText(), boundingBox.getWidth(),
                            boundingBox.getHeight());
                } else {
                    fontSize = splitTextRegion((TextRegion) obj, strings, boxes);
                }

                //Render
                for (int i = 0; i < strings.size(); i++) {
                    String text = strings.get(i);
                    Rect boundingBox = boxes.get(i);

                    //Calculate vertical transition (text is rendered at baseline -> descending bits are below the chosen position)
                    int descent = (int) font.getDescentPoint(text, fontSize);
                    int ascent = (int) font.getAscentPoint(text, fontSize);
                    int textHeight = Math.abs(descent) + ascent;
                    int transY = descent;

                    if (textHeight < boundingBox.getHeight()) {
                        transY = descent - (boundingBox.getHeight() - textHeight) / 2;
                    }

                    cb.beginText();
                    //cb.moveText(boundingBox.left, pageHeight - boundingBox.bottom);
                    cb.setTextMatrix(boundingBox.left, pageHeight - boundingBox.bottom - transY);
                    cb.setFontAndSize(font, fontSize);
                    cb.showText(text);
                    cb.endText();

                    //Debug
                    //cb.moveTo(boundingBox.left, pageHeight - boundingBox.bottom - transY);
                    //cb.lineTo(boundingBox.right, pageHeight - boundingBox.bottom - transY);
                    //cb.moveTo(boundingBox.left, pageHeight - boundingBox.bottom);
                    //cb.lineTo(boundingBox.right, pageHeight - boundingBox.bottom);
                }
            }
        }
        cb.restoreState();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the specified outlines of the given page to the current PDF page. 
 * @param writer/*from  ww w.  j  a v  a2 s  . c  o  m*/
 * @param page
 * @param type
 */
private void addOutlines(PdfWriter writer, Page page, ContentType type) {
    int pageHeight = page.getLayout().getHeight();

    try {
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        for (ContentIterator it = page.getLayout().iterator(type); it.hasNext();) {
            ContentObject contentObj = it.next();
            drawLayoutObject(contentObj, cb, pageHeight);
        }
        cb.restoreState();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the document page image to the current PDF page (spanning the whole page). 
 *///from  w w  w . ja  v  a  2  s  .  co m
private void addImage(String filepath, PdfWriter writer, Document doc, Page page)
        throws MalformedURLException, IOException, DocumentException {

    PdfContentByte cb = writer.getDirectContentUnder();
    cb.saveState();

    Image img = Image.getInstance(filepath);
    img.setAbsolutePosition(0f, 0f);
    //if (img.getScaledWidth() > 300 || img.getScaledHeight() > 300) {
    //img.scaleToFit(300, 300);
    //}
    img.scaleToFit(page.getLayout().getWidth(), page.getLayout().getHeight());

    cb.addImage(img);

    cb.restoreState();

}

From source file:org.saiku.web.export.PdfReport.java

License:Apache License

public byte[] pdf(QueryResult qr, String svg) throws Exception {

    int resultWidth = qr != null && qr.getCellset() != null && qr.getCellset().size() > 0
            ? qr.getCellset().get(0).length
            : 0;/*from www  .  jav a  2s .  c  o  m*/
    if (resultWidth == 0) {
        throw new SaikuServiceException("Cannot convert empty result to PDF");
    }
    Rectangle size = PageSize.A4.rotate();
    if (resultWidth > 8) {
        size = PageSize.A3.rotate();
    }
    if (resultWidth > 16) {
        size = PageSize.A2.rotate();
    }
    if (resultWidth > 32) {
        size = PageSize.A1.rotate();
    }
    if (resultWidth > 64) {
        size = PageSize.A0.rotate();
    }

    Document document = new Document(size, 15, 15, 10, 10);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    populatePdf(document, writer, qr);

    // do we want to add a svg image?
    if (StringUtils.isNotBlank(svg)) {
        document.newPage();
        StringBuffer s1 = new StringBuffer(svg);
        if (!svg.startsWith("<svg xmlns=\"http://www.w3.org/2000/svg\" ")) {
            s1.insert(s1.indexOf("<svg") + 4, " xmlns='http://www.w3.org/2000/svg'");
        }

        String t = "<?xml version='1.0' encoding='ISO-8859-1'" + " standalone='no'?>" + s1.toString();
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        cb.concatCTM(1.0f, 0, 0, 1.0f, 36, 0);
        float width = document.getPageSize().getWidth() - 20;
        float height = document.getPageSize().getHeight() - 20;
        Graphics2D g2 = cb.createGraphics(width, height);
        //g2.rotate(Math.toRadians(-90), 100, 100);
        PrintTranscoder prm = new PrintTranscoder();
        TranscoderInput ti = new TranscoderInput(new StringReader(t));
        prm.transcode(ti, null);
        PageFormat pg = new PageFormat();
        Paper pp = new Paper();
        pp.setSize(width, height);
        pp.setImageableArea(5, 5, width, height);
        pg.setPaper(pp);
        prm.print(g2, pg, 0);
        g2.dispose();
        cb.restoreState();
    }

    document.close();
    return baos.toByteArray();
}

From source file:org.yale.cs.graphics.gephi.imagepreview.ImageNodes.java

License:Open Source License

public void renderImagePDF(ImageItem item, PDFTarget target, PreviewProperties properties, File directory) {

    Image image = item.renderPDF(directory);

    if (image == null) {
        logger.log(Level.WARNING, "Unable to load image: {0}", item.getSource());
        return;//from   ww  w .  j ava 2  s  .  c om
    }

    Float x = item.getData(NodeItem.X);
    Float y = item.getData(NodeItem.Y);
    Float size = item.getData(NodeItem.SIZE);

    float alpha = properties.getFloatValue(IMAGE_OPACITY) / 100f;

    PdfContentByte cb = target.getContentByte();

    if (alpha < 1f) {
        cb.saveState();
        PdfGState gState = new PdfGState();
        gState.setFillOpacity(alpha);
        gState.setStrokeOpacity(alpha);
        cb.setGState(gState);
    }

    image.setAbsolutePosition(x - size / 2, -y - size / 2);
    image.scaleToFit(size, size);
    try {
        cb.addImage(image);
    } catch (DocumentException ex) {
        logger.log(Level.SEVERE, "Unable to add image to document: " + item.getSource(), ex);
    }

    if (alpha < 1f) {
        cb.restoreState();
    }
}

From source file:PDF.CrearPDF_Ficha.java

public static void drawRectangle(PdfContentByte content, float x, float y, float width, float height) {
    try {//from   w w  w. j a va2s .  c  o  m

        content.saveState();

        PdfGState state = new PdfGState();
        content.setGState(state);
        content.setRGBColorFill(232, 232, 232);
        content.setColorStroke(BaseColor.BLUE);
        content.setLineWidth((float) .5);
        content.rectangle(x, y, width, height);
        content.fillStroke();
        content.restoreState();

        BaseFont bf = BaseFont.createFont();
        float fontSize = 15f;
        Phrase phrase = new Phrase("Foto", new Font(bf, fontSize));
        ColumnText.showTextAligned(content, Element.ALIGN_CENTER, phrase, 475, 687, 0);
    } catch (DocumentException ex) {
        Logger.getLogger(CrearPDF_Ficha.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CrearPDF_Ficha.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Report.ItextReport.java

public static void absText(PdfWriter writer, String text, int x, int y) {
    try {/*from  w  w w  .j  a  v  a2  s  .  c  om*/
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.saveState();
        cb.beginText();
        cb.moveText(x, y);
        cb.setFontAndSize(bf, 12);
        cb.showText(text);
        cb.endText();
        cb.restoreState();
    } catch (DocumentException | IOException e) {
        e.getMessage();
    }
}

From source file:ryerson.daspub.artifact.PublishQRTagSheetTask.java

License:Open Source License

/**
 * Draw a text label on the current page.
 * @param Writer PDF writer//from w ww .  ja va  2  s .c  o  m
 * @param Text
 * @param x
 * @param y
 * @param alignment
 * @throws DocumentException
 * @throws IOException 
 */
private void drawLabel(PdfWriter Writer, String Text, int x, int y, int alignment)
        throws DocumentException, IOException {
    PdfContentByte cb = Writer.getDirectContent();
    BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.saveState();
    cb.beginText();
    cb.setFontAndSize(bf, 9);
    cb.showTextAligned(alignment, Text, x, y, 0);
    cb.endText();
    cb.restoreState();
}