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

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

Introduction

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

Prototype

public void addTemplate(final PdfTemplate template, final double x, final double y) 

Source Link

Document

Adds a template to this content.

Usage

From source file:jasperSoft.MergePDF.java

/**
 * /*from   w  w  w  .jav a 2  s . c  o m*/
 * @param streamOfPDFFiles
 * @param outputStream
 * @param paginate 
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:jati.GerandoArquivoCarimbado.java

public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN)
        throws InvalidPdfException, IOException {
    //Copiando arquivo informado.

    try {/*ww  w  . ja  v a 2 s .c  o m*/

        // Adicionado parametro para nao retornar erro quando o documento for protegido.
        PdfReader.unethicalreading = true;

        PdfWriter writer = PdfWriter.getInstance(montaraAquivo(caminhoarquivo),
                new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));
        // ABRE O DOCUMENTO CRIADO PARA MANUSEIO
        montaraAquivo(caminhoarquivo).open();

        //SUBSTRING RETIRA PARTE DO TEXTO ENTRE OS INDICES ESPECIFICADOS 
        //caminhoDestino RECEBE UM NOVO CAMINHO RESULTANTE DOS INDICES DE CAMINHO.LENGTH - BN.LENGTH
        // QUE FORMAM UMA NOVA STRING
        String caminhodestino = (caminhoarquivo.substring(0, caminhoarquivo.length() - BN.length()));

        File destinooriginal = new File(caminhodestino + "ORIGINAL\\");
        if (!destinooriginal.exists()) {
            destinooriginal.mkdir();
        }

        caminhodestino = (caminhodestino + "ORIGINAL\\" + BN);

        //TESTANDO NOVA FORMA DE COPIAR
        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);

        FileInputStream fis = new FileInputStream(origem);
        FileOutputStream fos = new FileOutputStream(destino);

        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();

        long transferFrom = outChannel.transferFrom(inChannel, 0, inChannel.size());

        fis.close();
        fos.close();
        inChannel.close();
        outChannel.close();

        // Thread.sleep(10);
        BN = BN.substring(0, BN.length() - 4);

        PdfContentByte cb = writer.getDirectContent();

        int i = 0;
        while (i < reader.getNumberOfPages()) {
            montaraAquivo(caminhodestino).newPage();

            i++;

            //PDFCONTETBYTE GERA UMA ESPECIE DE CODIGO DE BARRAS 
            PdfContentByte under = writer.getDirectContentUnder();
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 0, i * 0.2f);

            //CARIMBO DA BN
            BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            cb.beginText();
            cb.setFontAndSize(bf, 14);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
            cb.endText();

        }

        montaraAquivo(caminhodestino).close();
        writer.close();
        reader.close();
        origem.delete();

    } catch (IOException | DocumentException ex) {
    }

}

From source file:Login.ventas.fproyectos.java

public void fondos(Document documento, PdfContentByte canvas) {
    try {// ww w  .ja  va2  s.c o m
        Image imghead = Image.getInstance(usuario.getDireccion() + "/plantilla.jpg");
        imghead.setAbsolutePosition(0, 0);
        imghead.setAlignment(Image.ALIGN_CENTER);
        float scaler = ((documento.getPageSize().getWidth() - documento.leftMargin() - documento.rightMargin())
                / imghead.getWidth()) * 100;
        imghead.scalePercent(scaler);
        PdfTemplate tp = canvas.createTemplate(PageSize.A4.getWidth(), PageSize.A4.getHeight()); //el rea destinada para el encabezado
        tp.addImage(imghead);
        x = (int) imghead.getWidth();
        y = (int) imghead.getHeight();
        canvas.addTemplate(tp, 0, 0);//posicin del tmplate derecha y abajo
    } catch (IOException | DocumentException io) {

    }
}

From source file:matheos.texte.OngletTexte.java

License:Open Source License

