Java tutorial
/* * 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 johnbrooksupgrade; import java.awt.Desktop; import java.awt.Toolkit; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import org.apache.pdfbox.exceptions.COSVisitorException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap; import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage; //import classes for functionality public class PDFService extends javax.swing.JFrame { protected String Filename; protected String Date; public Maininterface mainDataEntry; private BufferedImage image2; private String Branch; private String Salesman; private final UserService userService = new UserService(); //import classes and creation of variables /** * @param mainDataEntryIn */ public PDFService(Maininterface mainDataEntryIn) { // This class constructor requires the calling class to pass a reference to itself. // That will allow each new instance of SalesInfo to know who called it. // Here, we call that calling class "mainDataEntry". mainDataEntry = mainDataEntryIn; initComponents(); //Set the date to today's by default DateInput.setText(GetCurrentDate()); userService.CreateTables(); LoadUserNames(); } /** * 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() { Save = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); ClientnameInput = new javax.swing.JTextField(); DateInput = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); ProjectNameInput = new javax.swing.JTextField(); jComboBoxBranch = new javax.swing.JComboBox(); cmbSalesPerson = new javax.swing.JComboBox(); jBAddUser = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); txtNewUser = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); Save.setText("Generate PDF"); Save.setToolTipText(""); Save.setActionCommand(""); Save.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveActionPerformed(evt); } }); jLabel1.setText("Sales Person (Existing)"); jLabel2.setText("Name of Client"); ClientnameInput.setText("Client"); jLabel3.setText("Date"); jLabel4.setText("Project Name"); ProjectNameInput.setText("Name"); jComboBoxBranch.setModel(new javax.swing.DefaultComboBoxModel( new String[] { "Branch", "Auckland", "Wellington", "Christchurch" })); jComboBoxBranch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxBranchActionPerformed(evt); } }); jBAddUser.setText("Add User"); jBAddUser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBAddUserActionPerformed(evt); } }); jLabel5.setText("Sales Person (New)"); txtNewUser.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtNewUserKeyTyped(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().addComponent(Save).addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)).addGap(45, 45, 45)) .addGroup(layout.createSequentialGroup() .addComponent(jComboBoxBranch, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(layout.createSequentialGroup() .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(68, 68, 68))) .addGroup(layout.createSequentialGroup().addComponent(jLabel5).addGap(61, 61, 61))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(DateInput, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ProjectNameInput).addComponent(cmbSalesPerson, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtNewUser, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ClientnameInput, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBAddUser))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DateInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1).addComponent(cmbSalesPerson, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtNewUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBAddUser)) .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE) .addComponent(Save)) .addGroup(layout.createSequentialGroup() .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2).addComponent( ClientnameInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4).addComponent(ProjectNameInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jComboBoxBranch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 80, Short.MAX_VALUE))))); jLabel1.getAccessibleContext().setAccessibleName("Existing Sales People"); pack(); }// </editor-fold>//GEN-END:initComponents private void jComboBoxBranchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxBranchActionPerformed int item = jComboBoxBranch.getSelectedIndex(); switch (item) { case 0: Branch = (null); break; case 1: Branch = ("AUCKLAND"); break; case 2: Branch = ("WELLINGTON"); break; case 3: Branch = ("CHRISTCHURCH"); break; } }//GEN-LAST:event_jComboBoxBranchActionPerformed private void jBAddUserActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBAddUserActionPerformed {//GEN-HEADEREND:event_jBAddUserActionPerformed // When adding a new user the existing users field should be empty and they should have // a value for the new user name if (cmbSalesPerson.getSelectedItem() == null && !txtNewUser.getText().isEmpty()) { userService.InsertUser(txtNewUser.getText()); // Reload the names now that a new name has been added LoadUserNames(); // Reset the selected item otherwise both will have a value and it might be confusing cmbSalesPerson.setSelectedItem(null); JOptionPane.showMessageDialog(null, "User added successfully.\nThis user will now be an existing sales person option.", "Successful", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "You must enter the sales person's name.", "Error!", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jBAddUserActionPerformed private void txtNewUserKeyTyped(java.awt.event.KeyEvent evt)//GEN-FIRST:event_txtNewUserKeyTyped {//GEN-HEADEREND:event_txtNewUserKeyTyped // if they're entering a new user name, we need to clear out the existing sales person combo, they can only have a value for existing or new. cmbSalesPerson.setSelectedItem(null); }//GEN-LAST:event_txtNewUserKeyTyped private void formWindowClosed(java.awt.event.WindowEvent evt)//GEN-FIRST:event_formWindowClosed {//GEN-HEADEREND:event_formWindowClosed // Clear the new user text so when they open this form again it doesn't have the // value still. txtNewUser.setText(""); }//GEN-LAST:event_formWindowClosed private void close() { WindowEvent windowclosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowclosingEvent); }//closes the window once you click save private void SaveActionPerformed(java.awt.event.ActionEvent evt) { Salesman = txtNewUser.getText().isEmpty() ? cmbSalesPerson.getSelectedItem().toString() : txtNewUser.getText(); Date = DateInput.getText(); String ClientName = ClientnameInput.getText(); String ProjectName = ProjectNameInput.getText(); if (Branch == null) { JOptionPane.showMessageDialog(null, "Please Select a branch and try again.", "Error", JOptionPane.ERROR_MESSAGE); } else { /*** * This is the logic that prints the information to a PDF ***/ //We want to save the file to Windows' temporary files folder so it can be loaded from there straight away //This temporary file is deleted when the program is exited File myfile = new File("C:\\Windows\\Temp\\ConveyorFile.pdf"); //creates a new pdf if ((myfile) != null) { try { PDDocument doc; PDPage page; doc = new PDDocument(); // Create a new blank page and add it to the document page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.COURIER_BOLD; PDPageContentStream content = new PDPageContentStream(doc, page); content.beginText(); content.setFont(font, 30); // creates a new page and gives it formatting of text content.moveTextPositionByAmount(110, 600); content.drawString("Technical Specifications "); PDFont font2 = PDType1Font.COURIER; content.setFont(font, 14); content.moveTextPositionByAmount(-50, -65); content.drawString("Date:" + Date); content.moveTextPositionByAmount(0, -14); content.drawString("Sales person: " + Salesman); content.moveTextPositionByAmount(0, -14); content.drawString("Client Name: " + ClientName); content.moveTextPositionByAmount(0, -14); content.drawString("Project Name: " + ProjectName); content.moveTextPositionByAmount(0, -14); content.drawString("Branch: " + Branch); content.moveTextPositionByAmount(0, -32); // Specifications content.setFont(PDType1Font.COURIER_BOLD, 20); content.drawString("Specifications"); content.moveTextPositionByAmount(0, -10); content.setFont(font, 14); content.moveTextPositionByAmount(10, -14); content.drawString("Speed of Belt M/pm: " + mainDataEntry.Speedofbeltanswer29f); content.moveTextPositionByAmount(0, -14); content.drawString( "Drum/Sprocket Mtrs: " + String.format("%.2f", mainDataEntry.Drumdiameterinput1)); content.moveTextPositionByAmount(0, -14); content.drawString("Metres per minute: " + mainDataEntry.getMetresperminuteanswer4f()); content.moveTextPositionByAmount(0, -14); content.drawString("Metres per hour: " + mainDataEntry.getMetresperhouranswer5f()); content.moveTextPositionByAmount(0, -14); content.drawString("Product per hour: " + mainDataEntry.getLengthperhouranswer7f()); content.moveTextPositionByAmount(0, -14); content.drawString("Kg's per hour: " + mainDataEntry.getKgsperhouranswer9f()); content.moveTextPositionByAmount(0, -14); content.drawString("Kg at any given time: " + mainDataEntry.getKgatanygiventimeanswer10f()); content.moveTextPositionByAmount(-10, -28); // Results content.setFont(PDType1Font.COURIER_BOLD, 20); content.drawString("Results"); content.moveTextPositionByAmount(0, -10); content.setFont(font, 14); content.moveTextPositionByAmount(10, -14); content.drawString("RPM: " + String.format("%.2f", mainDataEntry.getRpmconveyor34())); content.moveTextPositionByAmount(0, -14); content.drawString("Application Factor: " + mainDataEntry.getRadiananswer25f()); content.moveTextPositionByAmount(0, -14); content.drawString("Pull Force Kg/f: " + mainDataEntry.PullForce); content.moveTextPositionByAmount(0, -14); content.drawString("Nm Torque: " + mainDataEntry.getNmanswer15f()); content.moveTextPositionByAmount(0, -14); content.drawString("Service Factor: " + mainDataEntry.getServicefactor17f()); content.moveTextPositionByAmount(0, -14); content.drawString("Design Kw: " + mainDataEntry.getDesignkwanswer18f()); content.moveTextPositionByAmount(-10, -28); // Gearbox recommendations // only bother with section if the gearbox details aren't empty if (!mainDataEntry.GearboxDetailsForPDF.isEmpty()) { content.setFont(PDType1Font.COURIER_BOLD, 20); content.drawString("Gearbox/Motor Recommendations"); content.moveTextPositionByAmount(2, -25); content.setFont(PDType1Font.COURIER_BOLD, 18); content.drawString(mainDataEntry.GearboxType + ":"); content.setFont(font, 14); content.moveTextPositionByAmount(10, -25); String[] display; // For the brooks cyclo we need to split the string by these values // then write each index of the resulting array separately so the // result doesn't just run off the page display = mainDataEntry.GearboxDetailsForPDF.get(0).split("Ratio: |Overload "); // Only need to do this when the string has been split out by Ratio or Overload // i.e. this is only the case for brooks cyclo, the other two types fit the page fine if (display.length > 1) { display[1] = "Ratio: " + display[1]; content.drawString(display[0]); content.moveTextPositionByAmount(0, -14); content.drawString(display[1]); if (display.length > 2) { display[2] = "Overload " + display[2]; content.moveTextPositionByAmount(0, -14); content.drawString(display[2]); } } else { // first option must exist for the program to get this far content.drawString(mainDataEntry.GearboxDetailsForPDF.get(0)); } content.moveTextPositionByAmount(0, -14); // only bother with the second option if it exists if (mainDataEntry.GearboxDetailsForPDF.size() > 1) { display = mainDataEntry.GearboxDetailsForPDF.get(1).split("Ratio: |Overload "); if (display.length > 1) { content.moveTextPositionByAmount(0, -15); display[1] = "Ratio: " + display[1]; content.drawString(display[0]); content.moveTextPositionByAmount(0, -14); content.drawString(display[1]); if (display.length > 2) { display[2] = "Overload " + display[2]; content.moveTextPositionByAmount(0, -14); content.drawString(display[2]); } } else { content.moveTextPositionByAmount(0, -14); content.drawString(mainDataEntry.GearboxDetailsForPDF.get(1)); } } } content.endText(); image2 = ImageIO.read(new File("logosmall.jpg")); BufferedImage logo = image2; // writes the image to the file PDXObjectImage jblogo = new PDPixelMap(doc, logo); content.drawImage(jblogo, 20, 650); //postions image content.close(); doc.getDocument(); doc.save(myfile.getAbsolutePath()); // open the file Desktop.getDesktop().open(myfile); doc.close(); close(); //saves pdf and closes it } catch (IOException | COSVisitorException ie) { JOptionPane.showMessageDialog(null, ie.getMessage(), "Error!", JOptionPane.INFORMATION_MESSAGE); } } } } private String GetCurrentDate() { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date date = new Date(); return dateFormat.format(date); } private void LoadUserNames() { ArrayList<User> users = userService.GetUsers(); // Need to remove the current items so when reloading the items we // don't just add them all again on top off the ones that are there already cmbSalesPerson.removeAllItems(); for (User user : users) { cmbSalesPerson.addItem(user.GetName()); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField ClientnameInput; private javax.swing.JTextField DateInput; private javax.swing.JTextField ProjectNameInput; private javax.swing.JButton Save; private javax.swing.JComboBox cmbSalesPerson; private javax.swing.JButton jBAddUser; private javax.swing.JComboBox jComboBoxBranch; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField txtNewUser; // End of variables declaration//GEN-END:variables }