Example usage for com.itextpdf.text.pdf PdfReader PdfReader

List of usage examples for com.itextpdf.text.pdf PdfReader PdfReader

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfReader PdfReader.

Prototype

public PdfReader(final PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:Reader.java

public void showPdf(String s) throws IOException {
    bookNames.add(s);// w ww.  ja  v  a2 s  .  com

    PdfReader pr = new PdfReader(s);

    String content = PdfTextExtractor.getTextFromPage(pr, 1);

    currentPageNum = 1;
    pageContentPane.setText(content);
}

From source file:Reader.java

public void nextPage() throws IOException {

    PdfReader pr = new PdfReader(fileName);

    //increment current page if there is one more page to read

    if (currentPageNum < pr.getNumberOfPages()) {
        ++currentPageNum;// ww w. ja  v  a 2s .  c  o  m

        String content = PdfTextExtractor.getTextFromPage(pr, currentPageNum);

        //go to the next page
        pageContentPane.setText(content);
    } else {
        String content = PdfTextExtractor.getTextFromPage(pr, currentPageNum);

        //show the last page
        pageContentPane.setText(content);

    }
}

From source file:Reader.java

public void previousPage() throws IOException {

    PdfReader pr = new PdfReader(fileName);

    //decrement current page if it is not the first page

    if (currentPageNum <= pr.getNumberOfPages() && currentPageNum != 1) {
        --currentPageNum;/* ww  w.  ja va 2 s  .com*/

        String content = PdfTextExtractor.getTextFromPage(pr, currentPageNum);

        //go to the previous page
        pageContentPane.setText(content);
    } else {

        String content = PdfTextExtractor.getTextFromPage(pr, currentPageNum);

        //show the last page
        pageContentPane.setText(content);

    }
}

From source file:SigningProcess.java

public static String sign(String base64, HashMap map) {
    String base64string = null;//from w  w w  .  j a  v a  2 s .c om
    try {
        System.out.println("map :" + map);
        // Getting a set of the entries
        Set set = map.entrySet();
        System.out.println("set :" + set);
        // Get an iterator
        Iterator it = set.iterator();
        // Display elements
        while (it.hasNext()) {
            Entry me = (Entry) it.next();
            String key = (String) me.getKey();
            if ("privateKey".equalsIgnoreCase(key)) {
                privateKey = (PrivateKey) me.getValue();
            }
            if ("certificateChain".equalsIgnoreCase(key)) {
                certificateChain = (X509Certificate[]) me.getValue();
            }
        }

        OcspClient ocspClient = new OcspClientBouncyCastle();
        TSAClient tsaClient = null;
        for (int i = 0; i < certificateChain.length; i++) {
            X509Certificate cert = (X509Certificate) certificateChain[i];
            String tsaUrl = CertificateUtil.getTSAURL(cert);
            if (tsaUrl != null) {
                tsaClient = new TSAClientBouncyCastle(tsaUrl);
                break;
            }
        }
        List<CrlClient> crlList = new ArrayList<CrlClient>();
        crlList.add(new CrlClientOnline(certificateChain));

        String property = System.getProperty("java.io.tmpdir");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] FileByte = decoder.decodeBuffer(base64);
        writeByteArraysToFile(property + "_unsigned.pdf", FileByte);

        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(property + "_unsigned.pdf");
        FileOutputStream os = new FileOutputStream(property + "_signed.pdf");
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        //            appearance.setReason(reason);
        //            appearance.setLocation(location);
        appearance.setAcro6Layers(false);
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig1");
        // Creating the signature
        ExternalSignature pks = new PrivateKeySignature((PrivateKey) privateKey, DigestAlgorithms.SHA256,
                providerMSCAPI.getName());
        ExternalDigest digest = new BouncyCastleDigest();
        MakeSignature.signDetached(appearance, digest, pks, certificateChain, crlList, ocspClient, tsaClient, 0,
                MakeSignature.CryptoStandard.CMS);

        InputStream docStream = new FileInputStream(property + "_signed.pdf");
        byte[] encodeBase64 = Base64.encodeBase64(IOUtils.toByteArray(docStream));
        base64string = new String(encodeBase64);
    } catch (IOException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (DocumentException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (GeneralSecurityException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    }
    return base64string;
}

From source file:SignPDF.java

License:Open Source License

public static void main(String args[]) {
    try {/*from  w  ww . j ava 2  s  .  c o m*/

        if (args.length != 1) {
            System.err.println("usage: $0 <pdf-file>");
            System.exit(1);
        }
        src = args[0];
        dest = src + ".temp";

        rcname = System.getenv("SIGNPDFRC");
        if (rcname == null || rcname.length() == 0)
            rcname = System.getenv("HOME") + "/.signpdf";
        else
            System.out.println("using SIGNPDFRC=" + rcname);

        if (!getProperties())
            createDefaultProperties();

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(path), keystore_password.toCharArray());
        if (alias == null || alias.length() == 0)
            alias = (String) ks.aliases().nextElement();
        Certificate[] chain = ks.getCertificateChain(alias);
        PrivateKey key = (PrivateKey) ks.getKey(alias, key_password.toCharArray());

        X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        System.out.println("Signer ID serial     " + cert.getSerialNumber());
        System.out.println("Signer ID version    " + cert.getVersion());
        System.out.println("Signer ID issuer     " + cert.getIssuerDN());
        System.out.println("Signer ID not before " + cert.getNotBefore());
        System.out.println("Signer ID not after  " + cert.getNotAfter());

        // show days valid
        long ticks_now = new Date().getTime();
        long ticks_to = cert.getNotAfter().getTime();

        long ticks_delta = (ticks_to - ticks_now) / TICKS_PER_DAY;
        System.out.println("Certificate will expire in " + ticks_delta + " days.");

        Signature s = Signature.getInstance("SHA1withRSA");
        s.initVerify(ks.getCertificate(alias));

        try {
            cert.checkValidity();
            System.out.println("Validation check passed.");
        } catch (Exception e) {
            System.out.println("Certificate expired or invalid. Abroting.");
            System.exit(1);
        }

        PdfReader reader = new PdfReader(src);
        FileOutputStream os = new FileOutputStream(dest);
        //PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, false);
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        stamper.setEncryption(true, null, null,
                PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS | PdfWriter.ALLOW_COPY);

        HashMap<String, String> info = reader.getInfo();
        info.put("Creator", "SingPDF " + version);
        stamper.setMoreInfo(info);

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        appearance.setReason(reason);
        appearance.setLocation(location);
        appearance.setContact(contact);
        appearance.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

        /// ts + ocsp
        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        dic.setReason(appearance.getReason());
        dic.setLocation(appearance.getLocation());
        dic.setContact(appearance.getContact());
        dic.setDate(new PdfDate(appearance.getSignDate()));
        appearance.setCryptoDictionary(dic);

        // timestamping + ocsp

        if (tsa_url != null && tsa_url.length() > 0) {

            byte[] ocsp = null;
            TSAClient tsc = null;

            int contentEstimated = 15000;
            HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
            exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
            appearance.preClose(exc);

            InputStream data = appearance.getRangeStream();
            MessageDigest mdig = MessageDigest.getInstance("SHA1");

            byte buf[] = new byte[8192];
            int n;
            while ((n = data.read(buf)) > 0) {
                mdig.update(buf, 0, n);
            }

            if (root_cert != null && root_cert.length() > 0) {
                String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
                CertificateFactory cf = CertificateFactory.getInstance("X509");
                FileInputStream is = new FileInputStream(root_cert);
                X509Certificate root = (X509Certificate) cf.generateCertificate(is);
                ocsp = new OcspClientBouncyCastle().getEncoded((X509Certificate) chain[0], root, url);
            }

            byte hash[] = mdig.digest();
            Calendar cal = Calendar.getInstance();
            PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", null, false);
            byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.update(sh, 0, sh.length);

            if (tsa_url != null && tsa_url.length() > 0) {
                tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw);
                byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);
                if (contentEstimated + 2 < encodedSig.length)
                    throw new Exception("Not enough space");
                byte[] paddedSig = new byte[contentEstimated];
                System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
                PdfDictionary dic2 = new PdfDictionary();
                dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
                appearance.close(dic2);
            }
        }
        // ~timestamping + ocsp 

        File mysrc = new File(src);
        mysrc.delete();
        File mydest = new File(dest);
        mydest.renameTo(mysrc);

        System.exit(0);
    }

    catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:NPRImpl.java

