my.charpdf.DandDcharPDFUI.java Source code

Java tutorial

Introduction

Here is the source code for my.charpdf.DandDcharPDFUI.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 my.charpdf;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/* * * * * * * * * * * * * * * * * * * * * * * *
Added by D. Berkompas
* * * * * * * * * * * * * * * * * * * * * * * */
//import javax.xml.parsers.DocumentBuilderFactory;
//import javax.xml.parsers.DocumentBuilder;
//import org.w3c.dom.Document;
//import org.w3c.dom.NodeList;
//import org.w3c.dom.Node;
//import org.w3c.dom.Element;
//import java.io.File;

//import javax.xml.parsers.ParserConfigurationException;
//import javax.xml.transform.Transformer;
//import javax.xml.transform.TransformerException;
//import javax.xml.transform.TransformerFactory;
//import javax.xml.transform.dom.DOMSource;
//import javax.xml.transform.stream.StreamResult;

//import org.w3c.dom.Attr;
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;

//import java.io.BufferedWriter;
//import java.io.File;
//import java.io.FileWriter;
//import java.io.IOException;
import java.io.FileOutputStream;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

//import java.net.URLEncoder;
//import java.util.Arrays;
//import javax.xml.parsers.DocumentBuilder;
//import javax.xml.parsers.DocumentBuilderFactory;
//import org.w3c.dom.Document;
//import org.w3c.dom.NamedNodeMap;
//import org.w3c.dom.Node;
//import org.w3c.dom.NodeList;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.util.Set;
/* * * * * * * * * * * * * * * * * * * * * * * *
Added by D. Berkompas
* * * * * * * * * * * * * * * * * * * * * * * */

/**
 *
 * @author dberkompas
 */
public class DandDcharPDFUI extends javax.swing.JFrame {

    /**
     * Creates new form CandCcharConvertUI
     */
    public DandDcharPDFUI() {
        initComponents();

        // REMOVE THIS LINE, IT'S FOR TESTING ONLY
        //jTextField1.setText("C:\\cygwin\\home\\dberkompas\\herolab\\characters\\ElvenRanger8.xml");
        //jTextField1.setText("C:\\cygwin64\\home\\David\\herolab\\characters\\HumanFighter2.xml");
        //jTextField1.setText("C:\\cygwin\\home\\dberkompas\\herolab\\characters\\HalfOrcMonk5.xml");
        //jTextField1.setText("C:\\cygwin\\home\\dberkompas\\herolab\\characters\\HumanFighter2.xml");
        //jTextField1.setText("C:\\cygwin64\\home\\David\\herolab\\characters\\HalflingWizard3.xml");
        //jTextField1.setText("C:\\cygwin64\\home\\David\\herolab\\characters\\DwarfCleric9.xml");
        jTextField1.setText("C:\\FGchars\\Barakas-FGout.xml");
    }

