Example usage for com.itextpdf.text Rectangle Rectangle

List of usage examples for com.itextpdf.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(final float llx, final float lly, final float urx, final float ury) 

Source Link

Document

Constructs a Rectangle -object.

Usage

From source file:SigningProcess.java

public static String sign(String base64, HashMap map) {
    String base64string = null;/*  w  w w  .j a  v  a  2s .  c  o  m*/
    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:Separator.java

License:Apache License

public static void crop(String inFileName, String outFileName, int split, boolean vert) throws Exception {

    PdfReader reader = new PdfReader(new File(inFileName).getAbsolutePath());
    String PDFName = outFileName.substring(outFileName.lastIndexOf("Folder\\") + 7,
            outFileName.indexOf(".pdf"));
    File fn = new File(scanFolder + PDFName + "\\" + PDFName + "_split_" + split + ".pdf");
    fn.getParentFile().mkdirs();//from  w  w w. j av  a2 s .  co m

    int count = reader.getNumberOfPages();
    Document doc = new Document();
    PdfCopy copy = new PdfCopy(doc, new FileOutputStream(fn.getAbsolutePath()));
    doc.open();
    if (vert) {
        for (int i = 1; i <= count; i++) {
            reader.getPageN(i).put(PdfName.CROPBOX, new PdfRectangle(PageSize.LETTER));
            copy.addPage(copy.getImportedPage(reader, i));
        }
    } else {
        if (!doubSided) {
            for (int j = 1; j <= count; j++) {
                reader.getPageN(j).put(PdfName.CROPBOX, new PdfRectangle((new Rectangle(0, 180, 792, 792))));
                PdfDictionary pageDict;
                int rot = reader.getPageRotation(j);
                pageDict = reader.getPageN(j);
                pageDict.put(PdfName.ROTATE, new PdfNumber(rot + 90));
                copy.addPage(copy.getImportedPage(reader, j));
            }
        } else {
            for (int j = 1; j <= count; j++) {
                reader.getPageN(j).put(PdfName.CROPBOX, new PdfRectangle(new Rectangle(0, 180, 792, 792)));
                PdfDictionary pageDict;
                pageDict = reader.getPageN(j);
                if (j % 2 == 0) { // even
                    pageDict.put(PdfName.ROTATE, new PdfNumber(270));
                } else { // odd
                    pageDict.put(PdfName.ROTATE, new PdfNumber(90));
                }
                copy.addPage(copy.getImportedPage(reader, j));
            }
        }
    }
    doc.close();
}

From source file:app.App.java

private void setLink(int pageId, PdfStamper stamper) throws ClassNotFoundException, IOException {
    // load the sqlite-JDBC driver using the current class loader
    Class.forName("org.sqlite.JDBC");

    Connection connection = null;
    try {//from   w w  w  .j  a  v  a  2  s.  c om
        // create a database connection
        connection = DriverManager.getConnection("jdbc:sqlite:" + DATABASE);
        Statement statement = connection.createStatement();
        statement.setQueryTimeout(30); // set timeout to 30 sec.

        ResultSet rs = statement.executeQuery(
                "select * from page_annotations " + "where annotation_type = 'goto' and page_id = " + pageId);
        float spendX = 0;
        float spendY = 0;
        float coordX = 0;
        float coordY = 0;
        int pageDest = 0;
        Rectangle rect;
        PdfAnnotation annotation;
        while (rs.next()) {
            spendX = rs.getFloat("pdf_width");
            spendY = rs.getFloat("pdf_height");
            coordX = rs.getFloat("pdf_x");// + rs.getFloat("pdf_width");
            coordY = rs.getFloat("pdf_y");
            pageDest = rs.getInt("annotation_target");

            Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.UNDERLINE);
            // Blue
            font.setColor(0, 0, 255);
            Chunk chunk = new Chunk("GOTO", font);
            Anchor anchor = new Anchor(chunk);
            ColumnText.showTextAligned(stamper.getUnderContent(pageId), Element.ALIGN_LEFT, anchor,
                    coordX + spendX, coordY, 0);

            rect = new Rectangle(coordX, coordY, spendX, spendY);
            annotation = PdfAnnotation.createLink(stamper.getWriter(), rect, PdfAnnotation.HIGHLIGHT_INVERT,
                    new PdfAction("#" + pageDest));
            stamper.addAnnotation(annotation, pageId);
        }
    } catch (SQLException e) {
        // if the error message is "out of memory", 
        // it probably means no database file is found
        System.err.println(e.getMessage());
    } finally {
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            // connection close failed.
            System.err.println(e);
        }
    }
}

