Example usage for com.lowagie.text.pdf PdfContentByte addTemplate

List of usage examples for com.lowagie.text.pdf PdfContentByte addTemplate

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte addTemplate.

Prototype

public void addTemplate(PdfTemplate template, float x, float y) 

Source Link

Document

Adds a template to this content.

Usage

From source file:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] stamp(byte[] abPdf, String sigla, boolean rascunho, boolean cancelado, boolean semEfeito,
        boolean internoProduzido, String qrCode, String mensagem, Integer paginaInicial, Integer paginaFinal,
        Integer cOmitirNumeracao, String instancia, String orgaoUsu) throws DocumentException, IOException {

    PdfReader pdfIn = new PdfReader(abPdf);
    Document doc = new Document(PageSize.A4, 0, 0, 0, 0);
    // final SimpleDateFormat sdf = new SimpleDateFormat(
    // "EEE MMM dd HH:mm:ss zzz yyyy");
    // doc.add(new Meta("creationdate", sdf.format(new Date(0L))));
    final ByteArrayOutputStream boA4 = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(doc, boA4);
    doc.open();/*from   ww w. ja va 2  s  . c o m*/
    PdfContentByte cb = writer.getDirectContent();

    // Resize every page to A4 size
    //
    // double thetaRotation = 0.0;
    for (int i = 1; i <= pdfIn.getNumberOfPages(); i++) {
        int rot = pdfIn.getPageRotation(i);
        float left = pdfIn.getPageSize(i).getLeft();
        float bottom = pdfIn.getPageSize(i).getBottom();
        float top = pdfIn.getPageSize(i).getTop();
        float right = pdfIn.getPageSize(i).getRight();

        PdfImportedPage page = writer.getImportedPage(pdfIn, i);
        float w = page.getWidth();
        float h = page.getHeight();

        // Logger.getRootLogger().error("----- dimensoes: " + rot + ", " + w
        // + ", " + h);

        doc.setPageSize((rot != 0 && rot != 180) ^ (w > h) ? PageSize.A4.rotate() : PageSize.A4);
        doc.newPage();

        cb.saveState();

        if (rot != 0 && rot != 180) {
            float swap = w;
            w = h;
            h = swap;
        }

        float pw = doc.getPageSize().getWidth();
        float ph = doc.getPageSize().getHeight();
        double scale = Math.min(pw / w, ph / h);

        // do my transformations :
        cb.transform(AffineTransform.getScaleInstance(scale, scale));

        if (!internoProduzido) {
            cb.transform(AffineTransform.getTranslateInstance(pw * SAFETY_MARGIN, ph * SAFETY_MARGIN));
            cb.transform(AffineTransform.getScaleInstance(1.0f - 2 * SAFETY_MARGIN, 1.0f - 2 * SAFETY_MARGIN));
        }

        if (rot != 0) {
            double theta = -rot * (Math.PI / 180);
            if (rot == 180) {
                cb.transform(AffineTransform.getRotateInstance(theta, w / 2, h / 2));
            } else {
                cb.transform(AffineTransform.getRotateInstance(theta, h / 2, w / 2));
            }
            if (rot == 90) {
                cb.transform(AffineTransform.getTranslateInstance((w - h) / 2, (w - h) / 2));
            } else if (rot == 270) {
                cb.transform(AffineTransform.getTranslateInstance((h - w) / 2, (h - w) / 2));
            }
        }

        // Logger.getRootLogger().error(
        // "----- dimensoes: " + rot + ", " + w + ", " + h);
        // Logger.getRootLogger().error("----- page: " + pw + ", " + ph);

        // cb.transform(AffineTransform.getTranslateInstance(
        // ((pw / scale) - w) / 2, ((ph / scale) - h) / 2));

        // put the page
        cb.addTemplate(page, 0, 0);

        // draw a red rectangle at the page borders
        //
        // cb.saveState();
        // cb.setColorStroke(Color.red);
        // cb.rectangle(pdfIn.getPageSize(i).getLeft(), pdfIn.getPageSize(i)
        // .getBottom(), pdfIn.getPageSize(i).getRight(), pdfIn
        // .getPageSize(i).getTop());
        // cb.stroke();
        // cb.restoreState();

        cb.restoreState();
    }
    doc.close();

    abPdf = boA4.toByteArray();

    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();

    final PdfReader reader = new PdfReader(abPdf);

    final int n = reader.getNumberOfPages();
    final PdfStamper stamp = new PdfStamper(reader, bo2);

    // adding content to each page
    int i = 0;
    PdfContentByte under;
    PdfContentByte over;
    final BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    // Image img = Image.getInstance("watermark.jpg");
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    byte maskr[] = { (byte) 0xff };
    Image mask = Image.getInstance(1, 1, 1, 1, maskr);
    mask.makeMask();
    mask.setInverted(true);

    while (i < n) {
        i++;
        // watermark under the existing page
        under = stamp.getUnderContent(i);
        over = stamp.getOverContent(i);

        final Barcode39 code39 = new Barcode39();
        // code39.setCode(doc.getCodigo());
        code39.setCode(sigla.replace("-", "").replace("/", "").replace(".", ""));
        code39.setStartStopText(false);
        final Image image39 = code39.createImageWithBarcode(over, null, null);
        Rectangle r = stamp.getReader().getPageSizeWithRotation(i);

        image39.setInitialRotation((float) Math.PI / 2.0f);
        image39.setAbsolutePosition(
                r.getWidth() - image39.getHeight() + (STAMP_BORDER_IN_CM - PAGE_BORDER_IN_CM) * CM_UNIT,
                BARCODE_HEIGHT_IN_CM * CM_UNIT);

        image39.setBackgroundColor(Color.green);
        image39.setBorderColor(Color.RED);
        image39.setBorderWidth(0.5f * CM_UNIT);

        image39.setImageMask(mask);

        over.setRGBColorFill(255, 255, 255);
        mask.setAbsolutePosition(r.getWidth() - image39.getHeight() - (PAGE_BORDER_IN_CM) * CM_UNIT,
                (BARCODE_HEIGHT_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
        mask.scaleAbsolute(image39.getHeight() + 2 * STAMP_BORDER_IN_CM * CM_UNIT,
                image39.getWidth() + 2 * STAMP_BORDER_IN_CM * CM_UNIT);
        over.addImage(mask);

        over.setRGBColorFill(0, 0, 0);
        over.addImage(image39);

        // over.addImage(mask, mask.getScaledWidth() * 8, 0, 0,
        // mask.getScaledHeight() * 8, 100, 450);

        if (qrCode != null) {
            java.awt.Image imgQRCode = createQRCodeImage(qrCode);
            Image imageQRCode = Image.getInstance(imgQRCode, Color.BLACK, true);
            imageQRCode.scaleAbsolute(QRCODE_SIZE_IN_CM * CM_UNIT, QRCODE_SIZE_IN_CM * CM_UNIT);
            imageQRCode.setAbsolutePosition(QRCODE_LEFT_MARGIN_IN_CM * CM_UNIT, PAGE_BORDER_IN_CM * CM_UNIT);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition((QRCODE_LEFT_MARGIN_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute((QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    (QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT);
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            over.addImage(imageQRCode);
        }

        if (mensagem != null) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(r.getWidth() - image39.getHeight() - (QRCODE_LEFT_MARGIN_IN_CM
                    + QRCODE_SIZE_IN_CM + 4 * STAMP_BORDER_IN_CM + PAGE_BORDER_IN_CM) * CM_UNIT);
            PdfPCell cell = new PdfPCell(new Paragraph(mensagem,
                    FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, Color.BLACK)));
            cell.setBorderWidth(0);
            table.addCell(cell);

            over.setRGBColorFill(255, 255, 255);
            mask.setAbsolutePosition(
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + STAMP_BORDER_IN_CM) * CM_UNIT,
                    (PAGE_BORDER_IN_CM - STAMP_BORDER_IN_CM) * CM_UNIT);
            mask.scaleAbsolute(2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalWidth(),
                    2 * STAMP_BORDER_IN_CM * CM_UNIT + table.getTotalHeight());
            over.addImage(mask);

            over.setRGBColorFill(0, 0, 0);
            table.writeSelectedRows(0, -1,
                    (QRCODE_LEFT_MARGIN_IN_CM + QRCODE_SIZE_IN_CM + 2 * STAMP_BORDER_IN_CM) * CM_UNIT,
                    table.getTotalHeight() + PAGE_BORDER_IN_CM * CM_UNIT, over);
        }

        if (cancelado) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "CANCELADO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (rascunho) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "MINUTA", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        } else if (semEfeito) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "SEM EFEITO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // if (!rascunho
        // && request.getRequestURL().indexOf("http://laguna/") == -1) {

        if (!rascunho && !cancelado && !semEfeito && ((!Contexto.resource("isVersionTest").equals("false"))
                || (!Contexto.resource("isBaseTest").equals("false")))) {
            over.saveState();
            final PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            over.setGState(gs);
            over.setColorFill(Color.GRAY);
            over.beginText();
            over.setFontAndSize(helv, 72);
            over.showTextAligned(Element.ALIGN_CENTER, "INVLIDO", r.getWidth() / 2, r.getHeight() / 2, 45);
            over.endText();
            over.restoreState();
        }

        // Imprime um circulo com o numero da pagina dentro.

        if (paginaInicial != null) {
            String sFl = String.valueOf(paginaInicial + i - 1);
            // Se for a ultima pagina e o numero nao casar, acrescenta "-" e
            // pagina final
            if (n == i) {
                if (paginaFinal != paginaInicial + n - 1) {
                    sFl = sFl + "-" + String.valueOf(paginaFinal);
                }
            }
            if (i > cOmitirNumeracao) {

                // Raio do circulo interno
                final float radius = 18f;

                // Distancia entre o circulo interno e o externo
                final float circleInterspace = Math.max(helv.getAscentPoint(instancia, TEXT_HEIGHT),
                        helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT))
                        - Math.min(helv.getDescentPoint(instancia, TEXT_HEIGHT),
                                helv.getDescentPoint(orgaoUsu, TEXT_HEIGHT))
                        + 2 * TEXT_TO_CIRCLE_INTERSPACE;

                // Centro do circulo
                float xCenter = r.getWidth() - 1.8f * (radius + circleInterspace);
                float yCenter = r.getHeight() - 1.8f * (radius + circleInterspace);

                over.saveState();
                final PdfGState gs = new PdfGState();
                gs.setFillOpacity(1f);
                over.setGState(gs);
                over.setColorFill(Color.BLACK);

                over.saveState();
                over.setColorStroke(Color.black);
                over.setLineWidth(1f);
                over.setColorFill(Color.WHITE);

                // Circulo externo
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.fill();
                over.circle(xCenter, yCenter, radius + circleInterspace);
                over.stroke();

                // Circulo interno
                over.circle(xCenter, yCenter, radius);
                over.stroke();
                over.restoreState();

                {
                    over.saveState();
                    over.beginText();
                    over.setFontAndSize(helv, TEXT_HEIGHT);

                    // Escreve o texto superior do carimbo
                    float fDescent = helv.getDescentPoint(instancia, TEXT_HEIGHT);
                    showTextOnArc(over, instancia, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius - fDescent + TEXT_TO_CIRCLE_INTERSPACE, true);

                    // Escreve o texto inferior
                    float fAscent = helv.getAscentPoint(orgaoUsu, TEXT_HEIGHT);
                    showTextOnArc(over, orgaoUsu, helv, TEXT_HEIGHT, xCenter, yCenter,
                            radius + fAscent + TEXT_TO_CIRCLE_INTERSPACE, false);
                    over.endText();
                    over.restoreState();
                }

                over.beginText();
                int textHeight = 23;

                // Diminui o tamanho do font ate que o texto caiba dentro do
                // circulo interno
                while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
                    textHeight--;
                float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
                over.setFontAndSize(helv, textHeight);
                over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
                over.endText();
                over.restoreState();
            }
        }

    }
    stamp.close();
    return bo2.toByteArray();
}

From source file:buckley.compile.Compiler.java

License:Apache License

public void compile(InputStream pdfTemplate, OutputStream output, final buckley.Document doc) {
    final Pdf pdf = new Pdf(pdfTemplate, output);
    try {/*w w  w .ja  v  a 2 s .  c  o  m*/
        pdf.eachPage(new Pdf.PageHandler() {
            public void handlePage(int number, PdfReader reader, PdfWriter writer, Document document,
                    PdfAcroForm form) {
                PdfContentByte content = writer.getDirectContent();
                PdfImportedPage importedPage = writer.getImportedPage(reader, number);
                content.addTemplate(importedPage, 0.0f, 0.0f);
                if (doc.hasFields(number)) {
                    Page page = doc.getPage(number);
                    for (Field field : page.getFields()) {
                        Rectangle fieldSize = fieldSizeFactory.build(field);
                        ITextFieldFactory factory = fieldFactories.get(field.getClass());
                        BaseField iTextField = factory.build(writer, fieldSize, field.getName());
                        for (FieldAttributeModifier modifier : modifiers) {
                            if (modifier.canModify(field)) {
                                modifier.modify(iTextField, field, doc);
                            }
                        }
                        try {
                            writer.addAnnotation(factory.buildFormField(iTextField));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                document.newPage();
            }
        });
    } finally {
        pdf.close();
    }
}

From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java

License:Open Source License

/**
 * Outputs a PDF file report of the data in drs to the given
 * output stream.// w  w w .  j av  a2 s . c o  m
 * @throws SQLObjectException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void format(OutputStream out, List<ProfileResult> profileResults)
        throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException,
        IllegalAccessException, ClassNotFoundException {

    final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow
    final int mtop = 50; // margin at top of page (in points)
    final int mbot = 50; // margin at bottom of page (page numbers are below this)
    //        final int pbot = 20;  // padding between bottom margin and bottom of body text
    final int mlft = 50; // margin at left side of page
    final int mrgt = 50; // margin at right side of page
    final Rectangle pagesize = PageSize.LETTER.rotate();
    final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot);
    final PdfWriter writer = PdfWriter.getInstance(document, out);

    final float fsize = 6f; // the font size to use in the table body
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    document.addTitle("Table Profiling Report");
    document.addSubject("Tables: " + profileResults);
    document.addAuthor(System.getProperty("user.name"));
    document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION);

    document.open();

    // vertical position where next element should start
    //   (bottom is 0; top is pagesize.height())
    float pos = pagesize.height() - mtop;

    final PdfContentByte cb = writer.getDirectContent();
    final PdfTemplate nptemplate = cb.createTemplate(50, 50);
    writer.setPageEvent(new PdfPageEventHelper() {
        // prints the "page N of <template>" footer
        public void onEndPage(PdfWriter writer, Document document) {
            int pageN = writer.getPageNumber();
            String text = "Page " + pageN + " of ";
            float len = bf.getWidthPoint(text, fsize - 2);
            cb.beginText();
            cb.setFontAndSize(bf, fsize - 2);
            cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2);
            cb.showText(text);
            cb.endText();
            cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2);
        }

        public void onCloseDocument(PdfWriter writer, Document document) {
            nptemplate.beginText();
            nptemplate.setFontAndSize(bf, fsize - 2);
            nptemplate.showText(String.valueOf(writer.getPageNumber() - 1));
            nptemplate.endText();
        }
    });

    document.add(new Paragraph("SQL Power Architect Profiling Report"));
    document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name")));

    float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table
    LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result

    Font f = new Font(bf, fsize);

    // This ddl generator is set to the appropriate ddl generator for the source database
    // every time we encounter a table profile result in the list.
    DDLGenerator ddlg = null;

    PdfPTable pdfTable = null;
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    double allowedTableSize = pagesize.width() - mrgt - mlft;
    double totalWidths = 0;
    for (int i = 0; i < headings.length; i++) {
        if (!columnsToTruncate.contains(headings[i])) {
            widths[i] += PIXELS_PER_BORDER;
            totalWidths += widths[i];
        }
    }
    truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size())))
            / columnsToTruncate.size();
    logger.debug("Truncate length is " + truncateLength);
    widths = new float[totalColumn];

    profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    for (int i = 0; i < headings.length; i++) {
        widths[i] += PIXELS_PER_BORDER;
    }

    // add the PdfPTables to the document; try to avoid orphan and widow rows
    pos = writer.getVerticalPosition(true) - fsize;
    logger.debug("Starting at pos=" + pos);
    boolean newPageInd = true;

    for (ProfileTableStructure profile : profiles) {

        pdfTable = profile.getMainTable();
        pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft);
        pdfTable.setWidths(widths);
        resetHeaderWidths(profile, widths);

        int startrow = pdfTable.getHeaderRows();
        int endrow = startrow; // current page will contain header+startrow..endrow

        /* no other rows in the table, just the header, and the header may
         * contain error message
         */
        if (endrow == pdfTable.size()) {
            pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
            continue;
        }

        while (endrow < pdfTable.size()) {

            // figure out how many body rows fit nicely on the page
            float endpos = pos - calcHeaderHeight(pdfTable);

            // y position of page number# = (mbot/2+fsize)
            while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2)
                    && endrow < pdfTable.size()) {
                endpos -= pdfTable.getRowHeight(endrow);
                endrow++;
            }

            // adjust for orphan rows. Might create widows or make
            // endrow < startrow, which is handled later by deferring the table
            if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) {

                // page # maybe fall into table area, but usually that's column of
                // min value, usually that's enough space for both, or we should
                // disable page # on this page
                if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) {

                    // short by 1 row.. just squeeze it in
                    endrow = pdfTable.size();
                } else {
                    // more than 1 row remains: shorten this page so orphans aren't lonely
                    endrow = pdfTable.size() - minRowsTogether;
                }
            }

            if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) {
                // this is the end of the table, or we have enough rows to bother printing
                pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
                pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb);
                startrow = endrow;
                newPageInd = false;
            } else {
                // not the end of the table and not enough rows to print out
                if (newPageInd)
                    throw new IllegalStateException(
                            "PDF Page is not large engouh to display " + minRowsTogether + " row(s)");
                endrow = startrow;
            }

            // new page if necessary (that is, when we aren't finished the table yet)
            if (endrow != pdfTable.size()) {
                document.newPage();
                pos = pagesize.height() - mtop;
                newPageInd = true;
            }
        }
    }
    document.close();
}