public void export2Pdf(final File f) {
    final Formatter formatter = editeur.getFormatter();
    new Thread(new Runnable() {
        @Override//from   w w  w.  j ava2 s . co  m
        public void run() {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(f);
                Document document = new Document();
                Book book = formatter.createBook();

                try {
                    PdfWriter writer = PdfWriter.getInstance(document, fos);
                    document.open();
                    PdfContentByte canvas = writer.getDirectContent();
                    for (int i = 0; i < book.getNumberOfPages(); i++) {
                        document.newPage();
                        PageFormat page = book.getPageFormat(i);
                        PdfTemplate templ = canvas.createTemplate((float) page.getWidth(),
                                (float) page.getHeight());
                        Graphics2D g2 = templ.createGraphics((float) page.getWidth(), (float) page.getHeight());
                        try {
                            book.getPrintable(i).print(g2, book.getPageFormat(i), i);
                        } catch (PrinterException ex) {
                            Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        canvas.addTemplate(templ, 0, 0);
                        g2.dispose();
                    }
                } catch (DocumentException ex) {
                    Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    document.close();
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException ex) {
                        Logger.getLogger(OngletTexte.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }).start();
}

From source file:net.algem.edition.PdfHandler.java

License:Open Source License

public void createPdf(String fileName, ByteArrayOutputStream out, short templateType)
        throws IOException, DocumentException {
    try {/*from w w  w.java2 s  .  c  o m*/
        File tmpFile = File.createTempFile(fileName, ".pdf");
        final String target = tmpFile.getPath();
        PageTemplate pt = getTemplate(templateType);
        PdfReader reader = new com.itextpdf.text.pdf.PdfReader(out.toByteArray());
        if (pt != null) {
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));
            //        PdfStamper stamper = new PdfStamper(reader, new PrintStream(new FileOutputStream(target), true, "UTF-8"));
            PdfReader model = new com.itextpdf.text.pdf.PdfReader(pt.getContent());
            PdfImportedPage importedPage = stamper.getImportedPage(model, 1);
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                PdfContentByte canvas = stamper.getUnderContent(i);
                canvas.addTemplate(importedPage, 0, 0);
            }

            stamper.getWriter().freeReader(model);
            model.close();
            stamper.close();
        } else {
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));
            //PdfStamper stamper = new PdfStamper(reader, new PrintStream(new FileOutputStream(target), true, "UTF-8"));
            stamper.close();
        }

        preview(target, null);
    } catch (SQLException ex) {
        GemLogger.logException(ex);
    }
}

From source file:net.pickapack.chart.ChartPdfExporter.java

License:Open Source License

/**
 * Export the specified chart to the specified PDF file.
 *
 * @param chart the chart/*w  ww  .j a va  2s .co  m*/
 * @param width the width of the PDF file
 * @param height the height of the PDF file
 * @param fileName the PDF file name
 */
public static void exportPdf(JFreeChart chart, int width, int height, String fileName) {
    try {
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.sf.mzmine.chartbasics.graphicsexport.ChartExportUtil.java

License:Open Source License

/**
 * This method saves a chart as a PDF with given dimensions
 * //from   w w  w .j  a  v a 2s  . c o m
 * @param chart
 * @param width
 * @param height
 * @param fileName is a full path
 */
public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception {
    PdfWriter writer = null;

    Document document = new Document(new Rectangle(width, height));

    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        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, 0, 0);

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

From source file:nz.ac.waikato.cms.doc.OverlayFilename.java

License:Open Source License

/**
 * Performs the overlay.//from w  w w .  j a  va2s  . c  o  m
 *
 * @param input   the input file/dir
 * @param output   the output file/dir
 * @param vpos   the vertical position
 * @param hpos   the horizontal position
 * @param stripPath   whether to strip the path
 * @param stripExt   whether to strip the extension
 * @param pages   the array of pages (1-based) to add the overlay to, null for all
 * @param evenPages   whether to enforce even pages in the document
 * @return      true if successfully overlay
 */
public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt,
        int[] pages, boolean evenPages) {
    PdfReader reader;
    PdfStamper stamper;
    FileOutputStream fos;
    PdfContentByte canvas;
    int i;
    String text;
    int numPages;
    File tmpFile;
    Document document;
    PdfWriter writer;
    PdfImportedPage page;
    PdfContentByte cb;

    reader = null;
    stamper = null;
    fos = null;
    numPages = -1;
    try {
        reader = new PdfReader(input.getAbsolutePath());
        fos = new FileOutputStream(output.getAbsolutePath());
        stamper = new PdfStamper(reader, fos);
        numPages = reader.getNumberOfPages();
        if (pages == null) {
            pages = new int[reader.getNumberOfPages()];
            for (i = 0; i < pages.length; i++)
                pages[i] = i + 1;
        }

        if (stripPath)
            text = input.getName();
        else
            text = input.getAbsolutePath();
        if (stripExt)
            text = text.replaceFirst("\\.[pP][dD][fF]$", "");

        for (i = 0; i < pages.length; i++) {
            canvas = stamper.getOverContent(pages[i]);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f);
        }
    } catch (Exception e) {
        System.err.println("Failed to process " + input + ":");
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (reader != null)
                reader.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
            // ignored
        }
    }

    // enforce even pages?
    if (evenPages && (numPages > 0) && (numPages % 2 == 1)) {
        reader = null;
        fos = null;
        writer = null;
        tmpFile = new File(output.getAbsolutePath() + "tmp");
        try {
            if (!output.renameTo(tmpFile)) {
                System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!");
                return false;
            }
            reader = new PdfReader(tmpFile.getAbsolutePath());
            document = new Document(reader.getPageSize(1));
            fos = new FileOutputStream(output.getAbsoluteFile());
            writer = PdfWriter.getInstance(document, fos);
            document.open();
            document.addCreationDate();
            document.addAuthor(System.getProperty("user.name"));
            cb = writer.getDirectContent();
            for (i = 0; i < reader.getNumberOfPages(); i++) {
                page = writer.getImportedPage(reader, i + 1);
                document.newPage();
                cb.addTemplate(page, 0, 0);
            }
            document.newPage();
            document.add(new Paragraph(" ")); // fake content
            document.close();
        } catch (Exception e) {
            System.err.println("Failed to process " + tmpFile + ":");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                // ignored
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                // ignored
            }
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                // ignored
            }
            if (tmpFile.exists()) {
                try {
                    tmpFile.delete();
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    }

    return true;
}