    /**
     * 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() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Input XML:");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

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

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

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel2.setText("Dungeons & Dragons FG output to PDF");

        jButton3.setText("Exit");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(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().addContainerGap().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup().addComponent(jButton1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton3))
                                .addGroup(layout.createSequentialGroup().addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addComponent(jLabel1)
                                                .addGap(18, 18, 18)
                                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        164, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18).addComponent(jButton2,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 42,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 260,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(6, 6, 6).addComponent(jLabel2).addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButton1).addComponent(jButton3))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Fantasy Grounds XML output", "xml");
        chooser.setFileFilter(filter);
        int thisValue = chooser.showOpenDialog(this);
        if (thisValue == 0) {
            String filePathName;
            filePathName = chooser.getSelectedFile().getPath();
            jTextField1.setText(filePathName);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton3ActionPerformed

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        String inputFile;
        inputFile = jTextField1.getText().replace("\n", "").replace("\r", "");
        String pcName = "";
        String pcRace = "";
        String pcAlign = "";
        String pcBackG = "";
        String pcExp = "";
        String pcProfBonus = "";
        String pcStrScore = "";
        String pcStrMod = "";
        String pcDexScore = "";
        String pcDexMod = "";
        String pcConScore = "";
        String pcConMod = "";
        String pcIntScore = "";
        String pcIntMod = "";
        String pcWisScore = "";
        String pcWisMod = "";
        String pcChaScore = "";
        String pcChaMod = "";
        String pcClassLevel = "";
        String pcPerc = "";
        if (!inputFile.equals("")) {
            try {
                Builder parser = new Builder();
                Document doc = parser.build("file:///" + inputFile);

                Element root = doc.getRootElement();
                Elements character = root.getChildElements();

                pcName = character.get(0).getFirstChildElement("name").getValue();
                pcRace = character.get(0).getFirstChildElement("race").getValue();
                pcExp = character.get(0).getFirstChildElement("exp").getValue();
                pcAlign = character.get(0).getFirstChildElement("alignment").getValue();
                pcBackG = character.get(0).getFirstChildElement("background").getValue();
                pcProfBonus = character.get(0).getFirstChildElement("profbonus").getValue();
                pcPerc = character.get(0).getFirstChildElement("perception").getValue();

                //Integer numChildren = character.get(0).getChildCount();
                //System.out.println(numChildren);

                Elements pcAttrs = character.get(0).getChildElements("abilities").get(0).getChildElements();
                Elements pcClasses = character.get(0).getChildElements("classes").get(0).getChildElements();

                for (int i = 0; i < pcAttrs.size(); i++) {
                    if (pcAttrs.get(i).getLocalName().equals("strength")) {
                        pcStrScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                        pcStrMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                    } else if (pcAttrs.get(i).getLocalName().equals("dexterity")) {
                        pcDexScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                        pcDexMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                    } else if (pcAttrs.get(i).getLocalName().equals("constitution")) {
                        pcConScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                        pcConMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                    } else if (pcAttrs.get(i).getLocalName().equals("intelligence")) {
                        pcIntScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                        pcIntMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                    } else if (pcAttrs.get(i).getLocalName().equals("wisdom")) {
                        pcWisScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                        pcWisMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                    } else if (pcAttrs.get(i).getLocalName().equals("charisma")) {
                        pcChaScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                        pcChaMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                    }
                }

                for (int i = 0; i < pcClasses.size(); i++) {
                    // Gets the list of classes
                    //System.out.println(pcClasses.get(i).getLocalName());
                    String tempClass = pcClasses.get(i).getChildElements("name").get(0).getValue();
                    String tempLevel = pcClasses.get(i).getChildElements("level").get(0).getValue();
                    pcClassLevel += tempClass + " " + tempLevel + " / ";
                }
                pcClassLevel = pcClassLevel.substring(0, pcClassLevel.length() - 2);

                //for(i = 0; i < numClasses; i++) {
                //    System.out.println(charac);
                //}

                String inputTemplate = "resources/DandD5e-template.pdf";

                String outputPDF = "resources/" + pcName + ".pdf";

                PdfReader reader = new PdfReader(inputTemplate);
                PdfStamper stamper;
                stamper = new PdfStamper(reader, new FileOutputStream(outputPDF));
                AcroFields form = reader.getAcroFields();

                Set<String> fields = form.getFields().keySet();

                for (String key : fields) {
                    //System.out.println(key);
                    switch (form.getFieldType(key)) {
                    case AcroFields.FIELD_TYPE_CHECKBOX:
                        //System.out.println(key + ": Checkbox");
                        break;
                    case AcroFields.FIELD_TYPE_COMBO:
                        //System.out.println(key + ": Combo");
                        break;
                    case AcroFields.FIELD_TYPE_LIST:
                        //System.out.println(key + ": List");
                        break;
                    case AcroFields.FIELD_TYPE_NONE:
                        //System.out.println(key + ": None");
                        break;
                    case AcroFields.FIELD_TYPE_PUSHBUTTON:
                        //System.out.println(key + ": Pushbutton");
                        break;
                    case AcroFields.FIELD_TYPE_RADIOBUTTON:
                        //System.out.println(key + ": Radio");
                        break;
                    case AcroFields.FIELD_TYPE_SIGNATURE:
                        //System.out.println(key + ": Signature");
                        break;
                    case AcroFields.FIELD_TYPE_TEXT:
                        //System.out.println(key + ": Text");
                        break;
                    default:
                        //System.out.println(key + ": ???");
                    }
                }
                stamper.getAcroFields().setField("Race ", pcRace);
                stamper.getAcroFields().setField("CharacterName", pcName);
                stamper.getAcroFields().setField("XP", pcExp);
                stamper.getAcroFields().setField("Alignment", pcAlign);
                stamper.getAcroFields().setField("Background", pcBackG);
                int tempPB = Integer.parseInt(pcProfBonus);
                if (tempPB > 0) {
                    pcProfBonus = "+" + pcProfBonus;
                }
                stamper.getAcroFields().setField("ProfBonus", pcProfBonus);

                //Attributes
                stamper.getAcroFields().setField("STR", pcStrScore);
                stamper.getAcroFields().setField("STRmod", pcStrMod);
                stamper.getAcroFields().setField("DEX", pcDexScore);
                stamper.getAcroFields().setField("DEXmod ", pcDexMod);
                stamper.getAcroFields().setField("CON", pcConScore);
                stamper.getAcroFields().setField("CONmod", pcConMod);
                stamper.getAcroFields().setField("INT", pcIntScore);
                stamper.getAcroFields().setField("INTmod", pcIntMod);
                stamper.getAcroFields().setField("WIS", pcWisScore);
                stamper.getAcroFields().setField("WISmod", pcWisMod);
                stamper.getAcroFields().setField("CHA", pcChaScore);
                stamper.getAcroFields().setField("CHamod", pcChaMod);

                stamper.getAcroFields().setField("ClassLevel", pcClassLevel);
                stamper.getAcroFields().setField("Passive", pcPerc);

                stamper.close();
                reader.close();
            } catch (java.io.IOException | DocumentException e) {
                System.err.println("1st Catch, that didn't go well: " + e.getMessage());
            } catch (ParsingException e) {
                System.err.println("2nd Catch, that didn't go well: " + e.getMessage());
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @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(DandDcharPDFUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DandDcharPDFUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DandDcharPDFUI.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DandDcharPDFUI.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 DandDcharPDFUI().setVisible(true);
            }
        });
    }

    // 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.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}