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:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java

License:Apache License

/**
 * //from ww  w  .  j a v  a 2  s.  c om
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    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);
    int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH));
    int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE));

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

    int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X));
    int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y));

    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 AlfrescoRuntimeException("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = getReader(privateKey);
        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)) {
            //create the signature rectangle using either the provided position or
            //the exact coordinates, if provided
            if (position != null && !position.trim().equalsIgnoreCase("")) {
                Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber);
                sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null);
            } else {
                sap.setVisibleSignature(
                        new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber,
                        null);
            }
        }

        stamp.close();

        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);

        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();

        //if useAspect is true, store some additional info about the signature in the props
        if (useAspect) {
            serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED,
                    new HashMap<QName, Serializable>());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION,
                    location);
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE,
                    new java.util.Date());
            serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY,
                    AuthenticationUtil.getRunAsUser());
        }

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java

License:Apache License

/**
 * Create a rectangle for the visible signature using the selected position and signature size
 * //www .  j ava 2  s.  c om
 * @param position
 * @param width
 * @param height
 * @return
 */
private Rectangle positionSignature(String position, Rectangle pageRect, int width, int height) {

    float pageHeight = pageRect.getHeight();
    float pageWidth = pageRect.getWidth();

    Rectangle r = null;

    if (position.equals(POSITION_BOTTOMLEFT)) {
        r = new Rectangle(0, height, width, 0);
    } else if (position.equals(POSITION_BOTTOMRIGHT)) {
        r = new Rectangle(pageWidth - width, pageHeight, pageWidth, pageHeight - height);
    } else if (position.equals(POSITION_TOPLEFT)) {
        r = new Rectangle(0, pageHeight, width, pageHeight - height);
    } else if (position.equals(POSITION_TOPRIGHT)) {
        r = new Rectangle(pageWidth - width, height, pageWidth, 0);
    } else if (position.equals(POSITION_CENTER)) {
        r = new Rectangle((pageWidth / 2) - (width / 2), (pageHeight / 2) - (height / 2),
                (pageWidth / 2) + (width / 2), (pageHeight / 2) + (height / 2));
    }

    return r;
}

From source file:org.durel.mydooble.PDF.java

License:Open Source License