From source file:classroom.intro.HelloWorld08.java

public static void main(String[] args) {
    Document.compress = false;// w  w  w  .ja v a2s.  c o  m
    // step 1
    Document document = new Document();
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 12);
        cb.moveText(88.66f, 788);
        cb.showText("ld");
        cb.moveText(-22f, 0);
        cb.showText("Wor");
        cb.moveText(-15.33f, 0);
        cb.showText("llo");
        cb.endText();
        PdfTemplate tmp = cb.createTemplate(250, 25);
        tmp.beginText();
        tmp.setFontAndSize(bf, 12);
        tmp.moveText(0, 7);
        tmp.showText("He");
        tmp.endText();
        cb.addTemplate(tmp, 36, 781);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5
    document.close();
}

From source file:classroom.intro.HelloWorld09.java

public static void main(String[] args) {
    Document.compress = false;/*from  www  .  j a  v a2 s.  c o m*/
    BaseFont bf = null;
    // step 1
    Document document = new Document();
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT1));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 12);
        cb.moveText(88.66f, 788);
        cb.showText("ld");
        cb.moveText(-22f, 0);
        cb.showText("Wor");
        cb.endText();
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5
    document.close();

    try {
        PdfReader reader = new PdfReader(RESULT1);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT2));
        PdfContentByte cb1 = stamper.getUnderContent(1);
        cb1.beginText();
        cb1.setFontAndSize(bf, 12);
        cb1.setTextMatrix(51.33f, 788);
        cb1.showText("llo");
        cb1.endText();
        PdfContentByte cb2 = stamper.getOverContent(1);
        PdfTemplate tmp = cb2.createTemplate(250, 25);
        tmp.beginText();
        tmp.setFontAndSize(bf, 12);
        tmp.moveText(0, 7);
        tmp.showText("He");
        tmp.endText();
        cb2.addTemplate(tmp, 36, 781);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:classroom.newspaper_a.Newspaper02.java