@Override
public boolean saveReservationToPdf(ReservationImpl reservationImpl) throws RemoteException {

    try {/*from  w  w w  .  j  a va  2  s .c o  m*/
        BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt"));
        String path = "";
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            path = sb.toString().trim();
        } finally {
            br.close();
        }
        // TODO add your handling code here:
        Document doc = new Document();
        FileOutputStream fos = new FileOutputStream(path + "\\reservation\\" + reservationImpl.getlName().trim()
                + ", " + reservationImpl.getfName().trim() + "ReservationForm.pdf");
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, fos);
        PdfReader pdfReader = new PdfReader("ReservationForm.pdf");

        PdfStamper pdfStamper = new PdfStamper(pdfReader, fos);
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            PdfContentByte content = pdfStamper.getOverContent(i);
            //Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 10);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getDatePaid().trim(), 435, 655,
                    0);
            if (reservationImpl.getmName().trim().isEmpty()) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT,
                        reservationImpl.getlName().trim() + ", " + reservationImpl.getfName(), 265, 625, 0);
            } else {
                content.showTextAligned(
                        PdfContentByte.ALIGN_LEFT, reservationImpl.getlName().trim() + ", "
                                + reservationImpl.getfName() + " " + reservationImpl.getmName().charAt(0) + ".",
                        265, 625, 0);
            }
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getAddress().trim(), 265, 600,
                    0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getZipCode().trim(), 265, 580,
                    0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getmNumber().trim(), 265, 565,
                    0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getEmail().trim(), 265, 550, 0);
            content.setFontAndSize(bf, 12);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Room No.:" + reservationImpl.getRoom().trim(),
                    125, 370, 0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getRoomType().trim(), 325, 370,
                    0);
            //                content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getsTerm().trim(), 125, 310, 0);
            if (reservationImpl.getsTerm() != null) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getsTerm().trim(), 125, 310,
                        0);
                if (!reservationImpl.getAyTo().trim().isEmpty()
                        & !reservationImpl.getAyFrom().trim().isEmpty()) {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT,
                            reservationImpl.getAyFrom().trim() + " - " + reservationImpl.getAyTo().trim(), 325,
                            310, 0);
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, " - ", 435, 310, 0);
                } else {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, " - ", 325, 310, 0);
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, " - ", 435, 310, 0);
                }
            } else {
                if (reservationImpl.getOthers().trim().isEmpty()) {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, " - ", 325, 310, 0);
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, " - ", 435, 310, 0);
                } else {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, " - ", 325, 310, 0);
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getOthers().trim(), 435,
                            310, 0);
                }
            }
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, reservationImpl.getDatePaid().trim(), 265, 210,
                    0);
            content.endText();
        }
        pdfStamper.close();
        pdfReader.close();
        fos.close();
        pdfWriter.close();
    } catch (DocumentException | FileNotFoundException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    } catch (IOException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    }
    return true;
}

