blankpdf.BlankPDF.java Source code

Java tutorial

Introduction

Here is the source code for blankpdf.BlankPDF.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package blankpdf;

import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.attribute.standard.DateTimeAtCompleted;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

/**
 *
 * @author marcelosiedler
 */
public class BlankPDF extends javax.swing.JFrame {

    /**
     * Creates new form TestePDF
     */
    String nomepdfenviado;

    public BlankPDF() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Gera PDF");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Abre PDF");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Enviar PDF");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Abrir PDF");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup().addGap(55, 55, 55).addComponent(jButton1)
                                        .addGap(39, 39, 39).addComponent(jButton2))
                                .addGroup(layout.createSequentialGroup().addGap(24, 24, 24).addComponent(
                                        jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 362,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup().addGap(44, 44, 44).addComponent(jButton3)
                                        .addGap(18, 18, 18).addComponent(jButton4)))
                        .addContainerGap(14, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                javax.swing.GroupLayout.Alignment.TRAILING,
                layout.createSequentialGroup().addContainerGap(66, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton3).addComponent(jButton4))
                        .addGap(18, 18, 18)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(55, 55, 55)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1).addComponent(jButton2))
                        .addGap(93, 93, 93)));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        TestePDF();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        if (Desktop.isDesktopSupported()) {
            try {
                //System.getProperty("user.dir")  a raiz do projeto
                File myFile = new File(System.getProperty("user.dir") + "/Sparta.pdf");
                Desktop.getDesktop().open(myFile);
            } catch (IOException ex) {
                // no application registered for PDFs
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();
        //Abre a caixa de dilogo para selecionar o arquivo
        int res = fc.showOpenDialog(null);

        if (res == JFileChooser.APPROVE_OPTION) {
            //pegar o arquivo selecionado
            File file = fc.getSelectedFile();
            Path origem, destino;
            origem = file.toPath();
            Date d = new Date();
            nomepdfenviado = d.getTime() + ".pdf";
            InputStream is = null;
            OutputStream os = null;
            try {
                is = new FileInputStream(file);
                File f = new File(nomepdfenviado);
                f.createNewFile();

                os = new FileOutputStream(f, false); // buffer size 1K 

                byte[] buf = new byte[1024];
                int bytesRead;

                while ((bytesRead = is.read(buf)) > 0) {
                    os.write(buf, 0, bytesRead);
                }
                jButton4.setEnabled(true);
                JOptionPane.showMessageDialog(null, "Pdf copiado com sucesso");
            } catch (IOException ex) {
                Logger.getLogger(BlankPDF.class.getName()).log(Level.SEVERE, null, ex);
            }

            finally {
                try {
                    is.close();
                    os.close();
                } catch (IOException ex) {
                    Logger.getLogger(BlankPDF.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        if (Desktop.isDesktopSupported()) {
            try {
                //System.getProperty("user.dir")  a raiz do projeto
                File myFile = new File(nomepdfenviado);
                Desktop.getDesktop().open(myFile);
            } catch (IOException ex) {
                // no application registered for PDFs
            }
        }
        jButton4.setEnabled(false);
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BlankPDF.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BlankPDF.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BlankPDF.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BlankPDF.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BlankPDF().setVisible(true);
            }
        });

    }

    public void TestePDF() {
        String fileName = "Sparta.pdf"; // name of our file

        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();

        doc.addPage(page);
        PDImageXObject imagem;
        PDPageContentStream content;
        try {
            content = new PDPageContentStream(doc, page);

            //OBSERVAO IMPORTANTE --
            //Para funcionar sem tratamento de string criar o projeto em pasta sem caracteres
            //especiais nem ESPAO EM BRANCO
            imagem = PDImageXObject.createFromFile(getClass().getResource("sparta.png").getPath(), doc);
            ///Users/marcelosiedler/Google%20Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/silviosantos.jpg
            //imagem = PDImageXObject.createFromFile("/Users/marcelosiedler/Google Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/sparta.png", doc);

            content.beginText();
            content.setFont(PDType1Font.TIMES_BOLD, 26);
            content.newLineAtOffset(10, 750);
            content.showText("Gincana IFSUL2");
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.TIMES_BOLD, 16);
            content.newLineAtOffset(80, 700);
            content.showText("Turma : ");
            content.endText();

            content.drawImage(imagem, 75, 500);

            content.close();
            doc.save(fileName);
            doc.close();

            System.out.println("Arquivo criado em : " + System.getProperty("user.dir"));

        } catch (Exception e) {

            System.out.println(e.getMessage());

        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables
}