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

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

Introduction

In this page you can find the example usage for com.itextpdf.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:JT.java

public void createPdf(String filename) throws DocumentException, IOException {
    // step 1//  w  ww.ja v  a 2  s .  c o m
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3

    BaseFont bf = BaseFont.createFont("C:\\Windows\\Fonts\\vuTimes.ttf", BaseFont.IDENTITY_H,
            BaseFont.EMBEDDED);
    Font font = new Font(bf, 15);
    document.open();
    // step 4
    String pa = "H? v tn         : L Ng?c Long\n" + "MSSV                : 20142659\n"
            + "?? ti               : Xy dng chng trnh qun l th vin";
    pa += "\n\nTr?ng ?i H?c Bch Khoa H Ni          Cng Ha - X Hi - Ch Ngha - Vit Nam\n"
            + "      Th vin T Quang Bu                              ?c Lp - T Do - Hnh Phc";
    pa += "\n\n                                         TM KIM S?CH THEO xxx";

    document.add(new Paragraph(pa, font));

    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(jTable1.getWidth(), jTable1.getHeight());
    Graphics2D g2;

    g2 = tp.createGraphicsShapes(jTable1.getWidth(), jTable1.getHeight());
    jTable1.print(g2);
    float x = 50, y = 300;

    g2.dispose();
    cb.addTemplate(tp, x, y);

    // step 5
    document.close();
}