From source file:NPRImpl.java

@Override
public boolean saveRegistrationToPdf(RegistrationImpl registrationImpl, ResidentImpl residentImpl)
        throws RemoteException {
    try {/*from  w  w w.  ja va2s.  co  m*/
        BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt"));
        String path = "";
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            path = sb.toString().trim();
        } finally {
            br.close();
        }
        String gend = "";
        Document doc = new Document();
        FileOutputStream fos = new FileOutputStream(path + "\\registration\\" + residentImpl.getLName().trim()
                + ", " + residentImpl.getFName().trim() + "RegistrationResidentForm.pdf");
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, fos);

        PdfReader pdfReader = new PdfReader("RegistrationResidentForm.pdf");

        PdfStamper pdfStamper = new PdfStamper(pdfReader, fos);

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            PdfContentByte content = pdfStamper.getOverContent(i);
            if (residentImpl.getPicture() != null) {
                Image image1 = Image.getInstance(residentImpl.getPicture());
                image1.scaleAbsolute(95, 105);
                image1.setAbsolutePosition(465f, 635f);
                content.addImage(image1);
            }

            //Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 10);
            //last name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getLName().trim(), 175, 610, 0);
            //first name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getFName().trim(), 325, 610, 0);
            //middle name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getMName().trim(), 470, 610, 0);
            //college
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getCollege().trim(), 180, 582,
                    0);
            //Course and year
            content.showTextAligned(PdfContentByte.ALIGN_LEFT,
                    registrationImpl.getCourse().trim() + " - " + registrationImpl.getYear().trim(), 180, 568,
                    0);
            //department
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getDepartment().trim(), 400,
                    582, 0);
            //Sex
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, residentImpl.getGender().trim(), 400, 568, 0);
            //Home address
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getAddress().trim(), 110, 540,
                    0);
            //resident mobile no1
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMobile_number().trim(), 187,
                    485, 0);
            //resident mobile no2
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMobile_number2().trim(), 187,
                    470, 0);
            //student email
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getEmail().trim(), 397, 485, 0);
            //fathers name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherName().trim(), 110,
                    443, 0);
            //fathers area code
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherAreaCode().trim(), 300,
                    443, 0);
            //father landline
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherPhone().trim(), 355,
                    443, 0);
            //father mobile
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherMobile().trim(), 490,
                    443, 0);
            //father email
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getFatherEmail().trim(), 110,
                    430, 0);
            //mother name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherName().trim(), 110,
                    402, 0);
            //mother area code
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherAreaCode().trim(), 300,
                    402, 0);
            //mother landline
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherPhone().trim(), 355,
                    402, 0);
            //mother mobile
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherMobile().trim(), 490,
                    402, 0);
            //mother email
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getMotherEmail().trim(), 110,
                    387, 0);
            //guardian name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianName().trim(), 170,
                    335, 0);
            //guardian contact number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianMobile().trim(), 470,
                    335, 0);
            //guardian address
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianAddress().trim(),
                    125, 322, 0);
            //guardian relation
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, registrationImpl.getGuardianRelation().trim(),
                    170, 307, 0);
            content.setFontAndSize(bf, 12);
            //room details
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Room No.: "
                    + registrationImpl.getRoom_number().trim() + " - " + registrationImpl.getRoom_type().trim(),
                    355, 235, 0);
            content.endText();

        }
        pdfStamper.close();
        pdfReader.close();
        fos.close();
        pdfWriter.close();
    } catch (DocumentException | FileNotFoundException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    } catch (IOException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    }
    return true;
}

