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:bouttime.report.bracketsheet.BracketSheetReport.java

License:Open Source License

public static boolean generateReport(Dao dao, List<Group> list, String outputFile, boolean doBoutNumbers,
        boolean doTimestamp) {

    if (list.isEmpty()) {
        return false;
    }/*  w ww.  j a v  a2  s  .  c o m*/

    // step 1: creation of a document-object
    Document document = new Document();

    try {

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

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

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

        String timestamp = "";
        if (doTimestamp) {
            timestamp = DateFormat.getInstance().format(new Date());
        }

        int rv;
        int i = 0;
        int size = list.size();
        for (Group g : list) {
            rv = addBracket(cb, dao, g, doBoutNumbers);
            if (rv != PAGE_ERROR) {
                // Print the watermark, if necessary
                boolean doWatermark = false;
                String gClass = g.getClassification();
                String wmValues = dao.getBracketsheetWatermarkValues();
                if ((wmValues != null) && !wmValues.isEmpty()) {
                    String[] tokens = wmValues.split(",");
                    for (String s : tokens) {
                        if (s.trim().equalsIgnoreCase(gClass)) {
                            doWatermark = true;
                            break;
                        }
                    }
                }

                int rotation = (rv == PAGE_ROUNDROBIN) ? 45 : 135;

                if (doWatermark) {
                    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);
                    ucb.showTextAligned(Element.ALIGN_CENTER, gClass, document.getPageSize().getWidth() / 2,
                            document.getPageSize().getHeight() / 2, rotation);
                    ucb.endText();
                    ucb.restoreState();
                }

                if (doTimestamp) {
                    rotation -= 45;
                    float width = cb.getPdfWriter().getPageSize().getWidth();
                    int x = (rv == PAGE_ROUNDROBIN) ? 15 : (int) (width - 15);
                    int y = 15;
                    BracketSheetUtil.drawTimestamp(cb, null, x, y, 10, timestamp, rotation);
                }

                // If not doing bout numbers, this is an 'award' type of
                // bracket.  So print an image/logo, if configured.
                if (!doBoutNumbers && (dao.getBracketsheetAwardImage() != null)
                        && !dao.getBracketsheetAwardImage().isEmpty()) {
                    Image image = Image.getInstance(Image.getInstance(dao.getBracketsheetAwardImage()));
                    image.setRotationDegrees((rv == PAGE_ROUNDROBIN) ? 0 : 90);
                    PositionOnPage positionOnPage = dao.getBracketsheetAwardImagePosition();
                    if (PositionOnPage.UPPER_RIGHT == positionOnPage) {
                        float x = (rv == PAGE_ROUNDROBIN)
                                ? document.getPageSize().getWidth() - 10 - image.getWidth()
                                : 10;
                        float y = document.getPageSize().getHeight() - 10 - image.getHeight();
                        image.setAbsolutePosition(x, y);
                        cb.addImage(image);
                    } else if (PositionOnPage.CENTER == positionOnPage) {
                        // put the image in the background, in the middle of the page
                        PdfContentByte ucb = writer.getDirectContentUnder();
                        float pageX = document.getPageSize().getWidth() / 2;
                        float pageY = document.getPageSize().getHeight() / 2;
                        float imageX = image.getWidth() / 2;
                        float imageY = image.getHeight() / 2;
                        image.setAbsolutePosition(pageX - imageX, pageY - imageY);
                        ucb.addImage(image);
                    }
                }

                if (++i < size) {
                    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.bracketsheet.CommonBracketSheet.java

License:Open Source License

public Boolean doBlankPage(FileOutputStream fos, Dao dao) {
    if (!dao.isOpen()) {
        return false;
    }/* w  ww .ja  va  2  s  .  c  o m*/

    // step 1: creation of a document-object
    Document document = new Document();

    try {

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

        // 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);

        drawBracket(cb, bf, dao, null, false);

    } 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.bracketsheet.RoundRobinBracketSheetReport.java

License:Open Source License

public static Boolean doBlankPage(FileOutputStream fos, Dao dao, Integer numWrestlers) {
    if (!dao.isOpen()) {
        return false;
    }/*  w  w  w . ja v  a  2s. com*/

    // step 1: creation of a document-object
    Document document = new Document();

    try {

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

        // 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);

        drawBracket(cb, bf, dao, null, numWrestlers);

    } 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.utility.boutsheet.BoutSheetMaker.java

License:Open Source License

/**
 * @param args the command line arguments
 *//*from   w w  w . j a  va  2 s  . co m*/
public static void main(String[] args) {
    // 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
        PdfWriter writer;
        if (args.length >= 1) {
            writer = PdfWriter.getInstance(document, new FileOutputStream(args[0]));
        } else {
            System.err.println("ERROR : Must specify output file.");
            return;
        }

        // 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;

        drawBout(cb, bf, 35, midPage - 35);
        drawBout(cb, bf, midPage + 35, pageWidth - 35);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
        return;
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        return;
    }

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

    if ((args.length == 3) && (Boolean.parseBoolean(args[2]))) {
        showPDF(args[0]);
    }
}

From source file:bouttime.utility.bracketsheet.Bracket16Maker.java

License:Open Source License

/**
 * @param args the command line arguments
 * arg0 String filename for output file/* w ww  .j  ava 2s  .com*/
 * arg1 boolean value "true" will render/show PDF file in viewer, default is false
 *
 * For example :
 *     Bracket2Maker /tmp/test.pdf true
 */
public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        PdfWriter writer;
        if (args.length >= 1) {
            writer = PdfWriter.getInstance(document, new FileOutputStream(args[0]));
        } else {
            System.err.println("ERROR : Must specify output file.");
            return;
        }

        // 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);

        drawBracket(cb, bf);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
        return;
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        return;
    }

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

    if ((args.length == 2) && (Boolean.parseBoolean(args[1]))) {
        RoundRobinBracketMaker.showPDF(args[0]);
    }
}

From source file:bouttime.utility.bracketsheet.RoundRobinBracketMaker.java

License:Open Source License

/**
 * @param args the command line arguments
 * arg0 String filename for output file// w  w w . j  a  v a 2s .c o  m
 * arg1 int number of wrestlers
 * arg2 boolean value "true" will render/show PDF file in viewer, default is false
 *
 * For example :
 *     RoundRobinBracketMaker /tmp/test.pdf 3 true
 */
public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document();

    try {

        // step 2: creation of the writer
        PdfWriter writer;
        int numWrestlers;
        if (args.length >= 2) {
            writer = PdfWriter.getInstance(document, new FileOutputStream(args[0]));
            numWrestlers = Integer.parseInt(args[1]);
        } else {
            System.err.println("ERROR : Must specify output file and number of wrestlers.");
            return;
        }

        // 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);

        drawBracket(cb, bf, numWrestlers);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
        return;
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        return;
    }

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

    if ((args.length == 3) && (Boolean.parseBoolean(args[2]))) {
        showPDF(args[0]);
    }
}

From source file:br.jus.jfpr.Divisor1.java

/**
 * Divide um arquivo inicialmente em 2, testa se o tamanho que todos
 * arquivos ficaram dentro do limite, se no ficaram apaga tudo e recomea
 * dividindo por, 3, 4, 5, etc. at que todos arquivo fiquem dentro do
 * limite// ww  w  .ja  v a2  s.  c  o m
 *
 * @param arquivoEntrada O arquivo que ser dividido
 * @param arquivoSaida O nome do arquivo que ser criado
 * @param tamArqSel Tamanho selecionado que devero ficar os arquivos
 * divididos
 * @return String informativa do resultado
 */
public static String dividePDF(File arquivoEntrada, String arquivoSaida, int tamArqSel) {

    int daPagina = 1;
    int paraPagina;
    int tamInicial;
    // FileOutputStream arquivoSair = null;
    String MensagemErro = "ok";
    int fatorDivisao = 2; //Incialmente dividir em 2
    arquivoSaida = arquivoSaida.substring(0, arquivoSaida.indexOf('.')) + "-divido"; //PAra definir o nome do arquivo de sada

    try {
        PdfReader PdfDeEntrada = new PdfReader(arquivoEntrada.getAbsolutePath()); //Para ler o arquivo de entrada
        final int totalPaginas = PdfDeEntrada.getNumberOfPages(); //Verifica o total de pginas
        tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Define o tamanho (em pginas) do 1 arquivo e em quanto dever incrementar(sero o mesmo)
        PdfImportedPage pagina;

        int i = 1; //Contador simples
        while (i <= fatorDivisao && totalPaginas > fatorDivisao) { //Enquanto no fizer todas as divises
            Document documento = new Document();
            FileOutputStream arquivoSair = new FileOutputStream(arquivoSaida + "-" + i + ".pdf"); //Cria o arquivo, vazio
            PdfWriter writer = PdfWriter.getInstance(documento, arquivoSair); //
            documento.open();
            PdfContentByte PContentByte = writer.getDirectContent();
            while (daPagina <= paraPagina) {
                documento.newPage(); //Aloca uma nova pginA
                pagina = writer.getImportedPage(PdfDeEntrada, daPagina); //Seleciona uma pgina especfica. indicada pelo contador
                PContentByte.addTemplate(pagina, 0, 0); //Adiciona a pagina ao contedo
                daPagina++; //Contador simples
            }
            arquivoSair.flush();
            documento.close(); //Grava o arquivo de sada
            arquivoSair.close();
            File arquivoDest = new File(arquivoSaida + "-" + i + ".pdf");
            if (arquivoDest.length() > tamArqSel) { // O tamanho do arquivo de destino ficou maior do que deveria
                delete(arquivoSaida, i); //Chamar a funo para deletar todos arquivos at a chave i
                daPagina = i = 1; //Para recomear tudo de novo
                fatorDivisao++; //Se um arquivo ficou maior, ento deve aumentar a diviso
                tamInicial = paraPagina = (totalPaginas / fatorDivisao) + 1; //Para recomear tudo de novo
            } else {
                i++; //Continua a divisao
                if (i == fatorDivisao) { //Ou seja, chegou a ultima divisao
                    paraPagina = totalPaginas; //O ultimo arquivo conter mais pginas
                } else {
                    paraPagina += tamInicial; //Cada arquivo ter o mesmo nmero de pginas//Incrementa sempre o tamanho inicial
                }
            }
        }
    } catch (IOException | DocumentException e) {
        System.err.println(e.getMessage());
        MensagemErro = e.getMessage();
    }
    return MensagemErro;
}

From source file:by.bsuir.group172301.matskevich.tour.util.PDFCreator.java

public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName, int col1, int col2,
        double perc) {
    PdfWriter writer = null;

    Document document = new Document();

    try {/*from  w w w .ja  v a  2 s.co  m*/
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        Paragraph paragraph = new Paragraph();
        // We add one empty line

        paragraph = new Paragraph("Results:");
        paragraph.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph);
        paragraph = new Paragraph("Test before: " + col1);
        document.add(paragraph);
        paragraph = new Paragraph("Test after: " + col2);
        document.add(paragraph);
        paragraph = new Paragraph("Percentage: " + perc);
        document.add(paragraph);
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);

        chart.draw(graphics2d, rectangle2d);

        graphics2d.dispose();
        contentByte.addTemplate(template, 150, 250);

    } catch (Exception e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:ca.sqlpower.wabit.report.LayoutToPDF.java

License:Open Source License

public void writePDF() throws DocumentException, FileNotFoundException, PrinterException {
    monitorableHelper.setStarted(true);// w  w  w .  j  a  v a 2s .c om
    int pageNum = 0;

    int numPages = layout.getNumberOfPages();
    monitorableHelper.setJobSize(numPages);
    Page page = layout.getPage();
    OutputStream out = fileOS;
    Rectangle pageSize;
    pageSize = new Rectangle(page.getWidth(), page.getHeight());

    Document pdfDoc = new Document(pageSize, 0f, 0f, 0f, 0f);

    PdfWriter pdfOut = PdfWriter.getInstance(pdfDoc, out);
    pdfDoc.open();
    pdfDoc.addCreator("Wabit " + WabitVersion.VERSION);
    PdfContentByte pdfContent = pdfOut.getDirectContent();
    Graphics2D pdfGraphics = null;
    try {
        while (pageNum < numPages) {
            monitorableHelper.checkCancelled();
            monitorableHelper.setProgress(pageNum);
            pdfGraphics = pdfContent.createGraphics(pageSize.getWidth(), pageSize.getHeight());
            int flag = layout.print(pdfGraphics, layout.getPageFormat(pageNum), pageNum);

            if (watermarker != null) {
                java.awt.Rectangle watermarkSize = new java.awt.Rectangle();
                watermarkSize.setSize(Math.round(pageSize.getWidth()), Math.round(pageSize.getHeight()));
                watermarker.watermark(pdfGraphics, watermarkSize);
            }

            pdfGraphics.dispose();
            pdfGraphics = null;

            if (flag == Printable.NO_SUCH_PAGE)
                break;

            pdfDoc.newPage();

            pageNum++;
        }
    } finally {
        if (pdfGraphics != null)
            pdfGraphics.dispose();
        if (pdfDoc != null)
            pdfDoc.close();
        monitorableHelper.setFinished(true);
    }
}

From source file:ca.uwo.csd.cs2212.team02.MainWindow.java

/**
 * Export current page to PDF/*from  w  w  w . jav a 2 s .c o  m*/
 *
 * @param jpanel Panel to be exported to PDF
 */
public void createPDF(JLayeredPane jpanel) {
    playButtonSound();
    com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(0, 0, jpanel.getWidth(),
            jpanel.getHeight());
    Document doc = new Document(r);
    String filename = fileChooser();
    if (filename != "INVALID") {
        try {
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
            doc.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(PageSize.A4.getHeight() * 2, PageSize.A4.getWidth() * 2);
            Graphics2D g2;
            g2 = tp.createGraphics(jpanel.getWidth(), jpanel.getHeight(), new DefaultFontMapper());
            jpanel.print(g2);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
            PopUpWindow saveSuccess = new PopUpWindow(filename, "Save Successful!", 8);
        } catch (Exception e) {
            new PopUpWindow("Please try again.", "Error saving file");
        }
    }
    doc.close();
}