From source file:EmployeeInfo.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    String value1 = txt_empID.getText();
    String value2 = txt_firstName.getText();
    String value3 = txt_lastName.getText();
    String value4 = txt_age.getText();

    try {/*from   w  w w .  j  a  va 2 s  .c  om*/
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Report1.pdf"));
        document.open();
        //add barcode
        PdfContentByte CB = writer.getDirectContent();
        BarcodeEAN codEAN = new BarcodeEAN();
        codEAN.setCode("1234567891023"); //this value must be 13 digits
        Paragraph para = new Paragraph();
        document.add(new Paragraph("Barcode UDCA"));
        codEAN.setCodeType(BarcodeEAN.UPCA);
        codEAN.setCode("1098765432112");
        document.add(codEAN.createImageWithBarcode(CB, BaseColor.BLACK, BaseColor.BLACK));
        document.add(para);

        Image image = Image.getInstance("images/Cherry.png");
        document.add(new Paragraph("Image"));
        document.add(image);

        // write tile with style
        document.add(new Paragraph("Hello World",
                FontFactory.getFont(FontFactory.TIMES_BOLD, 18, Font.BOLD, BaseColor.RED)));
        // write date
        document.add(new Paragraph(new Date().toString()));
        document.add(new Paragraph("--------------------------------------------"));
        PdfPTable table = new PdfPTable(2);// 2 columns
        // set title , column sapn, aliignment,background color
        PdfPCell cell = new PdfPCell(new Paragraph("Title"));
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBackgroundColor(BaseColor.BLUE);
        table.addCell(cell);
        // PdfPTable table = new PdfPTable(x); should add multiple of x
        table.addCell("EmployeeID");
        table.addCell(value1);
        table.addCell("Name");
        table.addCell(value2);
        table.addCell("Last Name");
        table.addCell(value3);
        table.addCell("Age");
        table.addCell(value4);
        document.add(table);
        List list = new List(true, 20);
        list.add("First Item");
        list.add("Second Item");
        list.add("Third Item");
        list.add("Fourth Item");
        document.add(list);
        document.close();
        JOptionPane.showMessageDialog(null, "Report saved");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

From source file:Servlet3.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//  w w w  .  ja v a 2 s  .  c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        System.out.println("inside servlet");
        String a = request.getParameter("countryf");
        String c = request.getParameter("submit");
        String b = request.getParameter("paramf");

        //code added by Murugappan

        String CurentUID = request.getParameter("UIDvalue2f");
        String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy");
        String date1 = cal.getTime().toString();

        System.out.println("inside servlet");

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:server");

        //iserting data to UserActivity table
        Statement sthistoryinsert3 = con.createStatement();
        String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1
                + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')";
        sthistoryinsert3.executeUpdate(insertstring);
        sthistoryinsert3.close();
        System.out.println("\n Step 1");
        Statement st = con.createStatement();
        //  Statement st2 = con.createStatement();
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries(b);

        String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);
        if (rs == null)
            System.out.println("\n no rows ");
        else
            System.out.println("Rows present ");
        rs.next();

        Double start = Double.parseDouble(rs.getString(1));
        Double end = Double.parseDouble(rs.getString(2));
        Double period = 13.0;
        Double growth = Math.pow((end / start), (1 / period)) - 1;
        System.out.println("growth percentage =" + growth);
        rs.close();
        String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        rs = st.executeQuery(query2);
        rs.next();
        series.add(2011, Double.parseDouble(rs.getString(1)));
        Double second = Double.parseDouble(rs.getString(2));
        series.add(2012, second);

        Double growthvalue = second + (second * growth);

        series.add(2013, growthvalue);
        for (int i = 2014; i <= 2016; i++) {
            System.out.println("actual growth value = " + growthvalue);
            series.add((i++), (growthvalue + growthvalue * growth));
            growthvalue = growthvalue + growthvalue * growth;
        }
        rs.close();
        dataset.addSeries(series);
        DecimalFormat format_2Places = new DecimalFormat("0.00");
        growth = growth * 100;
        growth = Double.valueOf(format_2Places.format(growth));
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth
                        + "% ",
                "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false);
        // JFreeChart chart1=ChartFactory.createLineChart("World population Growth","Year","population in millions",dataSet1,PlotOrientation.VERTICAL,true,true,false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.black);
        plot.setRangeGridlinePaint(Color.black);

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(2, false);
        renderer.setSeriesShapesVisible(2, false);
        plot.setRenderer(renderer);

        /* We have to insert this colored Pie Chart into the PDF file using iText now */

        if (c.equals("View Graph in Browser")) {
            ChartUtilities.writeChartAsPNG(bos, chart, 700, 500);
            response.setContentType("image/png");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(bos.toByteArray());
            out.flush();
            out.close();
        }

        else {
            int width = 640; /* Width of our chart */
            int height = 480; /* Height of our chart */
            Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height));
            java.util.Date date = new java.util.Date();
            String chartname = "My_Colored_Chart" + date.getTime() + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname));
            PieChart.open();
            /* Add some Metadata to identify document later */
            PieChart.addTitle("How to color your Pie Chart and embed in a PDF file using iText");
            PieChart.addAuthor("Thinktibits");
            PieChart.addKeywords("iText,Color PieChart,JFreeChart,PDF,Example Tutorial");
            PdfContentByte Add_Chart_Content = writer.getDirectContent();
            PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height);
            Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
            chart.draw(Graphics_Chart, Chart_Region);
            Graphics_Chart.dispose();
            Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
            PieChart.close();
            //PrintWriter out = response.getWriter();
            //out.println("<!DOCTYPE html> <html> <body> <a href =file:///C:/apache-tomcat-8.0.12/bin/"+chartname+" download=newFileName> Download your file here </a> </body></html>");
            PdfReader reader = new PdfReader(chartname);
            PdfStamper stamper = null;
            try {
                stamper = new PdfStamper(reader, bos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            try {
                stamper.close();
            } catch (DocumentException e) {

                e.printStackTrace();
            }

            // set some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setContentLength(bos.size());

            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }

    catch (Exception i) {
        i.printStackTrace();
    }

}