From source file:bd.gov.forms.web.FormBuilder.java

License:Open Source License

@RequestMapping(value = "/pdfExport", method = RequestMethod.GET)
public String pdfExport(@RequestParam(value = "formId", required = true) String formId,
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "colName", required = false) String colName,
        @RequestParam(value = "colVal", required = false) String colVal,
        @RequestParam(value = "sortCol", required = false) String sortCol,
        @RequestParam(value = "sortDir", required = false) String sortDir, ModelMap model,
        HttpServletResponse response, HttpServletRequest request) throws IOException {

    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // step 2/*from w w w.ja v a 2 s .  c o m*/
    try {
        response.reset();
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "inline; filename=test.pdf");

        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "No-cache");

        PdfWriter writer = PdfWriter.getInstance(document, baos);
        // step 3
        document.open();

        Form form = null;
        //System.out.println("The form id is 1:"+formId);
        if (formId != null) {
            form = formDao.getFormWithFields(formId);
        }

        if (form != null) {
            if (form.getStatus() != 2) {//2-active, 3-deactive
                model.put("doneMessage", "msg.access.denied");
                model.put("doneMsgType", "failed");

                return "redirect:done.htm";
            }
            initForm(form);
        }

        List<Field> fieldList = form.getFields();

        if (fieldList.isEmpty()) {
            System.out.println("The list size is zero");
        }

        PdfPCell space;
        space = new PdfPCell();
        space.setBorder(Rectangle.NO_BORDER);
        space.setColspan(2);
        space.setFixedHeight(8);

        PdfPTable table = new PdfPTable(2);
        PdfPCell cell;

        //PdfPCell cell;                
        table.setWidths(new int[] { 1, 2 });

        int i = 0;
        for (Field f : fieldList) {
            if ("text".equals(f.getType())) {

                table.addCell(f.getLabel());
                cell = new PdfPCell();
                cell.setCellEvent(new TextFields(1, i));
                table.addCell(cell);

            } else if ("textarea".equals(f.getType())) {
                table.addCell(f.getLabel());
                cell = new PdfPCell();
                cell.setCellEvent(new TextFields(1, i));
                cell.setFixedHeight(60);
                table.addCell(cell);

            } else if ("select".equals(f.getType())) {
                table.addCell(f.getType());
                cell = new PdfPCell();
                cell.setCellEvent(new ChoiceFields(3, f.getList().toArray()));
                table.addCell(cell);
                //table.addCell(space);
                System.out.println("ajsdhd");
            }
            i++;
        }

        /*
          for(Field f : fieldList)
          {  
                
        if( "radio".equals(f.getType()) )
        {    
            System.out.println("List "+f.getList()+"  Oppt"+f.getOptions()+ "    df"+f.getColName());
                    
            writer = PdfWriter.getInstance(document, new FileOutputStream("TextFieldForm.pdf"));
                 
            //writer.addJavaScript(Utilities.readFileToString(""));
            // add the radio buttons
            PdfContentByte canvas = writer.getDirectContent();
            Font font = new Font(FontFamily.HELVETICA, 14);
            Rectangle rect;
            PdfFormField field;
            PdfFormField radiogroup = PdfFormField.createRadioButton(writer, true);
            radiogroup.setFieldName("language");
            RadioCheckField radio;
            for (int i = 0; i < 2; i++) 
            {
                rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40);
                radio = new RadioCheckField(writer, rect, null, f.getLabel());
                radio.setBorderColor(GrayColor.GRAYBLACK);
                radio.setBackgroundColor(GrayColor.GRAYWHITE);
                radio.setCheckType(RadioCheckField.TYPE_CIRCLE);
                field = radio.getRadioField();
                radiogroup.addKid(field);
                        
                writer.addAnnotation(field);
                       
                ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,
                    new Phrase(f.getLabel(), font), 70, 790 - i * 40, 0);
            }
            //table.addCell(f.getLabel());
            //cell = new PdfPCell();
                    
            //document.add(radiogroup);
            //writer.addAnnotation(radiogroup);
                    
                
        }
                
          }       */

        // Add submit button   
        PushbuttonField submitBtn = new PushbuttonField(writer, new Rectangle(400, 700, 370, 670),
                "submitPOST");
        //submitBtn.setBackgroundColor(Color.GRAY);
        submitBtn.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
        submitBtn.setText("Submit");
        submitBtn.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
        PdfFormField submitField = submitBtn.getField();
        submitField.setAction(
                PdfAction.createSubmitForm("http://localhost:8084/GovForm-07-02/formBuilder/pdfresponse.htm",
                        null, PdfAction.SUBMIT_HTML_FORMAT));

        writer.addAnnotation(submitField);

        document.add(table);

        System.out.println("Pdf creation successful");

        document.close();

        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception ex) {
        System.out.println("Could not print reasone::" + ex.toString());

    }

    //////////////////////////////////////// email part////////////////////////////  
    //email functionalities
    // Recipient's email ID needs to be mentioned.
    String to = "tanviranik@gmail.com";

    // Sender's email ID needs to be mentioned
    String from = "tanvir_cse@yahoo.com";

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject("This is the Subject Line!");

        // Now set the actual message
        message.setText("This is actual message");

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
    //////////////////////////////////////// email part////////////////////////////

    return null;

}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private byte[] personalize(byte[] pdf, Contact contact, Toc tableOfContents)
        throws IOException, DocumentException {

    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

        final PdfReader reader = new PdfReader(pdf);
        final PdfStamper stamper = new PdfStamper(reader, bos);

        // stamp some text on first page
        PdfContentByte text = stamper.getOverContent(1);

        text.beginText();//from   w ww  .j  a  v a2s.c  o  m

        text.setColorFill(iTextUtil.getFontCoverText().getColor());
        text.setFontAndSize(iTextUtil.getFontCoverText().getBaseFont(), iTextUtil.getFontCoverText().getSize());
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle1,
                text.getPdfDocument().getPageSize().getWidth() - 15, 195, 0);
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle2,
                text.getPdfDocument().getPageSize().getWidth() - 15, 175, 0);
        text.showTextAligned(Element.ALIGN_RIGHT, contact.getCurrency().getTitlePageDescription(),
                text.getPdfDocument().getPageSize().getWidth() - 15, 80, 0);

        text.setColorFill(iTextUtil.getFontCoverPricingguide().getColor());
        text.setFontAndSize(iTextUtil.getFontCoverPricingguide().getBaseFont(),
                iTextUtil.getFontCoverPricingguide().getSize());
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle3,
                text.getPdfDocument().getPageSize().getWidth() - 15, 145, 0);

        text.setColorFill(iTextUtil.getFontCoverYear().getColor());
        text.setFontAndSize(iTextUtil.getFontCoverYear().getBaseFont(), iTextUtil.getFontCoverYear().getSize());
        text.showTextAligned(Element.ALIGN_RIGHT, coverTitle4,
                text.getPdfDocument().getPageSize().getWidth() - 15, 105, 0);

        text.endText();

        // stamp some text on first page of the table of contents page
        final Image logoImage = iTextUtil.getImageFromByteArray(HttpUtil.readByteArray(
                pdfTemplate.getLogo().getUrl(), defaultService.getUserName(), defaultService.getPassword()));
        final PdfContentByte tocContent = stamper.getOverContent(tableOfContents.getFirstPageOfToc());
        final float resizeRatio = logoImage.getHeight() / 85; // define the desired height of the log
        tocContent.addImage(logoImage, logoImage.getWidth() / resizeRatio, 0, 0,
                logoImage.getHeight() / resizeRatio, 59, 615);

        text = stamper.getOverContent(tableOfContents.getFirstPageOfToc());

        text.beginText();

        text.setColorFill(iTextUtil.getFontPersonalization().getColor());
        text.setFontAndSize(iTextUtil.getFontPersonalization().getBaseFont(),
                iTextUtil.getFontPersonalization().getSize());
        text.showTextAligned(Element.ALIGN_LEFT, "Prepared for:", 355, 681, 0);
        text.showTextAligned(Element.ALIGN_LEFT, contact.getFullName(), 355, 662, 0);

        // set company name
        if (!StringUtils.isEmpty(contact.getCompany())) {
            text.showTextAligned(Element.ALIGN_LEFT, contact.getCompany(), 355, 643, 0);
            text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355,
                    624, 0);
        } else {
            text.showTextAligned(Element.ALIGN_LEFT, new SimpleDateFormat("MM-dd-yyyy").format(new Date()), 355,
                    643, 0);
        }

        text.endText();

        final ColumnText ct = new ColumnText(tocContent);
        ct.setSimpleColumn(new Rectangle(55, 517, iTextUtil.PAGE_SIZE.getWidth() - 45, 575));
        final List<Element> elements = HTMLWorker.parseToList(new StringReader(disclaimer), null);
        final Paragraph p = new Paragraph();
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        for (Element element : elements) {
            for (Chunk chunk : element.getChunks()) {
                chunk.setFont(iTextUtil.getFontDisclaimer());
            }
            p.add(element);
        }
        ct.addElement(p);
        ct.go();

        stamper.close();
        reader.close();
        return bos.toByteArray();

    }

}

