Example usage for com.lowagie.text.pdf PdfWriter getDirectContent

List of usage examples for com.lowagie.text.pdf PdfWriter getDirectContent

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getDirectContent.

Prototype


public PdfContentByte getDirectContent() 

Source Link

Document

Use this method to get the direct content for this document.

Usage

From source file:oscar.oscarPrevention.pageUtil.PreventionPrintPdf.java

License:Open Source License

public void printPdf(String[] headerIds, HttpServletRequest request, OutputStream outputStream)
        throws IOException, DocumentException {
    //make sure we have data to print
    //String[] headerIds = request.getParameterValues("printHP");
    if (headerIds == null)
        throw new DocumentException();

    //Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.setPageSize(PageSize.LETTER);
    document.open();//from  w  w  w  . j  a  v a2s.c o m

    //Create the font we are going to print to
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    Font font = new Font(bf, FONTSIZE, Font.NORMAL);
    float leading = font.getCalculatedLeading(LINESPACING);

    //set up document title and header
    String title = "Preventions for " + request.getParameter("nameAge");
    String hin = "HIN: " + request.getParameter("hin");
    String mrp = request.getParameter("mrp");
    if (mrp != null) {
        Properties prop = (Properties) request.getSession().getAttribute("providerBean");
        mrp = "MRP: " + prop.getProperty(mrp, "unknown");
    }

    ClinicData clinicData = new ClinicData();
    clinicData.refreshClinicData();
    String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(),
            clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(),
            clinicData.getClinicPhone(), title, hin, mrp };

    //Header will be printed at top of every page beginning with p2
    Phrase headerPhrase = new Phrase(LEADING, title, font);
    HeaderFooter header = new HeaderFooter(headerPhrase, false);
    header.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setHeader(header);

    //Write title with top and bottom borders on p1
    cb = writer.getDirectContent();
    cb.setColorStroke(new Color(0, 0, 0));
    cb.setLineWidth(0.5f);

    cb.moveTo(document.left(), document.top());
    cb.lineTo(document.right(), document.top());
    cb.stroke();
    cb.setFontAndSize(bf, FONTSIZE);

    upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f);
    cb.beginText();
    for (int idx = 0; idx < clinic.length; ++idx) {
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, clinic[idx], document.right() / 2f, upperYcoord, 0f);
        upperYcoord -= font.getCalculatedLeading(LINESPACING);
    }

    cb.endText();
    cb.moveTo(document.left(), upperYcoord);
    cb.lineTo(document.right(), upperYcoord);
    cb.stroke();

    //get top y-coord for starting to print columns
    upperYcoord = cb.getYTLM() - font.getCalculatedLeading(LINESPACING * 2f);

    int subIdx;
    String preventionHeader, procedureAge, procedureDate;

    //1 - obtain number of lines of incoming prevention data
    numLines = 0;
    for (int idx = 0; idx < headerIds.length; ++idx) {
        ++numLines;
        subIdx = 0;
        while (request.getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx) != null) {
            ++subIdx;
            numLines += 3;
        }
        numLines += 2;
    }

    //2 - calculate max num of lines a page can hold and number of pages of data we have
    pageHeight = upperYcoord - document.bottom();
    maxLines = (int) Math.floor(pageHeight / (font.getCalculatedLeading(LINESPACING) + 4d));
    numPages = (int) Math.ceil(numLines / ((double) maxLines * NUMCOLS));

    //3 - Start the column
    ct = new ColumnText(cb);
    ct.setSimpleColumn(document.left(), document.bottom(), document.right() / 2f, upperYcoord);

    linesToBeWritten = linesWritten = 0;
    boolean pageBreak = false;

    curPage = 1;
    totalLinesWritten = 0;

    //add promotext to current page
    addPromoText();

    //if we have > 1 element but less than a page of data, shrink maxLines so we can try to balance text in columns
    if (headerIds.length > 1) {
        if (curPage == numPages) {
            maxLines = numLines / NUMCOLS;
        }
    }

    //now we can start to print the prevention data
    for (int idx = 0; idx < headerIds.length; ++idx) {

        linesToBeWritten = 4; //minimum lines for header and one prevention item
        pageBreak = checkColumnFill(ct, "", font, pageBreak); //if necessary break before we print prevention header

        preventionHeader = request.getParameter("preventionHeader" + headerIds[idx]);
        Phrase procHeader = new Phrase(LEADING, "Prevention " + preventionHeader + "\n", font);
        ct.addText(procHeader);
        subIdx = 0;

        while ((procedureAge = request
                .getParameter("preventProcedureAge" + headerIds[idx] + "-" + subIdx)) != null) {
            procedureDate = request.getParameter("preventProcedureDate" + headerIds[idx] + "-" + subIdx);

            linesToBeWritten = 3;
            pageBreak = checkColumnFill(ct, preventionHeader, font, pageBreak);

            Phrase procedure = new Phrase(LEADING, "     " + procedureAge + "\n", font);
            procedure.add("     " + procedureDate + "\n\n");
            ct.addText(procedure);
            ct.go();
            linesWritten += ct.getLinesWritten();
            totalLinesWritten += ct.getLinesWritten();
            ++subIdx;
        }

    }

    ColumnText.showTextAligned(cb, Phrase.ALIGN_CENTER, new Phrase("-" + curPage + "-"), document.right() / 2f,
            document.bottom() - (document.bottomMargin() / 2f), 0f);

    document.close();
}