From source file:appArriendos.frmVistaInstalador.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    // TODO add your handling code here:

    try {/*from  ww  w.j  ava2 s . c o  m*/
        Connection miConexion = (Connection) Conexion.GetConnection();
        Statement statement = (Statement) miConexion.createStatement();
        String folio = txtFolio.getText();
        ResultSet rs = statement
                .executeQuery("SELECT COUNT(*) AS num FROM tb_reserva WHERE num ='" + folio + "' ");
        int rows = 0;
        if (rs.next()) {
            rows = rs.getInt("num");
        }

        if (rows > 0) {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Documento Pdf", "pdf");
            chooser.setFileFilter(filter);
            chooser.setDialogTitle("Guardar archivo");
            chooser.setMultiSelectionEnabled(false);
            chooser.setAcceptAllFileFilterUsed(false);
            if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {

                String file = chooser.getSelectedFile().toString().concat(".pdf");
                FileOutputStream archivo = new FileOutputStream(file);
                Document documento = new Document();
                PdfWriter pdfw = PdfWriter.getInstance(documento, archivo);
                documento.open();

                PdfContentByte cb = pdfw.getDirectContent();

                Barcode39 codeEAN = new Barcode39();
                codeEAN.setCodeType(Barcode.UPCA);
                //                 codeEAN.setCode(folio);
                codeEAN.setCode(folio);
                documento.add(codeEAN.createImageWithBarcode(cb, null, null));
                documento.add(new Paragraph("DOCUMENTO INSTALACIN", new Font(Font.FontFamily.HELVETICA, 16)));
                documento.add(new Paragraph(" "));

                documento.add(new Paragraph(" "));
                rs = statement.executeQuery("SELECT * FROM tb_reserva WHERE num ='" + folio + "' ");

                while (rs.next()) {

                    documento.add(new Paragraph("Nmero de folio : " + folio));
                    documento.add(new Paragraph("Pedido Para Dia : " + rs.getString("fecha") + " A Las : "
                            + rs.getString("hora") + "  Horas"));
                    documento.add(
                            new Paragraph("Devolucion De Pedido Para El Dia : " + rs.getString("fecha_entrega")
                                    + " A Las : " + rs.getString("hora_entrega") + "  Horas"));
                    documento.add(new Paragraph("Solicit : " + rs.getString("rut")));
                    documento.add(new Paragraph("Fue Atendido Por : " + rs.getString("cod_admin")));
                    documento.add(new Paragraph("Sera Instalado Por : " + rs.getString("cod_instalador")));

                    int estado = rs.getInt("estado");
                    switch (estado) {
                    case 1:
                        documento.add(new Paragraph("ESTADO : EMITIDO"));
                        break;
                    case 2:
                        documento.add(new Paragraph("ESTADO : ANULADO"));
                        break;
                    case 3:
                        documento.add(new Paragraph("ESTADO : EJECUTADO"));
                        break;
                    }

                    documento.add(new Paragraph("OBSERVACION : " + rs.getString("observacion"),
                            new Font(Font.FontFamily.HELVETICA, 14)));
                }

                PdfPTable table = new PdfPTable(3);

                rs = statement.executeQuery("SELECT * FROM tb_reserva_detalle WHERE folio ='" + folio + "' ");

                table.addCell("LINEA");
                table.addCell("CODIGO");
                table.addCell("DESCRIPCION");
                while (rs.next()) {
                    table.addCell(rs.getString("num"));
                    table.addCell(rs.getString("codigo"));
                    table.addCell(rs.getString("descripcion"));

                }

                documento.add(new Paragraph(" "));
                documento.add(new Paragraph(" "));
                documento
                        .add(new Paragraph(" Equipos Solicitados : ", new Font(Font.FontFamily.HELVETICA, 14)));
                documento.add(new Paragraph(" "));
                documento.add(table);
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph("Informacin sobre los prestamos : "));
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph(
                        "Despues de la firma del presente comprobante, el Cliente se responsabiliza por los equipos entregados por el Instalador. ",
                        new Font(Font.FontFamily.HELVETICA, 8)));
                documento.add(new Paragraph(
                        "Es Responzabilidad del Instalador retirar los equipos en la fecha acordada.",
                        new Font(Font.FontFamily.HELVETICA, 8)));
                documento.add(new Paragraph(
                        "En caso de ocurrir robo, deterioro, o perdida de los equipos entregados. El Ministerio Publico iniciara los sumarios correspondeientes segun la gravedad del incidente.",
                        new Font(Font.FontFamily.HELVETICA, 8)));
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph("Recib Conforme"));

                documento.add(new Paragraph(" "));
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph("Firma Cliente : _____________________________________"));
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph(" "));
                documento.add(new Paragraph("Firma Instalador : __________________________________"));

                documento.close();
            } // fin saveshowdialog
        } else {
            JOptionPane.showMessageDialog(this, "Numero de folio ingresado no se encuentra en sistema");
        }

    } // fin trycatch
    catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage());
    }

}