public static void main(String[] args) {
    try {/* w w w  . java  2  s. c o  m*/
        PdfReader reader = new PdfReader(NEWSPAPER);
        Document document = new Document(reader.getPageSizeWithRotation(1));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        PdfContentByte content = writer.getDirectContent();
        content.rectangle(document.left(), document.bottom(), document.right(), document.top());
        content.rectangle(LLX1, LLY1, W1, H1);
        content.rectangle(LLX2, LLY2, W2, H2);
        content.eoClip();
        content.newPath();
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        content.addTemplate(page, 0, 0);
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:com.anevis.jfreechartsamplespring.chart.ChartServiceImpl.java

private byte[] writeChartsToDocument(JFreeChart... charts) {
    try {/*w ww . j av  a  2 s  .  c  om*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight() / 2;
        int index = 0;

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();

        for (JFreeChart chart : charts) {

            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2D = template.createGraphics(width, height);
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);

            chart.draw(graphics2D, rectangle2D);

            graphics2D.dispose();
            contentByte.addTemplate(template, 0, height - (height * index));
            index++;
        }

        writer.flush();
        document.close();

        return baos.toByteArray();
    } catch (DocumentException ex) {
        Logger.getLogger(ChartService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.bayareasoftware.chartengine.chart.jfree.JFreeChartDriver.java

License:Apache License

/**
* Writes a chart to an output stream in PDF format.
*
* @param out the output stream./*from  w w  w. j  a  va2 s.c  o  m*/
* @param chart the chart.
* @param width the chart width.
* @param height the chart height.
*
*/
public void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height, FontMapper mapper) {
    com.lowagie.text.Rectangle pagesize = new com.lowagie.text.Rectangle(width, height);
    Document document = new Document(pagesize, 50.0f, 50.0f, 50.0f, 50.0f);
    try {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.addAuthor("ChartMechanic");
        document.addSubject("ChartMechanic PDF");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = tp.createGraphics(width, height, mapper);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2, r2D);
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    }
    document.close();

}

From source file:com.byterefinery.rmbench.export.diagram.PDFDiagramExporter.java

License:Open Source License

protected void doExport(OutputStream out, IFigure figure) {

    Rectangle bounds = getBounds(figure);
    Document document = new Document(new com.lowagie.text.Rectangle(bounds.width, bounds.height));

    PdfWriter pdf;//w  ww  .j av a 2 s  . co  m
    try {
        pdf = PdfWriter.getInstance(document, out);
        document.open();
        document.add(new Chunk(" "));
    } catch (DocumentException e) {
        ExportPlugin.logError(e);
        return;
    }
    PdfContentByte contentbytes = pdf.getDirectContent();
    PdfTemplate template = contentbytes.createTemplate(bounds.width, bounds.height);
    Graphics2D graphics2d = template.createGraphics(bounds.width, bounds.height);
    try {
        GraphicsToGraphics2DAdaptor graphics = new GraphicsToGraphics2DAdaptor(graphics2d,
                bounds.getTranslated(bounds.getLocation().negate()));
        graphics.translate(bounds.getLocation().negate());
        figure.paint(graphics);
    } finally {
        graphics2d.dispose();
        contentbytes.addTemplate(template, 0, 0);
        document.close();
    }
}

From source file:com.compomics.mascotdatfile.research.tool.spectrumviewer.spectrumviewer_gui.Spectrumviewer_gui.java

License:Apache License

/**
 * This method is called whenever the user clicked the button to export the spectrum to pdf.
 *//*w  w  w . j  a  v a2s .  c  om*/
private void pdfOutputTriggered() {
    if (dtp != null) {

        // Looping boolean.
        boolean lbContinue = true;
        // Previous selected path.
        String previousPath = "/";
        // The file filter to use.
        FileFilter filter = new FileFilter() {
            public boolean accept(File f) {
                boolean result = false;
                if (f.isDirectory() || f.getName().endsWith(".pdf")) {
                    result = true;
                }
                return result;
            }

            public String getDescription() {
                return "PDF file";
            }
        };
        while (lbContinue) {
            JFileChooser jfc = new JFileChooser(previousPath);
            jfc.setDialogTitle("Save spectrum panel as PDF file");
            jfc.setDialogType(JFileChooser.SAVE_DIALOG);
            jfc.setFileFilter(filter);
            int returnVal = jfc.showSaveDialog(this.getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = jfc.getSelectedFile();
                // Append the file extension if it is not already there.
                if (jfc.getFileFilter() == filter && !file.getName().toLowerCase().endsWith(".pdf")) {
                    file = new File(file.getAbsolutePath() + ".pdf");
                }
                // Check for existing file.
                if (file.exists()) {
                    int reply = JOptionPane.showConfirmDialog(this.getParent(),
                            new String[] { "File '" + file.getAbsolutePath() + "' exists.",
                                    "Do you wish to overwrite?" },
                            "File exists!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (reply != JOptionPane.YES_OPTION) {
                        previousPath = file.getParent();
                        continue;
                    }
                }

                // Output to PDF.
                JPanel jpanSpectrum = dtp.getSpectrumPanel();
                float lWidthFloat = (new Double(jpanSpectrum.getSize().getWidth())).floatValue() + 20;
                float lHeightFloat = (new Double(jpanSpectrum.getSize().getHeight())).floatValue();
                int lWidthInt = (new Double(jpanSpectrum.getSize().getWidth())).intValue();
                int lHeightInt = (new Double(jpanSpectrum.getSize().getHeight())).intValue();

                Document document = new Document(new Rectangle(lWidthInt, lHeightInt));

                try {
                    PdfWriter writer;
                    writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                    document.open();
                    PdfContentByte cb = writer.getDirectContent();
                    PdfTemplate tp = cb.createTemplate(lWidthFloat, lHeightFloat);
                    Graphics2D g2;
                    g2 = tp.createGraphicsShapes(lWidthFloat, lHeightFloat);
                    jpanSpectrum.print(g2);
                    g2.dispose();
                    cb.addTemplate(tp, 0, 0);
                    writer.flush();
                    JOptionPane.showMessageDialog(this, "Data successfully written to '" + file + "'!",
                            "Output completed!", JOptionPane.INFORMATION_MESSAGE);
                    document.close();
                } catch (DocumentException e) {
                    JOptionPane.showMessageDialog(this,
                            new String[] { "Unable to create PDF file!", e.getMessage() },
                            "Unable to create PDF file!", JOptionPane.WARNING_MESSAGE);
                } catch (FileNotFoundException e) {
                    // Should never occur.
                    JOptionPane.showMessageDialog(this,
                            new String[] { "Unable to write file!", e.getMessage() }, "Unable to write file!",
                            JOptionPane.WARNING_MESSAGE);
                }

                lbContinue = false;
            } else {
                lbContinue = false;
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "You need to load a datfile and SpectrumPanel first!",
                "No datfile loaded yet!", JOptionPane.ERROR_MESSAGE);
    }

}