From source file:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.PDFSignatureActionExecuter.java

License:Open Source License

/**
 * //from ww w . j  av  a 2s  . com
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 * @throws Exception 
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) throws Exception {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE);
    String signedName = (String) ruleAction.getParameterValue(PARAM_SIGNED_NAME);
    int height = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_WIDTH));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    // Ugly and verbose, but fault-tolerant
    String locationXStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_X);
    String locationYStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_Y);
    int locationX = 0;
    int locationY = 0;
    try {
        locationX = locationXStr != null ? Integer.parseInt(locationXStr) : 0;
    } catch (NumberFormatException e) {
        locationX = 0;
    }
    try {
        locationY = locationXStr != null ? Integer.parseInt(locationYStr) : 0;
    } catch (NumberFormatException e) {
        locationY = 0;
    }

    File tempDir = null;
    ContentWriter writer = null;
    KeyStore ks = null;

    try {
        // get a keystore instance by
        if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
        } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) {
            ks = KeyStore.getInstance("pkcs12");
        } else {
            throw new Exception("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = serviceRegistry.getContentService().getReader(privateKey,
                ContentModel.PROP_CONTENT);
        ks.load(keyReader.getContentInputStream(), storePassword.toCharArray());

        // set alias
        //         String alias = (String) ks.aliases().nextElement();

        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);

        //open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        FileOutputStream fout = new FileOutputStream(file);
        PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);

        // set reason for signature and location of signer
        sap.setReason(reason);
        sap.setLocation(location);

        if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) {
            sap.setVisibleSignature(new Rectangle(locationX + width, locationY - height, locationX, locationY),
                    1, null);
        }

        stamp.close();

        String[] splitedFilename = file.getName().split("\\.");
        String name = "-" + signedName + "." + splitedFilename[splitedFilename.length - 1];
        for (int i = splitedFilename.length - 2; i >= 0; i--) {
            if (name.equals("-" + signedName + "." + splitedFilename[splitedFilename.length - 1])) {
                name = splitedFilename[i] + name;
            } else {
                name = splitedFilename[i] + "." + name;
            }
        }

        writer = getWriter(name, (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER));
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();
    } catch (Exception e) {
        throw e;
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.chaschev.itext.ColumnTextBuilder.java

License:Apache License

public ColumnTextBuilder setSimpleColumn(float llx, float lly, float urx, float ury) {
    return setSimpleColumn(new Rectangle(llx, lly, urx, ury));
}

From source file:com.chaschev.itext.ColumnTextBuilder.java

License:Apache License

public ColumnTextBuilder setSimpleColumn(float llx, float lly, float urx, float ury, float leading,
        int alignment) {
    this.simpleColumnRectangle = new Rectangle(llx, lly, urx, ury);
    columnText.setSimpleColumn(llx, lly, urx, ury, leading, alignment);
    return this;
}

From source file:com.dexter.fms.mbean.ReportsMBean.java

@SuppressWarnings("unchecked")
public void createPDF(int type, String filename, int pageType) {
    try {/*  www .  jav a2 s.  c  o  m*/
        FacesContext context = FacesContext.getCurrentInstance();
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FMS");
        document.addCreationDate();
        document.addCreator("FMS");
        document.addSubject("Report");
        document.addTitle(getReport_title());

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        Hashtable<String, Object> params = new Hashtable<String, Object>();
        params.put("partner", dashBean.getUser().getPartner());
        GeneralDAO gDAO = new GeneralDAO();
        Object pSettingsObj = gDAO.search("PartnerSetting", params);
        PartnerSetting setting = null;
        if (pSettingsObj != null) {
            Vector<PartnerSetting> pSettingsList = (Vector<PartnerSetting>) pSettingsObj;
            for (PartnerSetting e : pSettingsList) {
                setting = e;
            }
        }
        gDAO.destroy();

        PdfPCell c = null;
        if (setting != null && setting.getLogo() != null) {
            Image logoImg = Image.getInstance(setting.getLogo());
            logoImg.scaleToFit(212, 51);
            c = new PdfPCell(logoImg);
        } else
            c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(getReport_title(), font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (getReport_start_dt() != null && getReport_end_dt() != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("From " + getReport_start_dt() + " to " + getReport_end_dt(), font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = exportPDFTable(type);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();
        String fileName = filename + ".pdf";

        writeFileToResponse(context.getExternalContext(), baos, fileName, "application/pdf");

        context.responseComplete();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dexter.fuelcard.mbean.UtilMBean.java

public byte[] createInvoicePDF(int pageType, String title, String dateperiod, String amount, String chargeType,
        String chargeAmount, String total) {
    try {/* w ww.  ja va 2s  . c  om*/
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new HeaderFooter());
        writer.setBoxSize("footer", new Rectangle(36, 54, 559, 788));
        if (!document.isOpen()) {
            document.open();
        }

        switch (pageType) {
        case 1:
            document.setPageSize(PageSize.A4);
            break;
        case 2:
            document.setPageSize(PageSize.A4.rotate());
            break;
        }
        document.addAuthor("FUELCARD");
        document.addCreationDate();
        document.addCreator("FUELCARD");
        document.addSubject("Invoice");
        document.addTitle(title);

        PdfPTable headerTable = new PdfPTable(1);

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images"
                + File.separator + "satraklogo.jpg";

        PdfPCell c = new PdfPCell(Image.getInstance(logo));
        c.setBorder(0);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        headerTable.addCell(c);

        Paragraph stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        BaseFont helvetica = null;
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
            //font exception
        }
        Font font = new Font(helvetica, 16, Font.NORMAL | Font.BOLD);

        c = new PdfPCell(new Paragraph(title, font));
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);

        if (dateperiod != null) {
            stars = new Paragraph(20);
            stars.add(Chunk.NEWLINE);
            stars.setSpacingAfter(10);

            c = new PdfPCell(stars);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            c.setBorder(0);
            headerTable.addCell(c);

            new Font(helvetica, 12, Font.NORMAL);
            Paragraph ch = new Paragraph("For " + dateperiod, font);
            c = new PdfPCell(ch);
            c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            headerTable.addCell(c);
        }
        stars = new Paragraph(20);
        stars.add(Chunk.NEWLINE);
        stars.setSpacingAfter(20);

        c = new PdfPCell(stars);
        c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        c.setBorder(0);
        headerTable.addCell(c);
        document.add(headerTable);

        PdfPTable pdfTable = new PdfPTable(4);
        try {
            helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        } catch (Exception e) {
        }
        font = new Font(helvetica, 8, Font.BOLDITALIC);

        pdfTable.addCell(new Paragraph("Charge Type", font)); // % per transaction or flat per license
        pdfTable.addCell(new Paragraph("Charge Amount", font)); // the amount of the charge setting

        if (chargeType.equalsIgnoreCase("Percent-Per-Tran")) {
            pdfTable.addCell(new Paragraph("Total Amount", font)); // the amount of the charge setting
        } else {
            pdfTable.addCell(new Paragraph("Total License", font)); // the amount of the charge setting
        }
        //pdfTable.addCell(new Paragraph("Description", font)); // the 
        pdfTable.addCell(new Paragraph("Amount Due", font));

        font = new Font(helvetica, 8, Font.NORMAL);
        pdfTable.addCell(new Paragraph(chargeType, font));
        pdfTable.addCell(new Paragraph(chargeAmount, font));
        pdfTable.addCell(new Paragraph(total, font));
        pdfTable.addCell(new Paragraph(amount, font));

        pdfTable.setWidthPercentage(100);
        if (pdfTable != null)
            document.add(pdfTable);

        //Keep modifying your pdf file (add pages and more)

        document.close();

        return baos.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}