From source file:appArriendos.frmVistaReserva.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    // TODO add your handling code here:

    try {//ww w  .j a va2  s .c  o m
        Connection miConexion = (Connection) Conexion.GetConnection();
        Statement statement = (Statement) miConexion.createStatement();
        String folio = txtFolio.getText();
        ResultSet rs = statement
                .executeQuery("SELECT COUNT(*) AS num FROM tb_reserva WHERE num ='" + folio + "' ");
        int rows = 0;
        if (rs.next()) {
            rows = rs.getInt("num");
        }

        if (rows > 0) {
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Documento Pdf", "pdf");
            chooser.setFileFilter(filter);
            chooser.setDialogTitle("Guardar archivo");
            chooser.setMultiSelectionEnabled(false);
            chooser.setAcceptAllFileFilterUsed(false);
            if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {

                String file = chooser.getSelectedFile().toString().concat(".pdf");
                FileOutputStream archivo = new FileOutputStream(file);
                Document documento = new Document();
                PdfWriter pdfw = PdfWriter.getInstance(documento, archivo);
                documento.open();
                PdfContentByte cb = pdfw.getDirectContent();

                Barcode39 codeEAN = new Barcode39();
                codeEAN.setCodeType(Barcode.UPCA);
                codeEAN.setCode(folio);
                documento.add(codeEAN.createImageWithBarcode(cb, null, null));
                documento.add(new Paragraph("DOCUMENTO RESERVA", new Font(Font.FontFamily.HELVETICA, 16)));

                documento.add(new Paragraph(""));

                documento.add(new Paragraph("Nmero de folio : " + folio));
                documento.add(new Paragraph(""));
                rs = statement.executeQuery("SELECT * FROM tb_reserva WHERE num ='" + folio + "' ");
                while (rs.next()) {
                    documento.add(new Paragraph("Nmero de folio : " + folio));
                    documento.add(new Paragraph("Pedido Para Dia : " + rs.getString("fecha") + " A Las : "
                            + rs.getString("hora") + "  Horas"));
                    documento.add(
                            new Paragraph("Devolucion De Pedido Para El Dia : " + rs.getString("fecha_entrega")
                                    + " A Las : " + rs.getString("hora_entrega") + "  Horas"));
                    documento.add(new Paragraph("Solicit : " + rs.getString("rut")));
                    documento.add(new Paragraph("Fue Atendido Por : " + rs.getString("cod_admin")));
                    documento.add(new Paragraph("Sera Instalado Por : " + rs.getString("cod_instalador")));

                    int estado = rs.getInt("estado");
                    switch (estado) {
                    case 1:
                        documento.add(new Paragraph("EMITIDO"));
                        break;
                    case 2:
                        documento.add(new Paragraph("ANULADO"));
                        break;
                    case 3:
                        documento.add(new Paragraph("EJECUTADO"));
                        break;
                    }
                }

                PdfPTable table = new PdfPTable(3);

                rs = statement.executeQuery("SELECT * FROM tb_reserva_detalle WHERE folio ='" + folio + "' ");

                table.addCell("LINEA");
                table.addCell("CODIGO");
                table.addCell("DESCRIPCION");
                while (rs.next()) {
                    table.addCell(rs.getString("num"));
                    table.addCell(rs.getString("codigo"));
                    table.addCell(rs.getString("descripcion"));

                }

                documento.add(new Paragraph(" "));
                documento.add(new Paragraph(" "));
                documento.add(table);

                documento.close();
            } // fin saveshowdialog                    
        } else {
            JOptionPane.showMessageDialog(this, "Numero de folio ingresado no se encuentra en sistema");
        }

    } // fin trycatch
    catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error " + ex.getMessage());
    }

}

From source file:araword.classes.HeaderFooter.java