From source file:papertoolkit.render.SheetRenderer.java

License:BSD License

/**
 * Uses the iText package to render a PDF file from scratch. iText is nice because we can write to a
 * Graphics2D context. Alternatively, we can use PDF-like commands.
 * //from   ww  w .ja va2s .com
 * @param destPDFFile
 */
public void renderToPDF(File destPDFFile) {
    try {
        final FileOutputStream fileOutputStream = new FileOutputStream(destPDFFile);

        final Rectangle pageSize = new Rectangle(0, 0, (int) Math.round(sheet.getWidth().getValueInPoints()),
                (int) Math.round(sheet.getHeight().getValueInPoints()));

        // create a document with these margins (worry about margins later)
        final Document doc = new Document(pageSize, 0, 0, 0, 0);
        final PdfWriter writer = PdfWriter.getInstance(doc, fileOutputStream);
        doc.open();

        final PdfContentByte topLayer = writer.getDirectContent();
        final PdfContentByte bottomLayer = writer.getDirectContentUnder();
        renderToPDFContentLayers(destPDFFile, topLayer, bottomLayer);

        doc.close();

        // save the pattern info to the same directory automatically
        savePatternInformation(); // do this automatically
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:peakml.graphics.JFreeChartTools.java

License:Open Source License

/**
 * This method writes the given graph to the output stream in the PDF format. As a vector
 * based file format it allows some freedom to be changed (e.g. colors, line thickness, etc.),
 * which can be convenient for presentation purposes.
 * // w  ww.  jav  a  2 s.c om
 * @param out         The output stream to write to.
 * @param chart         The chart to be written.
 * @param width         The width of the image.
 * @param height      The height of the image.
 * @throws IOException   Thrown when an error occurs with the IO.
 */
public static void writeAsPDF(OutputStream out, JFreeChart chart, int width, int height) throws IOException {
    Document document = new Document(new Rectangle(width, height), 50, 50, 50, 50);
    document.addAuthor("");
    document.addSubject("");

    try {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);

        java.awt.Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
        chart.draw(g2, new java.awt.geom.Rectangle2D.Double(0, 0, width, height));

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }

    document.close();
}

From source file:PresentationLayer.CreatePuzzleJFrame.java

private void savePuzzlejButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_savePuzzlejButtonActionPerformed
    fileChooser.resetChoosableFileFilters();
    fileChooser.setAcceptAllFileFilterUsed(false);

    fileChooser.setDialogTitle("Save Puzzle");

    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF", "pdf"));
    //        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG", "jpeg"));
    //        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG", "jpg"));
    //        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG", "png"));
    //        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("BMP", "bmp"));

    int r = fileChooser.showSaveDialog(this);

    if (r == JFileChooser.APPROVE_OPTION) {

        String name = fileChooser.getSelectedFile().getAbsolutePath();
        String type = fileChooser.getFileFilter().getDescription();

        JPanel jPanelToPrint = printablejPanel;

        if (type.equals("PDF")) { //Save as pdf
            puzzlejTable.setBackground(Color.black);
            try {
                //                  Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
                Document document = new Document(new Rectangle(docWidth, docHeight));
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name + ".pdf"));
                document.open();/*from   w w  w  .jav a 2  s . c  o m*/
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(jPanelToPrint.getWidth(), jPanelToPrint.getHeight());
                Graphics2D g2 = tp.createGraphics(jPanelToPrint.getWidth(), jPanelToPrint.getHeight());
                //g2.scale(0.8, 1.0);
                jPanelToPrint.print(g2);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
                document.close();
            } catch (DocumentException ex) {
                Logger.getLogger(CreatePuzzleJFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(CreatePuzzleJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            puzzlejTable.setBackground(Color.white);

        } else { //Save as image

            BufferedImage bi = ScreenImage.createImage(jPanelToPrint);
            try {
                ScreenImage.writeImage(bi, name + "." + type.toLowerCase());
            } catch (IOException ex) {
                Logger.getLogger(CreatePuzzleJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}

From source file:questions.directcontent.InterpretOCR.java

public static void main(String[] args) throws IOException, DocumentException {
    Document document = new Document(PageSize.LETTER);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
    document.open();/*  ww  w.  j a va 2  s . co m*/
    PdfContentByte cb = writer.getDirectContent();
    BaseFont font = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    cb.beginText();
    cb.setFontAndSize(font, 12);
    String line;
    String word;
    @SuppressWarnings("unused")
    float llx, lly, urx, ury;
    StringTokenizer tokenizer;
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(RESOURCE)));
    while ((line = reader.readLine()) != null) {
        tokenizer = new StringTokenizer(line);
        while (tokenizer.hasMoreTokens()) {
            tokenizer.nextToken();
            word = tokenizer.nextToken();
            llx = Float.parseFloat(tokenizer.nextToken() + "f") / 10;
            lly = document.top() - Float.parseFloat(tokenizer.nextToken() + "f") / 10;
            urx = Float.parseFloat(tokenizer.nextToken() + "f") / 10;
            ury = document.top() - Float.parseFloat(tokenizer.nextToken() + "f") / 10;
            cb.showTextAligned(Element.ALIGN_LEFT, word, (llx + urx) / 2, lly, 0);
        }
    }
    cb.endText();
    document.close();
}

From source file:questions.directcontent.Logo.java

public static void main(String[] args) {
    Rectangle rect = new Rectangle(36, 726, 136, 786);
    Document document = new Document(rect);
    try {//from ww  w .j  av a 2  s.c om
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        PdfContentByte canvas = writer.getDirectContent();
        canvas.moveTo(63.73f, 735.47f);
        canvas.curveTo(72.13f, 737.94f, 75.73f, 758.15f, 79.67f, 768.04f);
        canvas.curveTo(84.82f, 767.79f, 94.41f, 772.38f, 85.69f, 772.97f);
        canvas.curveTo(83.19f, 768.56f, 63.84f, 779.61f, 60.55f, 779.7f);
        canvas.curveTo(48.58f, 780.03f, 74.62f, 769.75f, 74.68f, 769.99f);
        canvas.curveTo(74.64f, 769.8f, 69.43f, 743.55f, 66.08f, 740.12f);
        canvas.curveTo(59.24f, 733.11f, 52.73f, 745.57f, 53.35f, 752.21f);
        canvas.curveTo(53.6f, 754.85f, 64.32f, 747.14f, 57.21f, 755.02f);
        canvas.curveTo(45.66f, 767.82f, 49.11f, 731.17f, 63.73f, 735.47f);
        canvas.moveTo(93.61f, 741.57f);
        canvas.curveTo(109.15f, 721.02f, 112.42f, 746.51f, 118.3f, 761.57f);
        canvas.curveTo(124.73f, 761.48f, 129.8f, 765.3f, 124f, 765.62f);
        canvas.curveTo(119.84f, 761.88f, 108.12f, 770.22f, 100.92f, 771.57f);
        canvas.curveTo(94.24f, 769.12f, 115.02f, 764.34f, 114.24f, 761.53f);
        canvas.curveTo(109.9f, 751.94f, 107.5f, 721.65f, 95.84f, 744.74f);
        canvas.curveTo(100.15f, 747.38f, 109.63f, 766.92f, 95.28f, 748.57f);
        canvas.curveTo(91.45f, 743.68f, 89.6f, 766.35f, 77.99f, 754.83f);
        canvas.curveTo(74.22f, 751.07f, 84.27f, 747.81f, 81.6f, 745.28f);
        canvas.curveTo(67.39f, 750.93f, 74.66f, 719.55f, 93.61f, 741.57f);
        canvas.moveTo(78.37f, 743.72f);
        canvas.curveTo(78.19f, 743.22f, 89.27f, 744.04f, 82.46f, 749.7f);
        canvas.curveTo(76.28f, 754.83f, 85.17f, 760.2f, 90.72f, 746.97f);
        canvas.curveTo(94f, 739.15f, 73.88f, 730.88f, 78.37f, 743.72f);
        canvas.setCMYKColorFillF(1, 0.5f, 0, 0.467f);
        canvas.fill();
        canvas.setCMYKColorFillF(0, 0.467f, 1, 0);
        canvas.moveTo(58f, 764.8f);
        canvas.curveTo(58f, 767.01f, 56.21f, 768.8f, 54f, 768.8f);
        canvas.curveTo(51.79f, 768.8f, 50f, 767.01f, 50f, 764.8f);
        canvas.curveTo(50f, 762.59f, 51.79f, 760.8f, 54f, 760.8f);
        canvas.curveTo(56.21f, 760.8f, 58f, 762.59f, 58f, 764.8f);
        canvas.fill();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:questions.forms.RadioButtonsOnDifferentPages.java

public static void main(String[] args) {
    Document document = new Document();
    try {/*from  w w w  . j a  va  2  s  .  com*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        String[] languages = { "English", "French", "Dutch" };
        Rectangle rect;

        // create radio button field and its kids
        PdfFormField language = PdfFormField.createRadioButton(writer, true);
        language.setFieldName("language");
        language.setValueAsName(languages[0]);
        for (int i = 0; i < languages.length; i++) {
            rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40);
            addRadioButton(writer, rect, language, languages[i], i == 0, writer.getPageNumber() + i);
        }
        writer.addAnnotation(language);

        // add the page content
        for (int i = 0; i < languages.length; i++) {
            cb.beginText();
            cb.setFontAndSize(bf, 18);
            cb.showTextAligned(Element.ALIGN_LEFT, languages[i], 70, 790 - i * 40, 0);
            cb.endText();
            document.newPage();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // step 5: we close the document
    document.close();

}

From source file:questions.graphics2D.ArabicText.java

public static void main(String[] args) {
    Document document = new Document(PageSize.A4);
    try {//from w w w  .  ja v  a  2 s .  c o m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        String text1 = "\u0634\u0627\u062f\u062c\u0645\u0647\u0648\u0631";
        String text2 = "\u0634";
        java.awt.Font font = new java.awt.Font("arial", 0, 12);
        PdfContentByte cb = writer.getDirectContent();

        java.awt.Graphics2D g2Shapes = cb.createGraphicsShapes(PageSize.A4.getWidth(), PageSize.A4.getHeight());
        g2Shapes.setFont(font);
        g2Shapes.drawString("text1, expected to render RTL", 50, 100);
        g2Shapes.drawString(text1, 50, 120);
        g2Shapes.drawString("text2, expected to match right-most glyph above", 50, 140);
        g2Shapes.drawString(text2, 50, 160);
        g2Shapes.dispose();

        ColumnText text = new ColumnText(cb);
        Font f = new Font(
                BaseFont.createFont("c://windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED),
                12);
        text.setSimpleColumn(50, 620, 545, 50);
        text.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
        text.setText(new Phrase(text1, f));
        text.go();
        text.setText(new Phrase(text2, f));
        text.go();

        FontMapper arialuni = new FontMapper() {
            public BaseFont awtToPdf(java.awt.Font font) {
                try {
                    return BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H,
                            BaseFont.EMBEDDED);
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            public java.awt.Font pdfToAwt(BaseFont font, int size) {
                return null;
            }

        };
        java.awt.Graphics2D g = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight(), arialuni);
        g.setFont(null);
        g.drawString("text1, not expected to render RTL", 50, 180);
        g.drawString(text1, 50, 200);
        g.drawString("text2, not expected to match right-most glyph above", 50, 220);
        g.drawString(text2, 50, 240);
        g.drawString("to your right you see what it SHOULD look like:", 50, 260);
        g.drawString("If it doesn't, the problem is in the JDK, it's not an iText problem.", 50, 280);
        g.dispose();
        document.close();
    } catch (Exception de) {
        de.printStackTrace();
    }
}

From source file:questions.graphics2D.SwingForceArialUni.java

public static void main(String[] args) {
    Document document = new Document(new Rectangle(210, 25));
    try {/* www . j  ava2 s  .  c o m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        FontMapper arialuni = new FontMapper() {
            public BaseFont awtToPdf(Font font) {
                try {
                    return BaseFont.createFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H,
                            BaseFont.EMBEDDED);
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            public Font pdfToAwt(BaseFont font, int size) {
                return null;
            }

        };
        Graphics2D g2 = cb.createGraphics(200, 50, arialuni);
        g2.setFont(null);
        g2.drawString("Greek mu: \u03bc - \u039c; degree symbol: \u00b0", 0, 40);
        g2.dispose();
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();
}

From source file:questions.images.CustomizedTitleBar.java

public static Image getTitleBar(PdfWriter writer, Image background, String title)
        throws DocumentException, IOException {
    float width = background.getWidth();
    float height = background.getHeight();
    PdfTemplate tmp = writer.getDirectContent().createTemplate(width, height);
    tmp.addImage(background, width, 0, 0, height, 0, 0);
    BaseFont font = BaseFont.createFont();
    tmp.beginText();//from   ww  w. ja  va  2  s  . co m
    tmp.setGrayFill(1);
    tmp.setFontAndSize(font, 18);
    tmp.showTextAligned(Element.ALIGN_CENTER, title, width / 2, 4, 0);
    tmp.endText();
    return Image.getInstance(tmp);
}