From source file:NPRImpl.java

@Override
public boolean saveFurnitureToPdf(ArrayList<String> info, ArrayList<FurnitureImpl> furnitureImpl)
        throws RemoteException {
    try {/*  w  ww.j av a 2 s  . c o m*/
        // TODO add your handling code here:
        Document doc = new Document();
        BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt"));
        String path = "";
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            path = sb.toString().trim();
        } finally {
            br.close();
        }
        FileOutputStream fos = new FileOutputStream(path + "\\furniture\\" + info.get(0) + "InventoryForm.pdf");
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, fos);

        PdfReader pdfReader = new PdfReader("InventoryForm.pdf");
        PdfStamper pdfStamper = new PdfStamper(pdfReader, fos);
        float added = 0;
        float rowSize = 175;
        float columnSize = 560;
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            PdfContentByte content = pdfStamper.getOverContent(i);
            //Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 10);
            //room number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, info.get(0).trim(), 185, 650, 0);
            //room type
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, info.get(2).trim(), 185, 635, 0);
            //resident
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, info.get(1).trim(), 185, 620, 0);
            for (FurnitureImpl f : furnitureImpl) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, f.getItem_name().trim(), rowSize - 60,
                        columnSize + added, 0);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, f.getControl_number().trim(), rowSize + 30,
                        columnSize + added, 0);
                added -= 15;
            }

            content.endText();
        }
        pdfStamper.close();
        pdfReader.close();
        fos.close();
        pdfWriter.close();
    } catch (FileNotFoundException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    } catch (DocumentException | IOException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    }
    return true;
}

From source file:NPRImpl.java