/**
 * Increase the page number./* ww  w  .  jav a 2 s. co m*/
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
@Override
public void onStartPage(PdfWriter writer, Document document) {
    pagenumber++;
    System.out.println("ON Start Page PDF");
    Rectangle rect = writer.getBoxSize("art");

    /* header     
    ColumnText.showTextAligned(writer.getDirectContent(),                      
            com.itextpdf.text.Element.ALIGN_RIGHT, header[0],
              rect.getRight(), rect.getTop(), 0);
     */
    Font font = new Font();
    font.setSize(8);
    if (G.licensePDF) {
        ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_CENTER,
                new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA")), font),
                (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
        ColumnText.showTextAligned(writer.getDirectContent(), com.itextpdf.text.Element.ALIGN_CENTER,
                new Phrase(String.format(TLanguage.getString("EXPORT_PDF_LICENCIA2")), font),
                (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 9, 0);
    }

}

From source file:book.pdftemplates.FillTemplateHelper.java

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    background = writer.getImportedPage(reader, 1);
    total = writer.getDirectContent().createTemplate(30, 15);
    today = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(new Date());
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report that has no data in it (only the image).
 * The length is the given number of pages.
 * /*from ww w .j av  a  2 s.  c  o  m*/
 * @param numPages
 * @return True if the report was generated.
 */
public boolean generateBlank(Dao dao, Integer numPages) {
    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 1;
        while (true) {
            drawBout(cb, bf, 35, midPage - 35, null);
            drawBout(cb, bf, midPage + 35, pageWidth - 35, null);

            if (++count > numPages) {
                break;
            }

            document.newPage();
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

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

    return true;
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Generate a bout sheet report for the given list of bouts.
 * It is assumed that the list is in the desired order (no sorting is done here).
 *
 * @param list/*from   ww  w .  j a  v a 2 s  . c  o m*/
 * @return True if the report was generated.
 */
public boolean generateReport(Dao dao, List<Bout> list) {

    // step 1: creation of a document-object
    // rotate to make page landscape
    Document document = new Document(PageSize.A4.rotate());

    try {

        // step 2: creation of the writer
        FileOutputStream fos = createOutputFile();
        if (fos == null) {
            return false;
        }
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        writer.setPageEvent(this);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it
        PdfContentByte cb = writer.getDirectContent();

        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        float pageWidth = cb.getPdfDocument().getPageSize().getWidth();
        float midPage = pageWidth / 2;

        setHeaderString(dao);

        int count = 0;
        for (Bout b : list) {
            boolean rightSide = false;
            if ((count++ % 2) == 0) {
                if (count > 2) {
                    // We could put this after Bout 2 is added, but
                    // that could leave a blank last page.
                    document.newPage();
                }

                // Bout 1 (Left side)
                drawBout(cb, bf, 35, midPage - 35, b);
            } else {
                // Bout 2 (Right side)
                drawBout(cb, bf, midPage + 35, pageWidth - 35, b);
                rightSide = true;
            }

            // Print the watermark, if necessary
            boolean doWatermark = false;
            String gClass = b.getGroup().getClassification();
            String wmValues = dao.getBoutsheetWatermarkValues();
            if ((wmValues != null) && !wmValues.isEmpty()) {
                String[] tokens = wmValues.split(",");
                for (String s : tokens) {
                    if (s.trim().equalsIgnoreCase(gClass)) {
                        doWatermark = true;
                        break;
                    }
                }
            }
            if (doWatermark) {
                int rotation = 45;
                PdfContentByte ucb = writer.getDirectContentUnder();
                BaseFont helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
                ucb.saveState();
                ucb.setColorFill(BaseColor.LIGHT_GRAY);
                ucb.beginText();
                ucb.setFontAndSize(helv, 86);
                float centerWidth = document.getPageSize().getWidth() / 4;
                if (rightSide) {
                    centerWidth = centerWidth * 3;
                }
                ucb.showTextAligned(Element.ALIGN_CENTER, gClass, centerWidth,
                        document.getPageSize().getHeight() / 2, rotation);
                ucb.endText();
                ucb.restoreState();
            }
        }

    } catch (DocumentException de) {
        logger.error("Document Exception", de);
        return false;
    } catch (IOException ioe) {
        logger.error("IO Exception", ioe);
        return false;
    }

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

    return true;
}

From source file:bouttime.report.boutsheet.BoutSheetReport.java

License:Open Source License

/**
 * Add the header string to the document.
 * @param writer PdfWriter object to use.
 * @param document Document object to add the header to.
 *///w  w w  .  j av  a  2 s .  c  o m
private void addHeader(PdfWriter writer, Document document) {
    if (this.headerString == null) {
        return;
    }

    PdfContentByte cb = writer.getDirectContent();

    float textBase = document.top() + 5;
    cb.beginText();
    cb.setFontAndSize(this.baseFont, 12);
    cb.setTextMatrix(document.left(), textBase);
    cb.showText(this.headerString);
    cb.endText();
}