Example usage for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject createFromFile

List of usage examples for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject createFromFile

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject createFromFile.

Prototype

public static PDImageXObject createFromFile(String imagePath, PDDocument doc) throws IOException 

Source Link

Document

Create a PDImageXObject from an image file, see #createFromFileByExtension(File,PDDocument) for more details.

Usage

From source file:org.esteco.jira.pdf.AddImageToPDF.java

License:Apache License

/**
 * Add an image to an existing PDF document.
 *
 * @param inputFile  The input PDF to add the image to.
 * @param imagePath  The filename of the image to put in the PDF.
 * @param outputFile The file to write to the pdf to.
 * @throws IOException If there is an error writing the data.
 *//*  w w w . ja v a  2s  .  c  o m*/
public void createPDFFromImage(String inputFile, String imagePath, String outputFile) throws IOException {
    // the document
    PDDocument doc = null;
    try {
        doc = PDDocument.load(new File(inputFile));

        //we will add the image to the first page.
        PDPage page = doc.getPage(0);
        //page.setRotation(90);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage,
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 0.4f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

        contentStream.close();
        doc.save(outputFile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:stepReport.reports.model.savePDFModel.java

public void savePDFSemanal(File file, String[][] matrizDados) {

    if (matrizDados == null)
        return;// ww  w . j a v  a  2 s .c  o m

    //Cria o documento
    PDDocument document = new PDDocument();

    //Vou criando as paginas dinamicamente de acordo com o numero de registros a serem impressos.
    //Para cada 25 registros, crio uma nova pagina
    //O valor de k vai ser atualizado durante o loop de impressao de registros,
    //assim como o loop de impressao de registro comeca a partir do valor de k
    int k = 1;
    int pagina = 0;
    while (k < matrizDados.length) {
        //Variavel com o numero da pagina
        pagina++;
        //Adiciona uma pagina
        PDPage page = new PDPage();
        //Configura o padrao de tamanho da pagina
        page.setMediaBox(PDRectangle.A4);
        //Configura a orientacao
        page.setRotation(90);
        //Adiciona a pagina ao documento
        document.addPage(page);
        PDFont font;
        //Obtem a largura da pagina
        float pageWidth = page.getMediaBox().getWidth();

        try {
            //abre o buffer pra edicao da pagina
            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            //Gira a pagina em 90 graus
            contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));

            PDImageXObject pdImage = PDImageXObject.createFromFile("./step2.png", document);

            contentStream.drawImage(pdImage, 30, 520);

            //Define a cor da letra
            contentStream.setNonStrokingColor(Color.BLACK);
            //Abre pra edicao escrita
            contentStream.beginText();

            //Configura a fonte de titulo e o tamanho no buffer
            font = PDType1Font.COURIER_BOLD;
            contentStream.setFont(font, 18);
            contentStream.setLeading(14.5f);

            contentStream.newLineAtOffset(250, 530);
            contentStream.showText("Resumo de Horas semanais");

            //Imprime o numero da pagina
            font = PDType1Font.COURIER;
            contentStream.setFont(font, 12);

            contentStream.newLineAtOffset(490, 0);
            contentStream.showText("Pag " + Integer.toString(pagina));

            //Define o ponto de partida em X e Y
            contentStream.newLineAtOffset(-700, -50);
            //Define a fonte do cabecalho
            font = PDType1Font.COURIER_BOLD;
            contentStream.setFont(font, 12);
            //carrega o cabecalho com nome, profissao, itera pra cada data da semana e depois o total
            String titulo = StringUtils.rightPad("Nome", 20) + StringUtils.rightPad("Profissao", 16);
            for (int i = 2; i < matrizDados[0].length; i++)
                titulo += matrizDados[0][i] + "  ";

            //Escreve o cabecalho
            contentStream.showText(titulo);
            //Troca a fonte pra normal
            font = PDType1Font.COURIER;
            contentStream.setFont(font, 12);
            //TODO criar loop duplo para criar pagina e depois imprimir o dado enquanto houver dados a serem impressos
            contentStream.newLine();

            //Para cada linha da matriz recebida, vou formatar os campos nome, profissao, cada data da semana e o total pra imprimir na linha
            //Tenho que comecar a partir de k porque pode nao ser a primeira pagina. 

            //Configuro o limite baseado se eu estou ou nao na ultima pagina
            int limite = (k + savePDFModel.REGISTROS_PAGINA < matrizDados.length - 1)
                    ? savePDFModel.REGISTROS_PAGINA
                    : matrizDados.length - k;

            for (int i = 0; i < limite; i++) {
                String nome = this.formatName(matrizDados[i + k][0]);
                String profissao = this.formatProfissao(matrizDados[i + k][1]);
                String linha = nome + profissao;
                for (int j = 2; j < matrizDados[i].length; j++)
                    linha += StringUtils.rightPad(matrizDados[i + k][j], 10);

                contentStream.showText(linha);
                contentStream.newLine();
            }
            k += limite;

            //Imprime o total em negrito quando chega no final
            System.out.println(k);
            if (k >= matrizDados.length) {
                font = PDType1Font.COURIER_BOLD;
                contentStream.setFont(font, 12);
                Double[] totais = new Double[matrizDados[0].length - 2];
                for (int i = 0; i < totais.length; i++)
                    totais[i] = 0.0;

                for (int i = 1; i < matrizDados.length; i++) {
                    for (int j = 2; j < matrizDados[i].length; j++) {
                        if (!matrizDados[i][j].equals(""))
                            totais[j - 2] += Double.parseDouble(matrizDados[i][j]);
                    }
                }
                String linhaTot = StringUtils.rightPad("Totais", 36);
                for (int i = 0; i < totais.length; i++) {
                    linhaTot += StringUtils.rightPad(totais[i].toString(), 10);
                }
                contentStream.showText(linhaTot);
                //Imprime a linha de assinatura
                this.signatureLine(contentStream);
            }
            contentStream.endText();
            contentStream.close();

        } catch (javax.imageio.IIOException ex) {
            JOptionPane.showMessageDialog(new JFrame(), "Imagem step2.png no encontrada");
            return;
        } catch (IOException ex) {
            Logger.getLogger(savePDFModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        //Esse save vai dentro do loop?
        document.save(file);
        document.close();
    } catch (IOException ex) {
        Logger.getLogger(savePDFModel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:uia.pdf.gridbag.model.ImageCell.java

License:Apache License

@Override
public void accept(ContentView cv, GridBagDrawer view, PDPageContentStream contentStream, Point bottomLeft,
        Map<String, Object> data) {
    PDImageXObject img = null;/*from w  w w  .  j  av  a  2 s .c  o  m*/
    try {
        img = PDImageXObject.createFromFile(this.fileName, cv.getDoc().getDocument());
        float pct = (float) getHeight() / (float) img.getHeight();
        contentStream.drawImage(img, bottomLeft.x, bottomLeft.y, img.getWidth() * pct, img.getHeight() * pct);
    } catch (Exception ex) {

    }
}

From source file:uia.pdf.PDFMakerTest.java

License:Apache License

@Test
public void justTest() throws Exception {
    PDDocument doc = new PDDocument();
    try {//from  w ww. jav a  2  s  .com
        PDPage page = new PDPage();
        doc.addPage(page);

        PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false, false);
        contents.moveTo(20, 650);
        contents.lineTo(500, 650);
        contents.stroke();
        contents.close();

        PDImageXObject pdImage = PDImageXObject
                .createFromFile(PDFMakerTest.class.getResource("sample.jpg").getFile(), doc);
        contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false, false);
        contents.drawImage(pdImage, 20, 700);
        contents.close();

        contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false, false);
        contents.moveTo(20, 550);
        contents.lineTo(500, 550);
        contents.stroke();
        contents.close();

        doc.save("C:\\TEMP\\IMAGE.PDF");
    } finally {
        doc.close();
    }

}

From source file:Utils.PDF.java

public static void print(String nFactura, Date fecha, String empleado, ClienteVO cliente,
        List<ProductosCanasta> productos, BigDecimal subtotal) throws IOException {
    DateFormat dateAnio = new SimpleDateFormat("yyyy");
    DateFormat dateMes = new SimpleDateFormat("MM");
    DateFormat dateDia = new SimpleDateFormat("dd");
    String direccion = "facturas" + "/" + dateAnio.format(fecha) + "/" + dateMes.format(fecha) + "/"
            + dateDia.format(fecha);/*w w  w  . j  a  v  a  2  s . c o  m*/
    File dir = new File(direccion);
    if (dir.exists()) {
        System.out.println("Ya exitiste la carpeta");
    } else {
        dir.mkdirs();
    }
    DateFormat dateF = new SimpleDateFormat("kk-mm-ss_dd-MM-yyyy");
    String fileName = direccion + "/" + dateF.format(fecha) + ".pdf";
    String imagem = "bill-512.png";
    System.out.println("Se creo su factura");
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A4);
    PDPageContentStream content = new PDPageContentStream(doc, page);
    doc.addPage(page);

    PDImageXObject pdImage = null;
    try {
        pdImage = PDImageXObject.createFromFile(imagem, doc);
    } catch (IOException e1) {
        System.out.println("ERROR no cargo logo factura");
    }
    float scale = 0.2f;

    // Titulo factura     
    content.beginText();
    content.setFont(PDType1Font.HELVETICA, 26);
    content.setNonStrokingColor(Color.BLUE);
    content.newLineAtOffset(250, 785);
    content.showText("Factura Bazar A&J");
    content.endText();

    // Logo
    content.drawImage(pdImage, 30, 725, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

    //Cuadro info empresa
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(25, 700, 280, 1);
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(304, 700, 1, -65);
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(25, 634, 280, 1);
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(25, 700, 1, -65);
    content.fill();

    // Texto info empresa
    content.beginText();
    content.setLeading(15); // da el salto de pagina
    content.setFont(PDType1Font.COURIER, 10);
    content.newLineAtOffset(30, 685);
    content.showText("Direccion: " + "Coop. Universitaria Mz 258 Solar 9");
    content.newLine();
    content.showText("Ciudad   : " + "Guayaquil, Ecuador");
    content.newLine();
    content.showText("Telefono : " + "042937914");
    content.newLine();
    content.showText("RUC      : " + "1710034065");
    content.endText();

    //Cuadro datos factura
    content.setNonStrokingColor(Color.BLACK); //arriba
    content.addRect(380, 700, 200, 1);
    content.setNonStrokingColor(Color.BLACK); // derecha
    content.addRect(579, 700, 1, -65);
    content.setNonStrokingColor(Color.BLACK); // abajo
    content.addRect(380, 634, 200, 1);
    content.setNonStrokingColor(Color.BLACK); // izquierda
    content.addRect(380, 700, 1, -65);
    content.fill();

    DateFormat dateFormat = new SimpleDateFormat("dd - MM - yyyy");
    DateFormat dateFormath = new SimpleDateFormat("h:mm a");
    // Texto datos factura
    content.beginText();
    content.setLeading(15); // da el salto de pagina
    content.setFont(PDType1Font.COURIER, 10);
    content.newLineAtOffset(390, 685);
    content.showText("Factura N: " + nFactura);
    content.newLine();
    content.showText("Fecha    : " + dateFormat.format(fecha));
    content.newLine();
    content.showText("Hora     : " + dateFormath.format(fecha));
    content.newLine();
    content.showText("Empleado : " + empleado);
    content.endText();

    // Linea Divisoria
    content.setNonStrokingColor(Color.BLUE); // abajo
    content.addRect(0, 620, 595, 1);
    content.fill();

    // Datos Cliente
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER, 13);
    content.newLineAtOffset(30, 600);
    content.showText("Nombre   : " + cliente.getNombre_C() + cliente.getApellido_C());
    content.newLine();
    content.showText("Direcion : " + cliente.getDireccion_C());
    content.newLine();
    content.showText("Telefono : " + cliente.getConvencional_C());
    content.endText();

    content.setNonStrokingColor(Color.BLUE); // abajo
    content.addRect(0, 550, 595, 1);
    content.fill();

    content.setNonStrokingColor(Color.BLACK); // numero
    content.addRect(30, 510, 50, 15);
    content.fill();
    content.beginText();
    content.setLeading(0);
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(45, 515);
    content.showText("N.");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // cantidad
    content.addRect(90, 510, 40, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(94, 515);
    content.showText("Cant");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // Descripcion
    content.addRect(140, 510, 270, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(230, 515);
    content.showText("Descripcion");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // cantidad
    content.addRect(430, 510, 70, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(440, 515);
    content.showText("P.Unit");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // importe
    content.addRect(510, 510, 70, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(515, 515);
    content.showText("Importe");
    content.endText();

    int cont = 1;
    int vertical = 490;
    // Productos
    for (ProductosCanasta p : productos) {
        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(45, vertical);
        content.showText("" + cont);
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(105, vertical);
        content.showText("" + p.getCantidad());
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 11);
        content.newLineAtOffset(145, vertical);
        content.showText("" + p.getNombre());
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(440, vertical);
        content.showText("" + p.getPrecio_venta());
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(520, vertical);
        content.showText("" + p.getPrecio_venta().multiply(new BigDecimal(p.getCantidad())));
        content.endText();

        cont++;
        vertical -= 20;
    }

    // max x pagina 595 x 841.8898
    content.setNonStrokingColor(Color.BLUE); // total
    content.addRect(0, 60, 595, 1);
    content.fill();

    /// TOTAL
    content.beginText();
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER_BOLD, 20);
    content.newLineAtOffset(500, 35);
    content.showText(subtotal.multiply(new BigDecimal(0.14)).add(subtotal).setScale(2, 3).toString());
    content.endText();

    content.beginText();
    content.newLineAtOffset(510, 20);
    content.setFont(PDType1Font.COURIER_BOLD, 15);
    content.showText("TOTAL");
    content.endText();

    // IVA
    content.beginText();
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER_BOLD, 20);
    content.newLineAtOffset(430, 35);
    content.showText("" + 14 + "%");
    content.endText();

    content.beginText();
    content.newLineAtOffset(430, 20);
    content.setFont(PDType1Font.COURIER_BOLD, 15);
    content.showText("IVA");
    content.endText();

    // Subtotal
    content.beginText();
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER_BOLD, 20);
    content.newLineAtOffset(300, 35);
    content.showText(subtotal.toString());
    content.endText();

    content.beginText();
    content.newLineAtOffset(300, 20);
    content.setFont(PDType1Font.COURIER_BOLD, 15);
    content.showText("SUBTOTAL");
    content.endText();

    content.close();
    doc.save(fileName);
    doc.close();
    Process p = Runtime.getRuntime().exec(new String[] { "xpdf", fileName });
    System.out.println("your file created in : " + System.getProperty("user.dir"));
}