From source file:nz.ac.waikato.cms.supernova.io.PDF.java

License:Open Source License

/**
 * Generates the intermediate data structure.
 *
 * @param test      the test results (measure - [score, percentile])
 * @param angle      the angle to use//from   ww  w .  jav a 2  s . c  o m
 * @param numFlips      the number of flips
 * @param overallFlipCycles   the overall flip cycles
 * @param errors      for storing error messages
 * @return         null if successfully generated, otherwise error message
 */
public ByteArrayOutputStream generatePlot(Map<String, List<Double>> test, double angle,
        Map<String, Integer> numFlips, int overallFlipCycles, StringBuilder errors) {
    ByteArrayOutputStream result;
    Document document;
    PdfWriter writer;
    PdfContentByte canvas;
    PdfTemplate template;
    Graphics2D g;

    result = new ByteArrayOutputStream();
    g = null;
    document = null;
    try {
        document = new Document(new Rectangle(m_Width, m_Height));
        writer = PdfWriter.getInstance(document, result);
        document.open();
        canvas = writer.getDirectContent();
        template = canvas.createTemplate(m_Width, m_Height);
        g = new PdfGraphics2D(template, m_Width, m_Height);
        draw(g, test, angle, numFlips, overallFlipCycles, errors);
        canvas.addTemplate(template, 0, 0);
    } catch (Exception e) {
        errors.append(Utils.throwableToString(e));
    } finally {
        try {
            if (g != null)
                g.dispose();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (document != null)
                document.close();
        } catch (Exception e) {
            // ignored
        }
    }

    return result;
}

From source file:org.fhaes.fhsamplesize.view.SSIZCurveChart.java

License:Open Source License

/**
 * Save chart as PDF file. Requires iText library.
 * /*from  w ww  .j  av a  2 s .c om*/
 * @param chart JFreeChart to save.
 * @param fileName Name of file to save chart in.
 * @param width Width of chart graphic.
 * @param height Height of chart graphic.
 * @throws Exception if failed.
 * @see <a href="http://www.lowagie.com/iText">iText</a>
 */
@SuppressWarnings("deprecation")
public static void writeAsPDF(File fileToSave, int width, int height) throws Exception {

    if (chart != null) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(fileToSave.getAbsolutePath()));

            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            Document document = new Document(pagesize, 50, 50, 50, 50);
            try {
                PdfWriter writer = PdfWriter.getInstance(document, out);
                document.addAuthor("JFreeChart");
                document.open();

                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());

                Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
                chart.draw(g2, r2D, null);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
            } finally {
                document.close();
            }
        } finally {
            if (out != null)
                out.close();
        }
    }
}