public void newCard() {
    col++;//  ww  w. j  av  a 2s. co m
    if (col > (COL_NUM - 1)) {
        col = 0;
        row++;
        if (row > (ROW_NUM - 1))
            newPage();
    }
    float x1 = col * (WIDTH + MARGIN) + MARGIN;
    float x2 = (col + 1) * (WIDTH + MARGIN);
    float y2 = (row + 1) * (HEIGHT + MARGIN);
    float y1 = row * (HEIGHT + MARGIN) + MARGIN;
    cardBox = new Rectangle(x1, y1, x2, y2);
    try {
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        cardBox.setBorderWidth(1.2f);
        cardBox.setBorderColor(BaseColor.BLACK);
        cardBox.setBorder(Rectangle.BOX);
        cb.rectangle(cardBox);
        cb.stroke();
        cb.restoreState();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.me.modelos.PDFHelper.java

public void tablaToPdf(JTable jTable, File pdfNewFile, String title) {
    try {// ww  w . jav a 2s . c  om
        Font subCategoryFont = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD);
        Document document = new Document(PageSize.LETTER.rotate());
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile));
        } catch (FileNotFoundException fileNotFoundException) {
            Message.showErrorMessage(fileNotFoundException.getMessage());
        }

        writer.setBoxSize("art", new Rectangle(150, 10, 700, 580));
        writer.setPageEvent(new HeaderFooterPageEvent());
        document.open();
        document.addTitle(title);

        document.addSubject("Reporte");
        document.addKeywords("reportes, gestion, pdf");
        document.addAuthor("Gestion de Proyectos de software");
        document.addCreator("gestion de proyectos");

        Paragraph parrafo = new Paragraph(title, subCategoryFont);

        PdfPTable table = new PdfPTable(jTable.getColumnCount());
        table.setWidthPercentage(100);
        PdfPCell columnHeader;

        for (int column = 0; column < jTable.getColumnCount(); column++) {
            Font font = new Font(Font.FontFamily.HELVETICA);
            font.setColor(255, 255, 255);
            columnHeader = new PdfPCell(new Phrase(jTable.getColumnName(column), font));
            columnHeader.setHorizontalAlignment(Element.ALIGN_LEFT);
            columnHeader.setBackgroundColor(new BaseColor(96, 125, 139));
            table.addCell(columnHeader);
        }
        table.getDefaultCell().setBackgroundColor(new BaseColor(255, 255, 255));
        table.setHeaderRows(1);
        BaseColor verdad = new BaseColor(255, 255, 255);
        BaseColor falso = new BaseColor(214, 230, 244);
        boolean bandera = false;
        for (int row = 0; row < jTable.getRowCount(); row++) {

            for (int column = 0; column < jTable.getColumnCount(); column++) {

                if (bandera) {
                    table.getDefaultCell().setBackgroundColor(verdad);
                } else {
                    table.getDefaultCell().setBackgroundColor(falso);
                }
                table.addCell(jTable.getValueAt(row, column).toString());
                bandera = !bandera;
            }

        }

        parrafo.add(table);
        document.add(parrafo);
        document.close();
        //JOptionPane.showMessageDialog(null, "Se ha creado el pdf en " + pdfNewFile.getPath(),
        //        "RESULTADO", JOptionPane.INFORMATION_MESSAGE);
    } catch (DocumentException documentException) {
        System.out.println("Se ha producido un error " + documentException);
        JOptionPane.showMessageDialog(null, "Se ha producido un error" + documentException, "ERROR",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.opencps.pki.PdfSigner.java

License:Open Source License

/**
 * Compute digest hash//from  w w w. jav a  2s . co  m
 */
protected byte[] computeDigest(float llx, float lly, float urx, float ury) throws SignatureException {
    byte digestHash[] = null;
    int contentEstimated = 8192;
    try {
        PdfReader reader = new PdfReader(getOriginFilePath());
        FileOutputStream os = new FileOutputStream(getTempFilePath());
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        signatureFieldName = appearance.getNewSigName();
        TSAClient tsaClient = null;
        appearance.setCertificate(getCertificate());
        String tsaUrl = CertificateUtil.getTSAURL(getCertificate());
        if (tsaUrl != null) {
            tsaClient = new TSAClientBouncyCastle(tsaUrl);
        }
        if (tsaClient != null) {
            LtvTimestamp.timestamp(appearance, tsaClient, signatureFieldName);
            contentEstimated += 4096;
        }

        appearance.setSignDate(signDate);
        CertificateInfo certInfo = new CertificateInfo(getCertificate());
        appearance.setLocation(certInfo.getOrganizationUnit());
        appearance.setReason("Document is signed by " + certInfo.getCommonName());
        appearance.setContact(certInfo.getCommonName());
        if (!isVisible) {
            appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureFieldName);
        } else {
            if (signatureImage != null) {
                appearance.setSignatureGraphic(signatureImage.getImage());
                appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
            } else {
                appearance.setLayer2Text(certInfo.getCommonName());
            }
            appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName);
        }

        ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE,
                PdfName.ADBE_PKCS7_DETACHED);
        MakeSignature.signExternalContainer(appearance, external, contentEstimated);

        digestHash = DigestAlgorithms.digest(appearance.getRangeStream(),
                digest.getMessageDigest(getHashAlgorithm().toString()));

        reader.close();
        os.close();
    } catch (Exception e) {
        throw new SignatureException(e.getMessage(), e);
    }
    return digestHash;
}

From source file:org.openmrs.module.laboratorymanagement.db.hibernate.LaboratoryDAOimpl.java

License:Open Source License

