Example usage for com.itextpdf.text Rectangle getHeight

List of usage examples for com.itextpdf.text Rectangle getHeight

Introduction

In this page you can find the example usage for com.itextpdf.text Rectangle getHeight.

Prototype

public float getHeight() 

Source Link

Document

Returns the height of the rectangle.

Usage

From source file:com.qmetric.document.watermark.strategy.MessageWatermarkStrategy.java

License:Open Source License

private float yAxisPosition(final Rectangle pageSize) {
    return pageSize.getHeight() / 8;
}

From source file:com.swayam.bhasha.engine.io.writers.impl.PDFGenerator.java

License:Apache License

private void makePDFPage(HTMLDocModel htmlDoc, String fileName) throws DocGenerationException {

    Rectangle pageSize = PageSize.A4;

    if (pageDim.height > pageSize.getHeight()) {
        pageSize = new Rectangle(pageDim.width, pageDim.height);
    }//w ww . j  ava  2 s .  c om

    Document pdfDoc = new Document(pageSize, MARGINS, MARGINS, MARGINS, MARGINS);

    FileOutputStream pdfStream = null;

    try {
        pdfStream = new FileOutputStream(fileName);

        PdfWriter.getInstance(pdfDoc, pdfStream);

        pdfDoc.addAuthor("Bhasha PDF Generator (Powered by IText)");

        pdfDoc.open();

        List<Para> paraList = htmlDoc.getParaList();

        for (Para para : paraList) {
            pdfDoc.add(getParagraph(para));
        }

        pdfDoc.close();

    } catch (Exception e) {
        throw new DocGenerationException(e);
    } finally {

        if (pdfStream != null) {
            try {
                pdfStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

From source file:com.swayam.bhasha.engine.io.writers.impl.PDFImageGenerator.java

License:Apache License

private void makePDFPage(HTMLDocModel htmlDoc, String fileName) throws DocGenerationException, IOException {

    BufferedImage image = getImage(pageDim, htmlDoc);

    /*/*ww w  . j  av a  2s. c o m*/
     * ByteArrayOutputStream bos = new ByteArrayOutputStream();
     * 
     * ImageIO.write(image, "JPG", bos);
     * 
     * byte[] imageData = bos.toByteArray();
     * 
     * System.out.println("PDFImageGenerator.makePDFPage() " +
     * imageData.length);
     */

    Rectangle pageSize = PageSize.A4;

    if (image.getHeight() > pageSize.getHeight()) {
        pageSize = new Rectangle(image.getWidth(), image.getHeight());
    }

    Document pdfDoc = new Document(pageSize, MARGINS, MARGINS, MARGINS, MARGINS);

    FileOutputStream pdfStream = null;

    try {
        pdfStream = new FileOutputStream(fileName);

        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfStream);

        pdfDoc.addAuthor("Bhasha PDF Generator (Powered by IText)");

        pdfDoc.open();

        PdfContentByte contentByte = pdfWriter.getDirectContent();

        Image pdfImage = Image.getInstance(image, null);

        pdfImage.setAbsolutePosition(0, 0);
        contentByte.addImage(pdfImage);

    } catch (Exception e) {
        throw new DocGenerationException(e);
    } finally {

        pdfDoc.close();

        if (pdfStream != null) {
            try {
                pdfStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:com.vectorprint.report.itext.debug.DebugHelper.java

License:Open Source License

public static void debugBackground(PdfContentByte canvas, Rectangle rect, BaseColor color, String prefix,
        EnhancedMap settings, LayerManager layerAware) {
    canvas = canvas.getPdfWriter().getDirectContentUnder();
    int rgb = color.getRed() + color.getBlue() + color.getGreen();
    rect.setBackgroundColor(color);/*w w  w . j  av  a  2s .co m*/
    canvas.rectangle(rect);
    layerAware.startLayerInGroup(DEBUG, canvas);
    debugFont(canvas, settings);
    BaseColor txtColor = (rgb < 150) ? color.brighter().brighter() : color.darker().darker();
    canvas.setColorFill(txtColor);
    canvas.setColorStroke(txtColor);
    canvas.beginText();
    canvas.showTextAligned(Element.ALIGN_LEFT, prefix + color.toString().replace(Color.class.getName(), ""),
            rect.getLeft() + rect.getWidth() / 2, rect.getTop() - rect.getHeight() / 2, 0);
    canvas.endText();
    canvas.endLayer();
}

From source file:com.vectorprint.report.itext.EventHelper.java

License:Open Source License

/**
 * Calls the super and {@link Advanced#draw(com.itextpdf.text.Rectangle, java.lang.String) } for each Advanced styler
 * registered. Adds a debugging link for images when in debug mode.
 *
 * @param writer/*ww  w .  j a  va  2  s .  c  o  m*/
 * @param document
 * @param rect
 * @param genericTag
 * @see #addDelayedStyler(java.lang.String, java.util.Collection, com.itextpdf.text.Chunk) 
 * @see Advanced#addDelayedData(java.lang.String, com.itextpdf.text.Chunk)
 * @see VectorPrintDocument
 */
@Override
public final void onGenericTag(PdfWriter writer, Document document, final Rectangle rect, String genericTag) {
    //      if (log.isLoggable(Level.FINE)) {
    //         Collection<Advanced> av = doOnGenericTag.get(genericTag);
    //         String data = null;
    //         if (av!=null) {
    //            for (Advanced a : av) {
    //               data += a.getDelayed(genericTag).getDataPart();
    //               break;
    //            }
    //         }
    //         System.out.println("wrapped: " + carriageReturns.toString() + ", " + genericTag + " " + data + " " + rect.toString() + ", x=" + rect.getLeft());
    //      }
    if (doOnGenericTag.get(genericTag) != null && !genericTag.startsWith(VectorPrintDocument.DRAWNEAR)
            && !genericTag.startsWith(VectorPrintDocument.DRAWSHADOW)) {
        int i = -1;
        for (Advanced a : doOnGenericTag.get(genericTag)) {
            ++i;
            if (genericTag.startsWith(DefaultElementProducer.ADV) && Integer
                    .parseInt(genericTag.replace(DefaultElementProducer.ADV, "")) > maxTagForGenericTagOnPage) {
                continue;
            }
            try {
                if (a.shouldDraw(a.getDelayed(genericTag).getData())) {
                    if (a instanceof DebugStyler && imageChunks.containsKey(genericTag)) {
                        Chunk wrapper = imageChunks.get(genericTag);
                        Object[] atts = (Object[]) wrapper.getAttributes().get(Chunk.IMAGE);
                        Rectangle shifted = new Rectangle(rect);
                        shifted.setLeft(shifted.getLeft() + (Float) atts[1]);
                        shifted.setRight(shifted.getRight() + (Float) atts[1]);
                        shifted.setTop(shifted.getTop() + (Float) atts[2]);
                        shifted.setBottom(shifted.getBottom() + (Float) atts[2]);
                        a.draw(shifted, genericTag);
                    } else if (!genericTag.startsWith(VectorPrintDocument.IMG_DEBUG)) {
                        a.draw(rect, genericTag);
                    }
                }
            } catch (VectorPrintException ex) {
                throw new VectorPrintRuntimeException(ex);
            }
        }
    }
    // images
    if (genericTag.startsWith(VectorPrintDocument.IMG_DEBUG)
            && getSettings().getBooleanProperty(false, DEBUG)) {
        // only now we can define a goto action, we know the position of the image
        if (rectangles.containsKey(genericTag)) {
            Rectangle rectangle = imageRectFromChunk(genericTag, rect);
            DebugHelper.debugAnnotation(rectangle, genericTag.replaceFirst(VectorPrintDocument.IMG_DEBUG, ""),
                    writer);
        } else {
            DebugHelper.debugAnnotation(rect, genericTag.replaceFirst(VectorPrintDocument.IMG_DEBUG, ""),
                    writer);
        }
    }
    if (genericTag.startsWith(VectorPrintDocument.DRAWNEAR)) {
        Rectangle rectangle = imageRectFromChunk(genericTag, rect);
        com.vectorprint.report.itext.style.stylers.Image image = (com.vectorprint.report.itext.style.stylers.Image) doOnGenericTag
                .get(genericTag).iterator().next();
        short i = -1;
        for (Advanced a : doOnGenericTag.get(genericTag)) {
            try {
                if (++i > 0 && a.shouldDraw(a.getDelayed(genericTag).getData())) {
                    if (getSettings().getBooleanProperty(false, DEBUG)) {
                        DebugHelper.styleLink(writer.getDirectContent(), a.getStyleClass(), "draw near",
                                rectangle.getLeft(), rectangle.getTop(), getSettings(), elementProducer);
                    }
                    a.draw(rectangle, genericTag);
                }
            } catch (VectorPrintException ex) {
                throw new VectorPrintRuntimeException(ex);
            }

        }
    }
    if (genericTag.startsWith(VectorPrintDocument.DRAWSHADOW)) {
        // we know the position of the image
        Rectangle r = imageRectFromChunk(genericTag, rect);
        com.vectorprint.report.itext.style.stylers.Image image = (com.vectorprint.report.itext.style.stylers.Image) doOnGenericTag
                .get(genericTag).iterator().next();
        try {
            image.drawShadow(r.getLeft(), r.getBottom(), r.getWidth(), r.getHeight(),
                    genericTag.replaceFirst(VectorPrintDocument.DRAWSHADOW, ""));
        } catch (VectorPrintException ex) {
            throw new VectorPrintRuntimeException(ex);
        }
    }
}

From source file:com.vectorprint.report.itext.style.stylers.AbstractFieldStyler.java

License:Open Source License

@Override
protected void draw(PdfContentByte canvas, float x, float y, float width, float height, String genericTag)
        throws VectorPrintException {
    Rectangle box = new Rectangle(x, y, x + width, y - height);
    PdfFormField pff = null;//w w  w . j  a  v  a 2  s  .co  m
    if (getValue(DocumentSettings.WIDTH, Float.class) > 0) {
        box.setRight(box.getLeft() + getValue(DocumentSettings.WIDTH, Float.class));
    }
    if (getValue(DocumentSettings.HEIGHT, Float.class) > 0) {
        float diff = box.getHeight() - getValue(DocumentSettings.HEIGHT, Float.class);
        box.setBottom(box.getBottom() + diff / 2);
        box.setTop(box.getTop() - diff / 2);
    }
    bf.setBox(box);
    try {
        List<BaseStyler> stylers = stylerFactory.getStylers(getStyleClass());
        List<FormFieldStyler> ffStylers = StyleHelper.getStylers(stylers, FormFieldStyler.class);
        pff = makeField();
        if (FormFieldStyler.FIELDTYPE.BUTTON.equals(getFieldtype())) {
            for (FormFieldStyler f : ffStylers) {
                if (f.isParameterSet(Image.URLPARAM)) {
                    pff.setAction(PdfAction.createSubmitForm(f.getValue(Image.URLPARAM, URL.class).toString(),
                            null, PdfAction.SUBMIT_HTML_FORMAT));
                    break;
                }
            }
        }
    } catch (IOException | DocumentException | VectorPrintException ex) {
        throw new VectorPrintRuntimeException(ex);
    }
    getWriter().addAnnotation(pff);
    if (stylerFactory.getSettings().getBooleanProperty(false, DEBUG)) {
        DebugHelper.debugRect(canvas, box, new float[] { 2, 2 }, 0.7f, stylerFactory.getSettings(),
                elementProducer);
        DebugHelper.styleLink(canvas, getStyleClass(), "", box.getLeft(), box.getTop(),
                stylerFactory.getSettings(), elementProducer);
    }
}

From source file:com.vectorprint.report.itext.style.stylers.AbstractPositioning.java

License:Open Source License

/**
 * Calls {@link #draw(com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, String) } with rect.getLeft()
 * + getShiftx(), rect.getTop() + getShifty(), rect.getWidth(), rect.getHeight(), genericTag. When {@link #isShadow()
 * } is true {@link #isDrawShadow() } will be set to true, prior to calling
 * {@link #draw(com.itextpdf.text.pdf.PdfContentByte, float, float, float, float, java.lang.String) } and to false
 * afterwards./*from   www . j av  a 2  s.co  m*/
 *
 * @param rect
 * @param genericTag passed on to abstract method
 * @throws VectorPrintException
 * @see EventHelper#onGenericTag(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document,
 * com.itextpdf.text.Rectangle, java.lang.String)
 */
@Override
public final void draw(Rectangle rect, String genericTag) throws VectorPrintException {
    if (getValue(SHADOW, Boolean.class)) {
        drawShadow(rect.getLeft() + getShiftx(), rect.getTop() + getShifty(), rect.getWidth(), rect.getHeight(),
                genericTag);
    }
    PdfContentByte canvas = getPreparedCanvas();
    draw(canvas, rect.getLeft() + getShiftx(), rect.getTop() + getShifty(), rect.getWidth(), rect.getHeight(),
            genericTag);
    resetCanvas(canvas);
}

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;//w w w . jav  a  2  s  .  c  o  m

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:de.mat.utils.pdftools.PdfAddPageNum.java

License:Mozilla Public License

/**
 * <h4>FeatureDomain:</h4>//from  w w w  .java 2 s .c  o m
 *     PublishingTools
 * <h4>FeatureDescription:</h4>
 *     adds pagenum with stamper to pages from reader 
 * <h4>FeatureResult:</h4>
 *   <ul>
 *     <li>updates stamper - updates the stamper
 *   </ul> 
 * <h4>FeatureKeywords:</h4>
 *     PDF Publishing
 * @param reader - reader with the pages
 * @param stamper - stamper to add the canvas
 * @param pageOffset - add to pagenumber
 * @throws DocumentException
 * @throws IOException
 */
public void addPageNumber(PdfReader reader, PdfStamper stamper, int pageOffset)
        throws DocumentException, IOException {
    // ierate all pages from reader
    for (int zaehler = 1; zaehler <= reader.getNumberOfPages(); zaehler++) {
        // read pagesize
        Rectangle pageSize = reader.getPageSize(zaehler);
        float xpos = pageSize.getLeft() + pageSize.getWidth() / 2;
        float ypos = 20;
        float fontSize = 7;

        // Default-Positions for --page-width 150mm --page-height 212mm == 601px
        if (pageSize.getHeight() > 602 || pageSize.getHeight() < 598) {
            // correct it relative
            float factor = pageSize.getHeight() / 601;
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(" PageHeight:" + pageSize.getHeight() + " Factor:" + factor);
            ypos = ypos * factor;
            fontSize = fontSize * factor;
        }

        // add pagenumber-canvas
        PdfContentByte canvas = stamper.getOverContent(zaehler);
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        canvas.setFontAndSize(bf_helv, fontSize);
        canvas.beginText();
        canvas.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + new Integer(zaehler + pageOffset - 1), xpos,
                ypos, 0);
        canvas.endText();
    }
}

From source file:de.mat.utils.pdftools.PdfResize.java

License:Mozilla Public License

/**
/**/*  w  w w.jav a  2  s  .  co m*/
 * <h4>FeatureDomain:</h4>
 *     PublishingTools
 * <h4>FeatureDescription:</h4>
 *     scales and move comntents of the pdf pages from fileSrc and output to
 *     fileNew
 * <h4>FeatureResult:</h4>
 *   <ul>
 *     <li>create PDF - fileNew
 *   </ul> 
 * <h4>FeatureKeywords:</h4>
 *     PDF Publishing
 * @param fileSrc - source-pdf
 * @param fileNew - scaled dest-pdf
 * @param factorX - scaling x
 * @param factorY - scaling y
 * @param pixelLeft - move right
 * @param pixelTop - move down
 * @throws Exception
 */
public static void resizePdf(String fileSrc, String fileNew, float factorX, float factorY, float pixelLeft,
        float pixelTop) throws Exception {

    // open reader
    PdfReader reader = new PdfReader(fileSrc);

    // get pagebasedata
    int pageCount = reader.getNumberOfPages();
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getHeight();
    float height = psize.getWidth();

    // open writer
    Document documentNew = new Document(new Rectangle(height * factorY, width * factorX));
    PdfWriter writerNew = PdfWriter.getInstance(documentNew, new FileOutputStream(fileNew));
    documentNew.open();
    PdfContentByte cb = writerNew.getDirectContent();

    // iterate pages
    int i = 0;
    while (i < pageCount) {
        i++;
        // imoport page from reader and scale it to writer
        documentNew.newPage();
        PdfImportedPage page = writerNew.getImportedPage(reader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, pixelLeft, pixelTop);

        if (LOGGER.isInfoEnabled())
            LOGGER.info("AddPage " + i + " from:" + fileSrc + " to:" + fileNew);
    }

    documentNew.close();
    writerNew.close();
}