PDF.PDFDateStampPartial.java Source code

Java tutorial

Introduction

Here is the source code for PDF.PDFDateStampPartial.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 PDF;

import java.awt.Dimension;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
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.PDType1Font;
import Utilities.GlobalVar;

/**
 *
 * @author bob
 */
public class PDFDateStampPartial {
    private JRadioButton voidButton;
    private JRadioButton selectButton;
    private JRadioButton skipButton;
    private ButtonGroup statusButtonGroup;
    private JLabel seqText;
    private Boolean[][] statusArray;
    private JButton submitPDFButton;

    public PDFDateStampPartial(String pdfFileName, String date, Boolean selectAll, String ADSNname) {
        if (date == null || date.equalsIgnoreCase("")) {
            GregorianCalendar today = new GregorianCalendar();
            date = today.getTime().toString();
        } else {
            date = "Received on " + date + " " + ADSNname + " DMPO";
        }

        initComponent(pdfFileName, date, selectAll);

        SwingSimpleController controller = new SwingSimpleController(statusButtonGroup, seqText, statusArray);
        controller.openDocument(pdfFileName); // show the component 
        int pageNum = controller.getDocument().getNumberOfPages();

        System.out.println(controller.getDocument().getNumberOfPages());

        SwingViewSimpleBuilder factory = new SwingViewSimpleBuilder(controller, statusButtonGroup, seqText,
                submitPDFButton, statusArray);

        JPanel viewerComponentPanel = factory.buildViewerPanel();
        // add interactive mouse link annotation support via callback 
        //        controller.getDocumentViewController().setAnnotationCallback(
        //                new org.icepdf.ri.common.MyAnnotationCallback(controller.getDocumentViewController())); 

        JFrame applicationFrame = new JFrame();
        applicationFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        applicationFrame.getContentPane().add(viewerComponentPanel); // Now that the GUI is all in place, we can try opening a PDF 
        //        controller.openDocument(filePath); // show the component 
        //        System.out.println(controller.getDocument().getNumberOfPages());
        applicationFrame.pack();
        applicationFrame.setVisible(true);
    }

    private void initComponent(final String pdfFileName, final String date, boolean selectAll) {
        voidButton = new JRadioButton();
        selectButton = new JRadioButton();
        skipButton = new JRadioButton();

        voidButton.setText("Delete");
        skipButton.setText("Skip");
        voidButton.setEnabled(false);

        selectButton.setText("Select");
        //selectButton.setEnabled(false);

        statusButtonGroup = new ButtonGroup();
        statusButtonGroup.add(voidButton);
        statusButtonGroup.add(skipButton);
        statusButtonGroup.add(selectButton);

        seqText = new JLabel();
        seqText.setText("----");
        seqText.setSize(new Dimension(500, 20));
        //Icon ic = new ImageIcon("heart.gif");
        // seqText.setIcon(new ImageIcon("heart.gif"));
        seqText.setIcon(new ImageIcon(getClass().getResource("heart.gif")));
        statusArray = new Boolean[GlobalVar.NUM_BUTTON][GlobalVar.MAX_NUM_PAGES];

        for (int i = 0; i < GlobalVar.NUM_BUTTON; i++) {
            for (int j = 0; j < GlobalVar.MAX_NUM_PAGES; j++) {
                statusArray[i][j] = false;
            }
        }

        for (int j = 0; j < GlobalVar.MAX_NUM_PAGES; j++) {
            statusArray[GlobalVar.SELECT_BUTTON_INDEX][j] = selectAll;
        }

        submitPDFButton = new JButton();
        submitPDFButton.setText("Generate PDF");
        //Icon ic4 = new ImageIcon("signup.gif");
        // this.setIconImage(new ImageIcon(getClass().getResource(GlobalVar.ICON_NAME)).getImage());
        //submitPDFButton.setIcon(new ImageIcon("signup.gif"));   
        submitPDFButton.setIcon(new ImageIcon(getClass().getResource("signup.gif")));
        submitPDFButton.setSize(500, 200);
        //submitPDFButton.setBorder(BorderFactory.createLineBorder(Color.black, 5, true));
        submitPDFButton.setBorder(BorderFactory.createRaisedBevelBorder());
        submitPDFButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {

                try {
                    generatePDFFile(pdfFileName, statusArray, date);
                } catch (IOException ex) {
                    Logger.getLogger(PDFDateStampPartial.class.getName()).log(Level.SEVERE, null, ex);
                } catch (COSVisitorException ex) {
                    Logger.getLogger(PDFDateStampPartial.class.getName()).log(Level.SEVERE, null, ex);
                }
                JOptionPane.showMessageDialog(null, "pdf file is successfully date stamped on some pages.");
            }
        });
    }

    // given the original pdf file, date stamp every page, sequence selected pages and
    // output two pdf files, one for audit, the other for reject 
    private void generatePDFFile(String pdfFileName, Boolean[][] statusArray, String date)
            throws IOException, COSVisitorException {
        PDDocument pdf = PDDocument.load(pdfFileName);
        List pages = pdf.getDocumentCatalog().getAllPages();
        Iterator<PDPage> iter = pages.iterator();
        int pageNum = 0; // 0 based
        //int sequenceNum = 1; // start from 0001
        PDDocument pdfBlank = new PDDocument();

        while (iter.hasNext()) {
            PDPage page = iter.next();
            PDPage pageBlank = new PDPage();

            PDPageContentStream stream = new PDPageContentStream(pdf, page, true, false);
            PDPageContentStream streamBlank = new PDPageContentStream(pdfBlank, pageBlank, true, false);

            // == seq stamp
            if (statusArray[GlobalVar.SELECT_BUTTON_INDEX][pageNum]) {
                pageWrite(stream, date);
                pageWrite(streamBlank, date);
            }
            // == end of seq stamp
            pdfBlank.addPage(pageBlank);
            stream.close();
            streamBlank.close();

            pageNum++;
        }

        // out put two pdf files: one is template for printer print hardcopies, the other is digital copy
        String suffix = "_P dateStamped.pdf";
        pdfFileName = pdfFileName.replace(".pdf", suffix);
        String blankPdfFileName = pdfFileName.replace(".pdf", "BLANK.pdf");

        pdf.save(pdfFileName);
        pdfBlank.save(blankPdfFileName);

        pdf.close();
        pdfBlank.close();
    }

    // write a sequence number on a specific page
    private void pageWrite(PDPageContentStream stream, String date) throws IOException {
        stream.beginText();
        stream.setFont(PDType1Font.HELVETICA, GlobalVar.DATE_STAMP_FONT_SIZE);
        stream.moveTextPositionByAmount(GlobalVar.DATE_STAMP_X_POSITION, GlobalVar.DATE_STAMP_Y_POSITION);
        stream.drawString(date); //date stamp 
        stream.endText();
    }

}