public void exportPatientReportToPDF(HttpServletRequest request, HttpServletResponse response,
        Map<ConceptName, List<Object[]>> mappedLabExam, String filename, String title, int patientId)
        throws DocumentException, IOException {

    Document document = new Document();
    Patient patient = Context.getPatientService().getPatient(patientId);
    // List<PatientBill> patientBills =
    // (List<PatientBill>)request.getAttribute("reportedPatientBillsPrint");

    /*/*  ww  w. j  av a  2s  . com*/
     * PatientBill pb = null;
     * 
     * pb = Context.getService(BillingService.class).getPatientBill(
     * Integer.parseInt(request.getParameter("patientBills")));
     */
    /*
     * String filename = pb.getBeneficiary().getPatient().getPersonName()
     * .toString().replace(" ", "_"); filename =
     * pb.getBeneficiary().getPolicyIdNumber().replace(" ", "_") + "_" +
     * filename + ".pdf";
     */
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "report"); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(0, 0, 2382, 3369));
    writer.setBoxSize("art", PageSize.A4);

    HeaderFooterMgt event = new HeaderFooterMgt();
    writer.setPageEvent(event);

    document.open();
    document.setPageSize(PageSize.A4);
    // document.setPageSize(new Rectangle(0, 0, 2382, 3369));

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().toString());// the name of the author

    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.COURIER, 10.0f, Font.ITALIC));

    // Report title
    Chunk chk = new Chunk("Printed on : " + (new SimpleDateFormat("dd-MMM-yyyy").format(new Date())));
    chk.setFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));
    Paragraph todayDate = new Paragraph();
    todayDate.setAlignment(Element.ALIGN_RIGHT);
    todayDate.add(chk);
    document.add(todayDate);
    document.add(fontTitle.process("REPUBLIQUE DU RWANDA\n"));
    document.add(fontTitle.process("POLICE NATIONALE\n"));
    document.add(fontTitle.process("KACYIRU POLICE HOSPITAL\n"));
    document.add(fontTitle.process("B.P. 6183 KIGALI\n"));
    document.add(fontTitle.process("Tl : 584897\n"));
    document.add(fontTitle.process("E-mail : medical@police.gov.rw"));
    // End Report title

    document.add(new Paragraph("\n"));
    chk = new Chunk("Laboratory results");
    chk.setFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));
    chk.setUnderline(0.2f, -2f);
    Paragraph pa = new Paragraph();
    pa.add(chk);
    pa.setAlignment(Element.ALIGN_CENTER);
    document.add(pa);
    document.add(new Paragraph("\n"));

    document.add(fontTitle.process("Family Name: " + patient.getFamilyName() + "\n"));
    document.add(fontTitle.process("Given name: " + patient.getGivenName() + "\n"));
    document.add(fontTitle.process("Age: " + patient.getAge() + "\n"));

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.COURIER, 9, Font.ITALIC));
    // Table of identification;
    PdfPTable table = null;
    table = new PdfPTable(2);
    table.setWidthPercentage(100f);

    // tableHeader.addCell(table);

    // document.add(tableHeader);

    document.add(new Paragraph("\n"));

    // Table of lab report items;
    float[] colsWidth = { 6f, 3f, 6f };
    table = new PdfPTable(colsWidth);
    table.setWidthPercentage(100f);
    BaseColor bckGroundTitle = new BaseColor(170, 170, 170);
    BaseColor bckGroundTitl = new BaseColor(Color.yellow);

    // table Header
    PdfPCell cell = new PdfPCell(fontTitleSelector.process("Exam"));

    cell.setBackgroundColor(bckGroundTitle);

    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process("Result"));
    cell.setBackgroundColor(bckGroundTitle);

    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process("Normal Range"));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);
    /*
     * cell = new PdfPCell(fontTitleSelector.process("Date "));
     * cell.setBackgroundColor(bckGroundTitle); table.addCell(cell);
     */

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    // empty row
    FontSelector fontTotals = new FontSelector();
    fontTotals.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));

    // ===========================================================
    for (ConceptName cptName : mappedLabExam.keySet()) {

        cell = new PdfPCell(fontTitleSelector.process("" + cptName));
        cell.setBackgroundColor(bckGroundTitl);

        table.addCell(cell);
        cell = new PdfPCell(fontTitleSelector.process(""));
        table.addCell(cell);
        cell = new PdfPCell(fontTitleSelector.process(""));
        table.addCell(cell);

        List<Object[]> labExamHistory = mappedLabExam.get(cptName);
        for (Object[] labExam : labExamHistory) {
            // table Header
            // Object[] labe = listOflabtest.get(i);
            Obs ob = (Obs) labExam[0];
            cell = new PdfPCell(fontTitleSelector.process("" + ob.getConcept().getName()));

            table.addCell(cell);
            if (ob.getConcept().getDatatype().isNumeric()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueNumeric()));
                table.addCell(cell);

            }

            if (ob.getConcept().getDatatype().isCoded()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueCoded().getName()));
                table.addCell(cell);

            }

            if (ob.getConcept().getDatatype().isText()) {
                cell = new PdfPCell(fontTitleSelector.process("" + ob.getValueText()));
                table.addCell(cell);

            }

            cell = new PdfPCell(fontTitleSelector.process("" + (labExam[1] != null ? labExam[1] : "-")));
            table.addCell(cell);

            fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

            // empty row
            // FontSelector fontTotals = new FontSelector();
            fontTotals.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));

        }

    }

    cell = new PdfPCell(fontTitleSelector.process("Names, Signature et Stamp of Lab Chief\n"
            //+ Context.getAuthenticatedUser().getPersonName()));
            + Context.getUserService().getUser(140).getPersonName()));

    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);
    // ================================================================
    table.addCell(cell);

    document.add(table);

    // Table of signatures;
    table = new PdfPTable(2);
    table.setWidthPercentage(100f);

    cell = new PdfPCell(fontTitleSelector.process(" "));

    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(
            "Names, Signature and  Stamp of Provider\n" + Context.getAuthenticatedUser().getPersonName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);
    document.add(table);
    document.close();

    document.close();
}