@Override
public boolean saveGadgetToPdf(ArrayList<String> info, ArrayList<GadgetImpl> gadgetImpl)
        throws RemoteException {
    try {// w  w w  . j  a v  a  2 s  .  co m
        // TODO add your handling code here:
        BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt"));
        String path = "";
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            path = sb.toString().trim();
        } finally {
            br.close();
        }
        Document doc = new Document();
        FileOutputStream fos = new FileOutputStream(
                path + "\\gadget\\" + info.get(0).trim() + "GadgetForm.pdf");
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, fos);

        PdfReader pdfReader = new PdfReader("GadgetForm.pdf");

        PdfStamper pdfStamper = new PdfStamper(pdfReader, fos);
        float rowSize = 175;
        float columnSize = 495;
        float added = 0;
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            PdfContentByte content = pdfStamper.getOverContent(i);
            //Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 10);
            //room number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, info.get(1).trim(), 240, 630, 0);
            //room type
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, info.get(2).trim(), 240, 615, 0);
            //resident
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, info.get(0).trim(), 240, 600, 0);
            for (GadgetImpl g : gadgetImpl) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, g.getItem_name().trim(), rowSize - 60,
                        columnSize + added, 0);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, g.getDescription().trim(), rowSize + 65,
                        columnSize + added, 0);
                added -= 15;
            }

            content.endText();
        }
        pdfStamper.close();
        pdfReader.close();
        fos.close();
        pdfWriter.close();
    } catch (DocumentException | FileNotFoundException | IllegalPdfSyntaxException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    } catch (IOException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    }
    return true;
}

From source file:NPRImpl.java

@Override
public boolean saveTransientToPdf(TransientImpl transientImpl, ArrayList<String> names) throws RemoteException {
    try {/*w  w w .  j  av a 2  s  . co m*/
        BufferedReader br = new BufferedReader(new FileReader("dir\\defaults.txt"));
        String path = "";
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            path = sb.toString().trim();
        } finally {
            br.close();
        }

        com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
        FileOutputStream fos = new FileOutputStream(path + "\\transient\\" + transientImpl.getLast_name().trim()
                + ", " + transientImpl.getFirst_name().trim() + "TransientForm.pdf");
        PdfWriter.getInstance(doc, fos);

        PdfReader pdfReader = new PdfReader("TransientForm.pdf");

        PdfStamper pdfStamper = new PdfStamper(pdfReader, fos);
        float varPosition = 0;
        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            PdfContentByte content = pdfStamper.getOverContent(i);
            //Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 10);
            varPosition = 15;
            //last name
            content.showTextAligned(PdfContentByte.ALIGN_LEFT,
                    transientImpl.getLast_name().trim() + ", " + transientImpl.getFirst_name().trim(), 100,
                    661 + varPosition, 0);
            //first name 
            content.showTextAligned(PdfContentByte.ALIGN_LEFT,
                    new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()), 400,
                    661 + varPosition, 0);
            if (!transientImpl.getFull_name().isEmpty()) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getFull_name().trim(), 125,
                        633 + varPosition, 0);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getRelation().trim(), 470,
                        633 + varPosition, 0);
            } else {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "N / A", 125, 633 + varPosition, 0);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "N / A", 470, 633 + varPosition, 0);
            }
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getMobile_number().trim(), 135,
                    590 + varPosition, 0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getEmail().trim(), 400,
                    590 + varPosition, 0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getAddress().trim(), 175,
                    577 + varPosition, 0);
            varPosition = 35;
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getReservedRooms().trim(), 135,
                    507 + varPosition, 0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getArrival().trim(), 135,
                    493 + varPosition, 0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getDeparture().trim(), 435,
                    493 + varPosition, 0);
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, transientImpl.getNoAdditionalGuest().trim(), 180,
                    478 + varPosition, 0);
            for (int count = 0; count < names.size(); count++) {
                float x = 50;
                if (count <= 3) {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, names.get(0).trim(), x,
                            435 + varPosition, 0);
                    varPosition -= 13;
                    if (count == 3) {
                        varPosition = 35;
                    }
                } else if (count >= 4 & count <= 7) {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, names.get(0).trim(), x + 200,
                            435 + varPosition, 0);
                    varPosition -= 13;
                    if (count == 7) {
                        varPosition = 35;
                    }
                } else {
                    content.showTextAligned(PdfContentByte.ALIGN_LEFT, names.get(0).trim(), x + 400,
                            435 + varPosition, 0);
                    varPosition -= 13;
                }
            }
            content.endText();
        }
        pdfStamper.close();
        pdfReader.close();
    } catch (DocumentException | FileNotFoundException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    } catch (IOException ex) {
        //            Logger.getLogger(NPRImpl.class.getName()).log(Level.SEVERE, null, ex);
        label.setText(ex.getMessage());
        return false;
    }
    return true;
}