From source file:org.openmrs.module.mohtracportal.util.FileExporter.java

License:Open Source License

/**
 * @param request//from  w  ww.j  a va 2s  .c  o  m
 * @param response
 * @param res
 * @param filename
 * @param title
 * @param from
 * @param to
 * @param selectedUsers
 * @throws Exception
 */
public void exportToPDF(HttpServletRequest request, HttpServletResponse response, List<Object> res,
        String filename, String title, String from, String to, List<Integer> selectedUsers) throws Exception {
    SimpleDateFormat sdf = Context.getDateFormat();
    Document document = new Document();

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    HeaderFooter event = new HeaderFooter();
    writer.setPageEvent(event);

    document.open();
    document.setPageSize(PageSize.A4);

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().getFamilyName() + " "
            + Context.getAuthenticatedUser().getPersonName().getGivenName());// the name of the author

    PersonService ps = Context.getPersonService();

    String users = "";
    for (Integer usrId : selectedUsers) {
        users += ps.getPerson(usrId).getPersonName() + "; ";
    }

    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.COURIER, 10.0f, Font.BOLD));

    title = MohTracUtil.getMessage("mohtracportal.report.title", null) + "      : " + title;
    String underLine = "";
    int count = 0;
    while (count < title.length()) {
        count += 1;
        underLine += "_";
    }

    document.add(fontTitle.process(title));// Report title
    if (from.trim().compareTo("") != 0)
        document.add(fontTitle
                .process("\n" + MohTracUtil.getMessage("mohtracportal.from", null) + "      : " + from));// from
    if (to.trim().compareTo("") != 0)
        document.add(
                fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.to", null) + "        : " + to));// to
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.report.created.on", null)
            + " : " + sdf.format(new Date())));// Report date
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.report.created.by", null)
            + " : " + Context.getAuthenticatedUser().getPersonName()));// Report
    // author

    Integer numberOfPatients = res.size();
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("mohtracportal.numberOfPatients", null) + " : "
            + numberOfPatients.toString()));// Number of patients

    if (users.trim().compareTo("") != 0)
        document.add(fontTitle.process(
                "\n" + MohTracUtil.getMessage("mohtracportal.patient.enterers", null) + " : " + users));// enterer(s)
    document.add(fontTitle.process("\n" + underLine));// Report title
    document.add(new Paragraph("\n\n"));

    boolean hasPrivToViewPatientNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

    // PdfLine line;
    PdfPTable table = null;
    if (hasPrivToViewPatientNames == true) {
        float[] colsWidth = { 1.2f, 5f, 2.7f, 2.7f, 4.2f, 2.7f };
        table = new PdfPTable(colsWidth);
    } else {
        float[] colsWidth = { 1.2f, 2.7f, 2.7f, 4.2f, 2.7f };
        table = new PdfPTable(colsWidth);
    }

    // column number
    table.setTotalWidth(540f);

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.COURIER, 9, Font.BOLD));
    BaseColor bckGroundTitle = new BaseColor(170, 170, 170);

    // table Header
    PdfPCell cell = new PdfPCell(
            fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.report.list.no", null)));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    if (hasPrivToViewPatientNames) {
        cell = new PdfPCell(
                fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.patient.names", null)));
        cell.setBackgroundColor(bckGroundTitle);
        table.addCell(cell);
    }

    cell = new PdfPCell(fontTitleSelector.process(MohTracPortalTag
            .getIdentifierTypeNameByIdAsString("" + MohTracConfigurationUtil.getTracNetIdentifierTypeId())));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(MohTracPortalTag.getIdentifierTypeNameByIdAsString(
            "" + MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId())));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.patient.date.created", null) + "("
                    + Context.getDateFormat().toPattern() + ")"));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(MohTracUtil.getMessage("mohtracportal.numberOfEncounters", null)));
    cell.setBackgroundColor(bckGroundTitle);
    table.addCell(cell);

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    // empty row
    FontSelector fontEmptyCell = new FontSelector();
    fontEmptyCell.addFont(new Font(FontFamily.COURIER, 8, Font.NORMAL));

    int ids = 0;

    for (Object patient : res) {
        Object[] o = (Object[]) patient;
        ids += 1;

        cell = new PdfPCell(fontselector.process(ids + ""));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        if (hasPrivToViewPatientNames) {
            String names = MohTracPortalTag.getPersonNames(Integer.valueOf(o[0].toString()));
            cell = new PdfPCell(fontselector.process(names + ""));
            if (names.compareTo("-") == 0)
                cell.setBackgroundColor(new BaseColor(224, 224, 240));
            if (o[2].toString().compareTo("1") == 0)
                cell.setBackgroundColor(new BaseColor(238, 238, 238));
            if (o[3].toString().compareTo("1") == 0)
                cell.setBackgroundColor(new BaseColor(224, 0, 0));
            table.addCell(cell);
        }

        String tracnetId = MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                Integer.valueOf(o[0].toString()), MohTracConfigurationUtil.getTracNetIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(tracnetId + ""));
        if (tracnetId.compareTo("-") == 0)
            cell.setBackgroundColor(new BaseColor(224, 224, 240));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        String cohortId = MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId(
                Integer.valueOf(o[0].toString()),
                MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(cohortId + ""));
        if (cohortId.compareTo("-") == 0)
            cell.setBackgroundColor(new BaseColor(224, 224, 240));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        cell = new PdfPCell(fontselector.process(sdf.format(o[1]) + ""));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);

        String numberOfEncounters = MohTracPortalTag
                .getNumberOfEncounterByPatient(Integer.valueOf(o[0].toString()));
        cell = new PdfPCell(fontselector.process(numberOfEncounters + ""));
        if (numberOfEncounters.compareTo("-") == 0)
            cell.setBackgroundColor(new BaseColor(224, 224, 240));
        if (o[2].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(238, 238, 238));
        if (o[3].toString().compareTo("1") == 0)
            cell.setBackgroundColor(new BaseColor(224, 0, 0));
        table.addCell(cell);
    }

    document.add(table);
    document.close();

    log.info("pdf file created");
}

From source file:org.openmrs.module.tracpatienttransfer.util.FileExporter.java

License:Open Source License

/**
 * @param request// w  w w .j a v  a  2s  .  c  om
 * @param response
 * @param res
 * @param filename
 * @param title
 * @throws Exception
 */
public void exportToPDF(HttpServletRequest request, HttpServletResponse response, List<Integer> res,
        String filename, String title) throws Exception {

    SimpleDateFormat sdf = Context.getDateFormat();

    Document document = new Document();

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // file name

    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    float[] colsWidth = { 1.6f, 2.7f, 2.7f, 8f, 10.5f, 4f, 5f, 7.5f };//, 9.3f };
    PdfPTable table = new PdfPTable(colsWidth); // column number

    HeaderFooter event = new HeaderFooter(table);
    writer.setPageEvent(event);

    document.setPageSize(PageSize.A4.rotate());
    document.open();

    document.addAuthor(Context.getAuthenticatedUser().getPersonName().getFamilyName() + " "
            + Context.getAuthenticatedUser().getPersonName().getGivenName());// the name of the author

    ObsService os = Context.getObsService();
    FontSelector fontTitle = new FontSelector();
    fontTitle.addFont(new Font(FontFamily.HELVETICA, 8.0f, Font.BOLD));
    document.add(
            fontTitle.process(MohTracUtil.getMessage("tracpatienttransfer.report", null) + "    : " + title));// Report title
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdon", null)
            + " : " + sdf.format(new Date())));// Report date
    document.add(fontTitle.process("\n" + MohTracUtil.getMessage("tracpatienttransfer.report.createdby", null)
            + " : " + Context.getAuthenticatedUser().getPersonName()));// Report
    // author
    document.add(new Paragraph("\n"));

    Paragraph para = new Paragraph("" + title.toUpperCase());
    para.setAlignment(Element.ALIGN_CENTER);
    para.setFont(new Font(FontFamily.HELVETICA, 8.0f, Font.BOLD));
    document.add(para);

    table.setWidthPercentage(100.0f);

    // title row
    FontSelector fontTitleSelector = new FontSelector();
    fontTitleSelector.addFont(new Font(FontFamily.HELVETICA, 8, Font.BOLD));

    // top line of table
    for (int i = 0; i < 8; i++) {
        PdfPCell pdfPCell = new PdfPCell(fontTitleSelector.process(" "));
        pdfPCell.setBorder(PdfPCell.BOTTOM);
        table.addCell(pdfPCell);
    }

    boolean hasRoleToViewPatientsNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names");

    // table Header
    PdfPCell cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.number")));
    cell.setBorder(Rectangle.LEFT);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(Context.getPatientService()
            .getPatientIdentifierType(TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId())
            .getName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(Context.getPatientService()
                    .getPatientIdentifierType(
                            TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId())
                    .getName()));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    if (hasRoleToViewPatientsNames) {
        cell = new PdfPCell(
                fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.names")));
        cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);
    }

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.reasonofexit")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.general.exitwhen")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(fontTitleSelector.process(ContextProvider.getMessage("Encounter.provider")));
    cell.setBorder(Rectangle.NO_BORDER);
    table.addCell(cell);

    cell = new PdfPCell(
            fontTitleSelector.process(ContextProvider.getMessage("tracpatienttransfer.report.location")));
    cell.setBorder(Rectangle.RIGHT);
    table.addCell(cell);

    //      cell = new PdfPCell(fontTitleSelector
    //            .process("Resumed? (reason - by who?)"));
    //      cell.setBorder(Rectangle.RIGHT);
    //      table.addCell(cell);

    // normal row
    FontSelector fontselector = new FontSelector();
    fontselector.addFont(new Font(FontFamily.HELVETICA, 7, Font.NORMAL));

    // empty row
    FontSelector fontEmptyCell = new FontSelector();
    fontEmptyCell.addFont(new Font(FontFamily.HELVETICA, 7, Font.NORMAL));

    int ids = 0;

    for (Integer obsId : res) {
        Obs obs = os.getObs(obsId);
        Integer patientId = obs.getPersonId();
        ids += 1;

        cell = new PdfPCell(fontselector.process(ids + "."));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        String tracnetId = TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(patientId,
                TracPatientTransferConfigurationUtil.getTracNetIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(tracnetId + ""));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        String localIdentifierTypeId = TransferOutInPatientTag.personIdentifierByPatientIdAndIdentifierTypeId(
                patientId, TracPatientTransferConfigurationUtil.getLocalHealthCenterIdentifierTypeId());
        cell = new PdfPCell(fontselector.process(localIdentifierTypeId + ""));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        if (hasRoleToViewPatientsNames) {
            String names = TransferOutInPatientTag.getPersonNames(patientId);
            cell = new PdfPCell(fontselector.process(names + ""));
            if (ids == 1)
                cell.setBorder(Rectangle.TOP);
            else
                cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
        }

        String conceptValue = TransferOutInPatientTag.conceptValueByObs(obs);

        conceptValue += ((obs.getValueCoded().getConceptId()
                .intValue() == TransferOutInPatientConstant.PATIENT_TRANSFERED_OUT)
                        ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                TransferOutInPatientConstant.TRANSFER_OUT_TO_A_LOCATION) + ")"
                        : (obs.getValueCoded().getConceptId()
                                .intValue() == TransferOutInPatientConstant.PATIENT_DEAD)
                                        ? " (" + TransferOutInPatientTag.getObservationValueFromEncounter(obs,
                                                TransferOutInPatientConstant.CAUSE_OF_DEATH) + ")"
                                        : "");

        cell = new PdfPCell(fontselector.process(conceptValue));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        cell = new PdfPCell(fontselector.process(sdf.format(obs.getObsDatetime())));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        /*
         * cell=newPdfPCell(fontselector.process(TransferOutInPatientTag.
         * getProviderByObs(obs))); if(ids==1)
         * cell.setBorder(Rectangle.TOP); else
         * cell.setBorder(Rectangle.NO_BORDER);
         */table.addCell(cell);

        cell = new PdfPCell(fontselector.process(obs.getLocation().getName()));
        if (ids == 1)
            cell.setBorder(Rectangle.TOP);
        else
            cell.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell);

        //         cell = new PdfPCell(fontselector.process(TransferOutInPatientTag
        //               .obsVoidedReason(obs)));
        //         if (ids == 1)
        //            cell.setBorder(Rectangle.TOP);
        //         else
        //            cell.setBorder(Rectangle.NO_BORDER);
        //         table.addCell(cell);
    }

    document.add(table);
    document.close();

    log.info("pdf file created");
}

From source file:org.roda.common.certification.PDFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String reason, String location, String contact)
        throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path signedPDF = Files.createTempFile("signed", ".pdf");

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    IOUtils.closeQuietly(is);//from  w w w  .ja v a  2  s  . co  m

    PdfReader reader = new PdfReader(input.toString());
    FileOutputStream os = new FileOutputStream(signedPDF.toFile());
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    appearance.setContact(contact);
    appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature");
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
    MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null);
    IOUtils.closeQuietly(os);
    reader.close();

    return signedPDF;
}

From source file:org.roda.core.plugins.plugins.characterization.PDFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String reason, String location, String contact)
        throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path signedPDF = Files.createTempFile("signed", ".pdf");

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream is = new FileInputStream(keystore)) {
        ks.load(is, password.toCharArray());

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

        try (FileOutputStream os = new FileOutputStream(signedPDF.toFile())) {
            PdfReader reader = new PdfReader(input.toString());
            PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
            PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
            appearance.setReason(reason);
            appearance.setLocation(location);
            appearance.setContact(contact);
            appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature");
            ExternalDigest digest = new BouncyCastleDigest();
            ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
            MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null);
            reader.close();//from   w  ww . j a va  2s . c o  m
        }
    }

    return signedPDF;
}