Example usage for org.apache.pdfbox.pdmodel PDPage PDPage

List of usage examples for org.apache.pdfbox.pdmodel PDPage PDPage

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage PDPage.

Prototype

public PDPage(COSDictionary pageDictionary) 

Source Link

Document

Creates a new instance of PDPage for reading.

Usage

From source file:mail.java

private void bonos() throws SQLException {
    //**/*from w w w  .j a va2s  . c  o m*/
    double total = 0;
    ListaBono.clear();
    if (idmatricula != "0") {
        Connection conn;
        try {
            conn = Conector.Connect();

            System.out.println("Bonos");

            PreparedStatement resultado;
            PreparedStatement bono;
            String sql1 = "select * from bonos b left join juzgados j on b.ID_JUZGADO=j.id_juzgado where ID_MATRICULA=? ORDER BY ANO  ";
            bono = conn.prepareStatement(sql1);

            bono.setString(1, idmatricula);
            ResultSet ds = bono.executeQuery();
            DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
            SimpleDateFormat formatofecha = new SimpleDateFormat("dd-MM-yyyy");
            simbolos.setDecimalSeparator('.');
            DecimalFormat decim = new DecimalFormat("0.00", simbolos);
            if (ds.first()) {

                ds.beforeFirst();//regresa el puntero al primer registro
                while (ds.next()) {
                    int numero_expediente = ds.getInt("NUMERO_EXPTE");
                    String ano = ds.getString("ANO");
                    String caratula = ds.getString("cara");
                    String fecha_actuacion = ds.getString("FECHA_ACTUACION");
                    String juzgado = ds.getString("descripcion");
                    double importe = ds.getDouble("MONTOBONO");

                    Double monto_bono = Double.valueOf(decim.format(importe));
                    caratula = caratula.replaceAll("\r\n", " ");
                    caratula = caratula.replaceAll("\n", " ");
                    caratula = caratula.replaceAll("\\\\\\\\", "");

                    //                                    Date per =formatofecha.parse(fecha_pa);
                    //                                   String fecha_pago = formatofecha.format(per);
                    System.out.println(idmatricula);
                    System.out.format("%s,%s,%s,%s,%s,%s\n", numero_expediente, ano, caratula.toLowerCase(),
                            juzgado.toLowerCase(), fecha_actuacion, importe);

                    ListaBono.add(
                            new Bonos(numero_expediente, ano, caratula, juzgado, fecha_actuacion, monto_bono));
                    total = total + monto_bono;

                    botones(true);

                }

                ds.close();
                System.out.println(total);
                System.out.println(ListaBono.size());
            }
        } catch (SQLException ex) {
            Logger.getLogger(mail.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //**
    int alto = 595;
    int ancho = 842;
    PDDocument documento = new PDDocument();
    PDPage paginablanco = new PDPage(new PDRectangle(ancho, alto));

    documento.addPage(paginablanco);
    PDPageContentStream content;
    System.out.println(paginablanco.getMediaBox().getHeight() + "--" + paginablanco.getMediaBox().getWidth());

    try {
        content = new PDPageContentStream(documento, paginablanco);

        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 9);
        content.newLineAtOffset(50, alto - 20);
        content.showText("Consejo Profesional de Abogacia");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 9);
        content.newLineAtOffset(450, alto - 20);
        Locale espanol = new Locale("es", "ES");
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE MMMM d HH:mm:ss z yyyy", espanol);
        String fecha = dateFormat.format(new Date());
        content.showText(fecha);
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 6);
        content.newLineAtOffset(50, alto - 28);
        content.showText("Direccin: San Martin 457 - Formosa");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 10);
        content.newLineAtOffset(200, alto - 38);
        content.showText("BONOS DE ACCCIN LETRADA");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(200, alto - 45);
        content.showText("Estado de Gestin de bonos del Profesional");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 9);
        content.newLineAtOffset(50, alto - 60);
        // para que no tenga errores las tabla de mysql cotejamiento en utf8_bin al cargar en la PDF da error si esta con el tema de las 
        content.showText("Matricula N: " + idmatricula + "       Nombre:     " + nombre + "," + apellido);//
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(50, alto - 75);
        content.showText("Item");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(70, alto - 75);
        content.showText("Expte");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(100, alto - 75);
        content.showText("Ao");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(130, alto - 75);
        content.showText("Caratula");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(500, alto - 75);
        content.showText("Juzgado");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(650, alto - 75);
        content.showText("Monto");
        content.endText();
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 8);
        content.newLineAtOffset(680, alto - 75);
        content.showText("Vencimiento");
        content.endText();
        content.setNonStrokingColor(Color.DARK_GRAY);
        content.addRect(25, 45, 700, 400);
        //            content.fill();
        int j = 0;
        int renglon = alto - 100;

        for (int i = 0; i < ListaBono.size(); i++) {

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            j++;
            content.newLineAtOffset(50, renglon);
            content.showText(String.valueOf(i + 1));
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(70, renglon);
            content.showText(String.valueOf(ListaBono.get(i).getNumero_expediente()));
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(100, renglon);
            content.showText(ListaBono.get(i).getAno());
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(130, renglon);
            content.showText(String.valueOf(ListaBono.get(i).getCaratula()));
            content.endText();
            content.setFont(PDType1Font.COURIER, 8);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(500, renglon);
            content.showText(ListaBono.get(i).getJuzgado());
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(650, renglon);
            content.showText(String.valueOf(ListaBono.get(i).getMonto_bono()));
            content.endText();

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 8);
            content.newLineAtOffset(680, renglon);
            content.showText(ListaBono.get(i).getFecha_pago());
            content.endText();

            renglon = renglon - 13;
        }

        content.beginText();
        content.newLineAtOffset(100, renglon - 20);
        DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
        simbolos.setDecimalSeparator('.');
        DecimalFormat decim = new DecimalFormat("0.00", simbolos);

        content.showText("Total Bonos Adeudados           :$ " + String.valueOf(decim.format(total)));
        content.endText();
        content.close();

        documento.save("matricula_" + idmatricula + "_bonos.pdf");
        documento.close();
        System.out.println("guardo archivo matricula_" + idmatricula + "_bonos.pdf");
        //            System.out.println(String.valueOf(decim.format(total)));

        EnviarMail.setEnabled(true);

    } catch (IOException ex) {
        EnviarMail.setEnabled(false);
        Logger.getLogger(mail.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ambroafb.general.PDFHelper.java

public void replace(BufferedImage img, int index) throws IOException {
    PDPage old = doc.getPage(index);//  w w w .  ja  va  2 s .  c  om
    float width, height;
    if (img.getWidth() > img.getHeight()) {
        width = PDRectangle.LETTER.getHeight();
        height = PDRectangle.LETTER.getWidth();
    } else {
        height = PDRectangle.LETTER.getHeight();
        width = PDRectangle.LETTER.getWidth();
    }
    PDPage newPage = new PDPage(new PDRectangle(width, height));
    doc.getPages().insertAfter(newPage, old);
    doc.removePage(old);
    PDImageXObject pdImage = JPEGFactory.createFromImage(doc, img);
    try (PDPageContentStream contents = new PDPageContentStream(doc, newPage)) {
        contents.drawImage(pdImage, 0, 0, width, height);
    }
}

From source file:at.asitplus.regkassen.core.modules.print.SimplePDFPrinterModule.java

License:Apache License

@Override
public byte[] printReceipt(final ReceiptPackage receiptPackage, final ReceiptPrintType receiptPrintType) {
    //TODO Training/Storno!
    try {/*from w  ww  .  j av a 2s.  c  o m*/
        //init PDF document
        final PDDocument document = new PDDocument();
        final PDPage page = new PDPage(PDPage.PAGE_SIZE_A6);
        document.addPage(page);

        //init content objects
        final PDRectangle rect = page.getMediaBox();
        final PDPageContentStream cos = new PDPageContentStream(document, page);

        //add taxtype-sums
        int line = 1;
        //get string that will be encoded as QR-Code
        final String qrCodeRepresentation = CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                receiptPackage.getJwsCompactRepresentation());

        addTaxTypeToPDF(cos, rect, line++,
                CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation, MachineCodeValue.SUM_TAX_SET_NORMAL),
                TaxType.SATZ_NORMAL);
        addTaxTypeToPDF(cos, rect, line++, CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SUM_TAX_SET_ERMAESSIGT1), TaxType.SATZ_ERMAESSIGT_1);
        addTaxTypeToPDF(cos, rect, line++, CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SUM_TAX_SET_ERMAESSIGT2), TaxType.SATZ_ERMAESSIGT_2);
        addTaxTypeToPDF(cos, rect, line++, CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SUM_TAX_SET_BESONDERS), TaxType.SATZ_BESONDERS);
        addTaxTypeToPDF(cos, rect, line++,
                CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation, MachineCodeValue.SUM_TAX_SET_NULL),
                TaxType.SATZ_NULL);

        final String signatureValue = CashBoxUtils.getValueFromMachineCode(qrCodeRepresentation,
                MachineCodeValue.SIGNATURE_VALUE);
        final String decodedSignatureValue = new String(CashBoxUtils.base64Decode(signatureValue, false));
        final boolean secDeviceWasDamaged = "Sicherheitseinrichtung ausgefallen".equals(decodedSignatureValue);
        if (secDeviceWasDamaged) {
            final PDFont fontPlain = PDType1Font.HELVETICA;
            cos.beginText();
            cos.setFont(fontPlain, 8);
            cos.moveTextPositionByAmount(20, rect.getHeight() - 20 * (line));
            cos.drawString("SICHERHEITSEINRICHTUNG AUSGEFALLEN");
            cos.endText();
            line++;
        }

        //add OCR code or QR-code
        if (receiptPrintType == ReceiptPrintType.OCR) {
            addOCRCodeToPDF(document, cos, rect, line++, receiptPackage);
        } else {
            //create QRCode
            final BufferedImage image = createQRCode(receiptPackage);
            //add QRCode to PDF document
            final PDXObjectImage ximage = new PDPixelMap(document, image);
            final float scale = 2f; // alter this value to set the image size
            cos.drawXObject(ximage, 25, 0, ximage.getWidth() * scale, ximage.getHeight() * scale);
        }
        cos.close();

        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        document.save(bOut);
        document.close();
        return bOut.toByteArray();

    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final COSVisitorException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

License:EUPL

public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature,
        PDFASSignatureInterface genericSigner) throws PdfAsException {
    String fisTmpFile = null;//  ww  w  .j  a v a2s  .  c  o m

    PDFAsVisualSignatureProperties properties = null;

    if (!(genericPdfObject instanceof PDFBOXObject)) {
        // tODO:
        throw new PdfAsException();
    }

    PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject;

    if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) {
        // tODO:
        throw new PdfAsException();
    }

    PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner;

    TempFileHelper helper = pdfObject.getStatus().getTempFileHelper();
    PDDocument doc = pdfObject.getDocument();
    SignatureOptions options = new SignatureOptions();
    COSDocument visualSignatureDocumentGuard = null;
    try {
        fisTmpFile = helper.getStaticFilename();

        FileOutputStream tmpOutputStream = null;
        try {
            // write to temporary file
            tmpOutputStream = new FileOutputStream(new File(fisTmpFile));
            InputStream tmpis = null;
            try {
                tmpis = pdfObject.getOriginalDocument().getInputStream();
                IOUtils.copy(tmpis, tmpOutputStream);
                tmpis.close();
            } finally {
                IOUtils.closeQuietly(tmpis);
            }

            SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter
                    .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings());

            TablePos tablePos = null;

            if (signaturePlaceholderData != null) {
                // Placeholder found!
                logger.info("Placeholder data found.");
                if (signaturePlaceholderData.getProfile() != null) {
                    logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile());
                    requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile());
                }

                tablePos = signaturePlaceholderData.getTablePos();
                if (tablePos != null) {

                    SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                            .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

                    float minWidth = signatureProfileConfiguration.getMinWidth();

                    if (minWidth > 0) {
                        if (tablePos.getWidth() < minWidth) {
                            tablePos.width = minWidth;
                            logger.debug("Correcting placeholder with to minimum width {}", minWidth);
                        }
                    }
                    logger.debug("Placeholder Position set to: " + tablePos.toString());
                }
            }

            PDSignature signature = new PDSignature();
            signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default
            // filter
            signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter()));

            SignatureProfileSettings signatureProfileSettings = TableFactory.createProfile(
                    requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

            ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus());
            String signerName = resolver.resolve("SIG_SUBJECT",
                    signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings);

            signature.setName(signerName);

            // take signing time from provided signer...
            signature.setSignDate(signer.getSigningDate());
            // ...and update operation status in order to use exactly this date for the complete signing process
            requestedSignature.getStatus().setSigningDate(signer.getSigningDate());

            String signerReason = signatureProfileSettings.getSigningReason();

            if (signerReason == null) {
                signerReason = "PAdES Signature";
            }

            signature.setReason(signerReason);
            logger.debug("Signing reason: " + signerReason);

            logger.debug("Signing @ " + signer.getSigningDate().getTime().toString());

            // the signing date, needed for valid signature
            // signature.setSignDate(signer.getSigningDate());

            signer.setPDSignature(signature);

            int signatureSize = 0x1000;
            try {
                String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE);
                if (reservedSignatureSizeString != null) {
                    signatureSize = Integer.parseInt(reservedSignatureSizeString);
                }
                logger.debug("Reserving {} bytes for signature", signatureSize);
            } catch (NumberFormatException e) {
                logger.warn("Invalid configuration value: {} should be a number using 0x1000",
                        SIG_RESERVED_SIZE);
            }
            options.setPreferedSignatureSize(signatureSize);

            // Is visible Signature
            if (requestedSignature.isVisual()) {
                logger.debug("Creating visual signature block");

                SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                        .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

                if (tablePos == null) {
                    // ================================================================
                    // PositioningStage (visual) -> find position or use
                    // fixed
                    // position

                    String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition();

                    TablePos signaturePos = null;

                    String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();

                    if (signaturePosString != null) {
                        logger.debug("using signature Positioning: " + signaturePos);
                        signaturePos = new TablePos(signaturePosString);
                    }

                    logger.debug("using Positioning: " + posString);

                    if (posString != null) {
                        // Merge Signature Position
                        tablePos = new TablePos(posString, signaturePos);
                    } else {
                        // Fallback to signature Position!
                        tablePos = signaturePos;
                    }

                    if (tablePos == null) {
                        // Last Fallback default position
                        tablePos = new TablePos();
                    }
                }
                boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning();
                boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning();

                // create Table describtion
                Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                        requestedSignature);

                IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

                IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

                /*
                 * PDDocument originalDocument = PDDocument .load(new
                 * ByteArrayInputStream(pdfObject.getStatus()
                 * .getPdfObject().getOriginalDocument()));
                 */

                PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos,
                        "", doc, visualObject, legacy32Position, legacy40Position);

                logger.debug("Positioning: {}", positioningInstruction.toString());

                if (positioningInstruction.isMakeNewPage()) {
                    int last = doc.getNumberOfPages() - 1;
                    PDDocumentCatalog root = doc.getDocumentCatalog();
                    PDPageNode rootPages = root.getPages();
                    List<PDPage> kids = new ArrayList<PDPage>();
                    rootPages.getAllKids(kids);
                    PDPage lastPage = kids.get(last);
                    rootPages.getCOSObject().setNeedToBeUpdate(true);
                    PDPage p = new PDPage(lastPage.findMediaBox());
                    p.setResources(new PDResources());
                    p.setRotation(lastPage.findRotation());
                    doc.addPage(p);
                }

                // handle rotated page
                PDDocumentCatalog documentCatalog = doc.getDocumentCatalog();
                PDPageNode documentPages = documentCatalog.getPages();
                List<PDPage> documentPagesKids = new ArrayList<PDPage>();
                documentPages.getAllKids(documentPagesKids);
                int targetPageNumber = positioningInstruction.getPage();
                logger.debug("Target Page: " + targetPageNumber);
                // rootPages.getAllKids(kids);
                PDPage targetPage = documentPagesKids.get(targetPageNumber - 1);
                int rot = targetPage.findRotation();
                logger.debug("Page rotation: " + rot);
                // positioningInstruction.setRotation(positioningInstruction.getRotation()
                // + rot);
                logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation());

                SignaturePositionImpl position = new SignaturePositionImpl();
                position.setX(positioningInstruction.getX());
                position.setY(positioningInstruction.getY());
                position.setPage(positioningInstruction.getPage());
                position.setHeight(visualObject.getHeight());
                position.setWidth(visualObject.getWidth());

                requestedSignature.setSignaturePosition(position);

                properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject,
                        (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings);

                properties.buildSignature();

                /*
                 * ByteArrayOutputStream sigbos = new
                 * ByteArrayOutputStream();
                 * sigbos.write(StreamUtils.inputStreamToByteArray
                 * (properties .getVisibleSignature())); sigbos.close();
                 */

                if (signaturePlaceholderData != null) {
                    // Placeholder found!
                    // replace placeholder
                    InputStream is = null;
                    try {
                        is = PADESPDFBOXSigner.class.getResourceAsStream("/placeholder/empty.jpg");
                        PDJpeg img = new PDJpeg(doc, is);

                        img.getCOSObject().setNeedToBeUpdate(true);

                        PDDocumentCatalog root = doc.getDocumentCatalog();
                        PDPageNode rootPages = root.getPages();
                        List<PDPage> kids = new ArrayList<PDPage>();
                        rootPages.getAllKids(kids);
                        int pageNumber = positioningInstruction.getPage();
                        // rootPages.getAllKids(kids);
                        PDPage page = kids.get(pageNumber - 1);

                        logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());
                        COSDictionary xobjectsDictionary = (COSDictionary) page.findResources()
                                .getCOSDictionary().getDictionaryObject(COSName.XOBJECT);
                        xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img);
                        xobjectsDictionary.setNeedToBeUpdate(true);
                        page.findResources().getCOSObject().setNeedToBeUpdate(true);
                        logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());
                    } finally {
                        IOUtils.closeQuietly(is);
                    }
                }

                if (signatureProfileSettings.isPDFA()) {
                    PDDocumentCatalog root = doc.getDocumentCatalog();
                    COSBase base = root.getCOSDictionary().getItem(COSName.OUTPUT_INTENTS);
                    if (base == null) {
                        InputStream colorProfile = null;
                        try {
                            colorProfile = PDDocumentCatalog.class
                                    .getResourceAsStream("/icm/sRGB Color Space Profile.icm");

                            try {
                                PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
                                oi.setInfo("sRGB IEC61966-2.1");
                                oi.setOutputCondition("sRGB IEC61966-2.1");
                                oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
                                oi.setRegistryName("http://www.color.org");

                                root.addOutputIntent(oi);
                                root.getCOSObject().setNeedToBeUpdate(true);
                                logger.info("added Output Intent");
                            } catch (Throwable e) {
                                throw new PdfAsException("Failed to add Output Intent", e);
                            }
                        } finally {
                            IOUtils.closeQuietly(colorProfile);
                        }
                    }
                }

                options.setPage(positioningInstruction.getPage());

                options.setVisualSignature(properties.getVisibleSignature());
            }

            visualSignatureDocumentGuard = options.getVisualSignature();

            doc.addSignature(signature, signer, options);

            // set need to update indirect fields array in acro form
            COSDictionary trailer = doc.getDocument().getTrailer();
            if (trailer != null) {
                COSDictionary troot = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
                if (troot != null) {
                    COSDictionary acroForm = (COSDictionary) troot.getDictionaryObject(COSName.ACRO_FORM);
                    if (acroForm != null) {
                        COSArray tfields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
                        if (tfields != null && !tfields.isDirect()) {
                            tfields.setNeedToBeUpdate(true);
                        }
                    }
                }
            }

            String sigFieldName = signatureProfileSettings.getSignFieldValue();

            if (sigFieldName == null) {
                sigFieldName = "PDF-AS Signatur";
            }

            int count = PdfBoxUtils.countSignatures(doc, sigFieldName);

            sigFieldName = sigFieldName + count;

            PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm();

            PDSignatureField signatureField = null;
            if (acroFormm != null) {
                @SuppressWarnings("unchecked")
                List<PDField> fields = acroFormm.getFields();

                if (fields != null) {
                    for (PDField pdField : fields) {
                        if (pdField != null) {
                            if (pdField instanceof PDSignatureField) {
                                PDSignatureField tmpSigField = (PDSignatureField) pdField;

                                if (tmpSigField.getSignature() != null
                                        && tmpSigField.getSignature().getDictionary() != null) {
                                    if (tmpSigField.getSignature().getDictionary()
                                            .equals(signature.getDictionary())) {
                                        signatureField = (PDSignatureField) pdField;

                                    }
                                }
                            }
                        }
                    }
                } else {
                    logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]");
                }

                if (signatureField != null) {
                    signatureField.setPartialName(sigFieldName);
                }
                if (properties != null) {
                    signatureField.setAlternateFieldName(properties.getAlternativeTableCaption());
                } else {
                    signatureField.setAlternateFieldName(sigFieldName);
                }
            } else {
                logger.warn("Failed to name Signature Field! [Cannot find acroForm!]");
            }

            // PDF-UA
            logger.info("Adding pdf/ua content.");
            try {
                PDDocumentCatalog root = doc.getDocumentCatalog();
                PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot();
                if (structureTreeRoot != null) {
                    logger.info("Tree Root: {}", structureTreeRoot.toString());
                    List<Object> kids = structureTreeRoot.getKids();

                    if (kids == null) {
                        logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document");
                    }

                    PDStructureElement docElement = null;
                    for (Object k : kids) {
                        if (k instanceof PDStructureElement) {
                            docElement = (PDStructureElement) k;
                            break;

                        }
                    }

                    PDStructureElement sigBlock = new PDStructureElement("Form", docElement);

                    // create object dictionary and add as child element
                    COSDictionary objectDic = new COSDictionary();
                    objectDic.setName("Type", "OBJR");
                    objectDic.setItem("Pg", signatureField.getWidget().getPage());
                    objectDic.setItem("Obj", signatureField.getWidget());

                    List<Object> l = new ArrayList<Object>();
                    l.add(objectDic);
                    sigBlock.setKids(l);
                    sigBlock.setPage(signatureField.getWidget().getPage());

                    sigBlock.setTitle("Signature Table");
                    sigBlock.setParent(docElement);
                    docElement.appendKid(sigBlock);

                    // Create and add Attribute dictionary to mitigate PAC
                    // warning
                    COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject();
                    COSDictionary sub = new COSDictionary();

                    sub.setName("O", "Layout");
                    sub.setName("Placement", "Block");
                    sigBlockDic.setItem(COSName.A, sub);
                    sigBlockDic.setNeedToBeUpdate(true);

                    // Modify number tree
                    PDNumberTreeNode ntn = structureTreeRoot.getParentTree();
                    int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey();
                    if (ntn == null) {
                        ntn = new PDNumberTreeNode(objectDic, null);
                        logger.info("No number-tree-node found!");
                    }

                    COSArray ntnKids = (COSArray) ntn.getCOSDictionary().getDictionaryObject(COSName.KIDS);
                    COSArray ntnNumbers = (COSArray) ntn.getCOSDictionary().getDictionaryObject(COSName.NUMS);

                    if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array

                        //create dictionary with limits and nums array
                        COSDictionary pTreeEntry = new COSDictionary();
                        COSArray limitsArray = new COSArray();
                        //limits for exact one entry
                        limitsArray.add(COSInteger.get(parentTreeNextKey));
                        limitsArray.add(COSInteger.get(parentTreeNextKey));

                        COSArray numsArray = new COSArray();
                        numsArray.add(COSInteger.get(parentTreeNextKey));
                        numsArray.add(sigBlock);

                        pTreeEntry.setItem(COSName.NUMS, numsArray);
                        pTreeEntry.setItem(COSName.LIMITS, limitsArray);

                        PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry,
                                PDNumberTreeNode.class);

                        ntnKids.add(newKidsElement);
                        ntnKids.setNeedToBeUpdate(true);

                        //working
                        //                     List<PDNumberTreeNode> treeRootKids = structureTreeRoot.getParentTree().getKids();
                        //                     PDNumberTreeNode last = (PDNumberTreeNode)treeRootKids.get(treeRootKids.size()-1);
                        //                     COSArray lim1 = (COSArray) last.getCOSDictionary().getDictionaryObject(COSName.LIMITS);
                        //                     lim1.remove(1);
                        //                     lim1.add(1, COSInteger.get(parentTreeNextKey));
                        //                     PDNumberTreeNode verylast = (PDNumberTreeNode)last.getKids().get(last.getKids().size()-1);
                        //                     COSArray numa = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.NUMS);
                        //                     COSArray lim = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.LIMITS);
                        //                     lim.remove(1);
                        //                     lim.add(1, COSInteger.get(parentTreeNextKey));
                        //
                        //                     int size = numa.size();
                        //                     numa.add(size, COSInteger.get(parentTreeNextKey));
                        //                     numa.add(sigBlock);
                        //working end

                    } else if (ntnNumbers != null && ntnKids == null) {

                        int arrindex = ntnNumbers.size();

                        ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey));
                        ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject());

                        ntnNumbers.getCOSObject().setNeedToBeUpdate(true);

                        structureTreeRoot.setParentTree(ntn);

                    } else if (ntnNumbers == null && ntnKids == null) {
                        //document is not pdfua conform before signature creation
                        throw new PdfAsException("error.pdf.sig.pdfua.1");
                    } else {
                        //this is not allowed
                        throw new PdfAsException("error.pdf.sig.pdfua.1");
                    }

                    // set StructureParent for signature field annotation
                    signatureField.getWidget().setStructParent(parentTreeNextKey);

                    //Increase the next Key value in the structure tree root
                    structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1);

                    // add the Tabs /S Element for Tabbing through annots
                    PDPage p = signatureField.getWidget().getPage();
                    p.getCOSDictionary().setName("Tabs", "S");
                    p.getCOSObject().setNeedToBeUpdate(true);

                    //check alternative signature field name
                    if (signatureField != null) {
                        if (signatureField.getAlternateFieldName().equals(""))
                            signatureField.setAlternateFieldName(sigFieldName);
                    }

                    ntn.getCOSDictionary().setNeedToBeUpdate(true);
                    sigBlock.getCOSObject().setNeedToBeUpdate(true);
                    structureTreeRoot.getCOSObject().setNeedToBeUpdate(true);
                    objectDic.getCOSObject().setNeedToBeUpdate(true);
                    docElement.getCOSObject().setNeedToBeUpdate(true);

                }

            } catch (Throwable e) {
                if (signatureProfileSettings.isPDFUA() == true) {
                    logger.error("Could not create PDF-UA conform document!");
                    throw new PdfAsException("error.pdf.sig.pdfua.1", e);
                } else {
                    logger.info("Could not create PDF-UA conform signature");
                }
            }

            try {
                applyFilter(doc, requestedSignature);
            } catch (PDFASError e) {
                throw new PdfAsErrorCarrier(e);
            }

            FileInputStream tmpFileIs = null;

            try {
                tmpFileIs = new FileInputStream(new File(fisTmpFile));
                synchronized (doc) {
                    doc.saveIncremental(tmpFileIs, tmpOutputStream);
                }
                tmpFileIs.close();
            } finally {
                IOUtils.closeQuietly(tmpFileIs);
                if (options != null) {
                    if (options.getVisualSignature() != null) {
                        options.getVisualSignature().close();
                    }
                }
            }
            tmpOutputStream.flush();
            tmpOutputStream.close();
        } finally {
            IOUtils.closeQuietly(tmpOutputStream);
            COSDocument visualSignature = options.getVisualSignature();
            if (visualSignature != null) {
                visualSignature.close();
            }
        }

        FileInputStream readReadyFile = null;
        try {
            readReadyFile = new FileInputStream(new File(fisTmpFile));

            // write to resulting output stream
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // bos.write();
            // bos.close();

            pdfObject.setSignedDocument(StreamUtils.inputStreamToByteArray(readReadyFile));
            readReadyFile.close();
        } finally {
            IOUtils.closeQuietly(readReadyFile);
        }
    } catch (IOException e) {
        logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString());
        throw new PdfAsException("error.pdf.sig.01", e);
    } catch (SignatureException e) {
        logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString());
        throw new PdfAsException("error.pdf.sig.01", e);
    } catch (COSVisitorException e) {
        logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString());
        throw new PdfAsException("error.pdf.sig.01", e);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException e) {
                logger.debug("Failed to close COS Doc!", e);
                // Ignore
            }
        }

        if (fisTmpFile != null) {
            helper.deleteFile(fisTmpFile);
        }
        logger.debug("Signature done!");

    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*from   w  w w . j  a  v a  2  s .  co  m*/
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDPage.PAGE_SIZE_A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, false, false);
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, false, false);
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);
        List<PDPage> pages = new ArrayList<PDPage>();
        visualDoc.getDocumentCatalog().getPages().getAllKids(pages);

        PDPage firstPage = pages.get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

License:EUPL

public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature,
        PDFASSignatureInterface genericSigner) throws PdfAsException {
    //String fisTmpFile = null;

    PDFAsVisualSignatureProperties properties = null;

    if (!(genericPdfObject instanceof PDFBOXObject)) {
        // tODO:// ww  w.  j  av a2 s.c o m
        throw new PdfAsException();
    }

    PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject;

    if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) {
        // tODO:
        throw new PdfAsException();
    }

    PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner;

    String pdfaVersion = null;

    PDDocument doc = null;
    SignatureOptions options = new SignatureOptions();
    COSDocument visualSignatureDocumentGuard = null;
    try {

        doc = pdfObject.getDocument();

        SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter
                .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings());

        TablePos tablePos = null;

        if (signaturePlaceholderData != null) {
            // Placeholder found!
            logger.info("Placeholder data found.");
            if (signaturePlaceholderData.getProfile() != null) {
                logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile());
                requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile());
            }

            tablePos = signaturePlaceholderData.getTablePos();
            if (tablePos != null) {

                SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                        .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

                float minWidth = signatureProfileConfiguration.getMinWidth();

                if (minWidth > 0) {
                    if (tablePos.getWidth() < minWidth) {
                        tablePos.width = minWidth;
                        logger.debug("Correcting placeholder with to minimum width {}", minWidth);
                    }
                }
                logger.debug("Placeholder Position set to: " + tablePos.toString());
            }
        }

        PDSignature signature = new PDSignature();
        signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default
        // filter
        signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        /*
         * Check if input document is PDF-A conform
         *
        if (signatureProfileSettings.isPDFA()) {
           // TODO: run preflight parser
           runPDFAPreflight(pdfObject.getOriginalDocument());
        }
        */

        ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus());
        String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"),
                signatureProfileSettings);

        signature.setName(signerName);

        // take signing time from provided signer...
        signature.setSignDate(signer.getSigningDate());
        // ...and update operation status in order to use exactly this date for the complete signing process
        requestedSignature.getStatus().setSigningDate(signer.getSigningDate());

        String signerReason = signatureProfileSettings.getSigningReason();

        if (signerReason == null) {
            signerReason = "PAdES Signature";
        }

        signature.setReason(signerReason);
        logger.debug("Signing reason: " + signerReason);

        logger.debug("Signing @ " + signer.getSigningDate().getTime().toString());
        // the signing date, needed for valid signature
        // signature.setSignDate(signer.getSigningDate());

        signer.setPDSignature(signature);

        int signatureSize = 0x1000;
        try {
            String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE);
            if (reservedSignatureSizeString != null) {
                signatureSize = Integer.parseInt(reservedSignatureSizeString);
            }
            logger.debug("Reserving {} bytes for signature", signatureSize);
        } catch (NumberFormatException e) {
            logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE);
        }
        options.setPreferredSignatureSize(signatureSize);

        if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) {
            pdfaVersion = getPDFAVersion(doc);
            signatureProfileSettings.setPDFAVersion(pdfaVersion);
        }

        // Is visible Signature
        if (requestedSignature.isVisual()) {
            logger.debug("Creating visual signature block");

            SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                    .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

            if (tablePos == null) {
                // ================================================================
                // PositioningStage (visual) -> find position or use
                // fixed
                // position

                String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition();

                TablePos signaturePos = null;

                String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();

                if (signaturePosString != null) {
                    logger.debug("using signature Positioning: " + signaturePos);
                    signaturePos = new TablePos(signaturePosString);
                }

                logger.debug("using Positioning: " + posString);

                if (posString != null) {
                    // Merge Signature Position
                    tablePos = new TablePos(posString, signaturePos);
                } else {
                    // Fallback to signature Position!
                    tablePos = signaturePos;
                }

                if (tablePos == null) {
                    // Last Fallback default position
                    tablePos = new TablePos();
                }
            }

            //Legacy Modes not supported with pdfbox2 anymore
            //            boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning();
            //            boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning();

            // create Table describtion
            Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                    requestedSignature);

            IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

            IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

            /*
             * PDDocument originalDocument = PDDocument .load(new
             * ByteArrayInputStream(pdfObject.getStatus()
             * .getPdfObject().getOriginalDocument()));
             */

            PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, "",
                    doc, visualObject, pdfObject.getStatus().getSettings());

            logger.debug("Positioning: {}", positioningInstruction.toString());

            if (positioningInstruction.isMakeNewPage()) {
                int last = doc.getNumberOfPages() - 1;
                PDDocumentCatalog root = doc.getDocumentCatalog();
                PDPage lastPage = root.getPages().get(last);
                root.getPages().getCOSObject().setNeedToBeUpdated(true);
                PDPage p = new PDPage(lastPage.getMediaBox());
                p.setResources(new PDResources());
                p.setRotation(lastPage.getRotation());
                doc.addPage(p);
            }

            // handle rotated page
            int targetPageNumber = positioningInstruction.getPage();
            logger.debug("Target Page: " + targetPageNumber);
            PDPage targetPage = doc.getPages().get(targetPageNumber - 1);
            int rot = targetPage.getRotation();
            logger.debug("Page rotation: " + rot);
            // positioningInstruction.setRotation(positioningInstruction.getRotation()
            // + rot);
            logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation());

            SignaturePositionImpl position = new SignaturePositionImpl();
            position.setX(positioningInstruction.getX());
            position.setY(positioningInstruction.getY());
            position.setPage(positioningInstruction.getPage());
            position.setHeight(visualObject.getHeight());
            position.setWidth(visualObject.getWidth());

            requestedSignature.setSignaturePosition(position);

            properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject,
                    (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings);

            properties.buildSignature();

            /*
             * ByteArrayOutputStream sigbos = new
             * ByteArrayOutputStream();
             * sigbos.write(StreamUtils.inputStreamToByteArray
             * (properties .getVisibleSignature())); sigbos.close();
             */

            if (signaturePlaceholderData != null) {
                // Placeholder found!
                // replace placeholder

                URL fileUrl = PADESPDFBOXSigner.class.getResource("/placeholder/empty.jpg");

                PDImageXObject img = PDImageXObject.createFromFile(fileUrl.getPath(), doc);

                img.getCOSObject().setNeedToBeUpdated(true);
                //                     PDDocumentCatalog root = doc.getDocumentCatalog();
                //                     PDPageNode rootPages = root.getPages();
                //                     List<PDPage> kids = new ArrayList<PDPage>();
                //                     rootPages.getAllKids(kids);
                int pageNumber = positioningInstruction.getPage();
                PDPage page = doc.getPages().get(pageNumber - 1);

                logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());
                COSDictionary xobjectsDictionary = (COSDictionary) page.getResources().getCOSObject()
                        .getDictionaryObject(COSName.XOBJECT);
                xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img);
                xobjectsDictionary.setNeedToBeUpdated(true);
                page.getResources().getCOSObject().setNeedToBeUpdated(true);
                logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName());

            }

            if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) {
                PDDocumentCatalog root = doc.getDocumentCatalog();
                COSBase base = root.getCOSObject().getItem(COSName.OUTPUT_INTENTS);
                if (base == null) {
                    InputStream colorProfile = null;
                    try {
                        colorProfile = PDDocumentCatalog.class
                                .getResourceAsStream("/icm/sRGB Color Space Profile.icm");

                        try {
                            PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
                            oi.setInfo("sRGB IEC61966-2.1");
                            oi.setOutputCondition("sRGB IEC61966-2.1");
                            oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
                            oi.setRegistryName("http://www.color.org");

                            root.addOutputIntent(oi);
                            root.getCOSObject().setNeedToBeUpdated(true);
                            logger.info("added Output Intent");
                        } catch (Throwable e) {
                            e.printStackTrace();
                            throw new PdfAsException("Failed to add Output Intent", e);
                        }
                    } finally {
                        IOUtils.closeQuietly(colorProfile);
                    }
                }
            }

            options.setPage(positioningInstruction.getPage());

            options.setVisualSignature(properties.getVisibleSignature());
        }

        visualSignatureDocumentGuard = options.getVisualSignature();

        doc.addSignature(signature, signer, options);

        String sigFieldName = signatureProfileSettings.getSignFieldValue();

        if (sigFieldName == null) {
            sigFieldName = "PDF-AS Signatur";
        }

        int count = PdfBoxUtils.countSignatures(doc, sigFieldName);

        sigFieldName = sigFieldName + count;

        PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm();

        // PDStructureTreeRoot pdstRoot =
        // doc.getDocumentCatalog().getStructureTreeRoot();
        // COSDictionary dic =
        // doc.getDocumentCatalog().getCOSDictionary();
        // PDStructureElement el = new PDStructureElement("Widget",
        // pdstRoot);

        PDSignatureField signatureField = null;
        if (acroFormm != null) {
            @SuppressWarnings("unchecked")
            List<PDField> fields = acroFormm.getFields();

            if (fields != null) {
                for (PDField pdField : fields) {
                    if (pdField != null) {
                        if (pdField instanceof PDSignatureField) {
                            PDSignatureField tmpSigField = (PDSignatureField) pdField;

                            if (tmpSigField.getSignature() != null
                                    && tmpSigField.getSignature().getCOSObject() != null) {
                                if (tmpSigField.getSignature().getCOSObject()
                                        .equals(signature.getCOSObject())) {
                                    signatureField = (PDSignatureField) pdField;

                                }
                            }
                        }
                    }
                }
            } else {
                logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]");
            }

            if (signatureField != null) {
                signatureField.setPartialName(sigFieldName);
            }
            if (properties != null) {
                signatureField.setAlternateFieldName(properties.getAlternativeTableCaption());
            } else {
                signatureField.setAlternateFieldName(sigFieldName);
            }
        } else {
            logger.warn("Failed to name Signature Field! [Cannot find acroForm!]");
        }

        // PDF-UA
        logger.info("Adding pdf/ua content.");
        try {
            PDDocumentCatalog root = doc.getDocumentCatalog();
            PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot();
            if (structureTreeRoot != null) {
                logger.info("Tree Root: {}", structureTreeRoot.toString());
                List<Object> kids = structureTreeRoot.getKids();

                if (kids == null) {
                    logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document");
                }

                PDStructureElement docElement = null;
                for (Object k : kids) {
                    if (k instanceof PDStructureElement) {
                        docElement = (PDStructureElement) k;
                        break;

                    }
                }

                PDStructureElement sigBlock = new PDStructureElement("Form", docElement);

                // create object dictionary and add as child element
                COSDictionary objectDic = new COSDictionary();
                objectDic.setName("Type", "OBJR");
                objectDic.setItem("Pg", signatureField.getWidget().getPage());
                objectDic.setItem("Obj", signatureField.getWidget());

                List<Object> l = new ArrayList<Object>();
                l.add(objectDic);
                sigBlock.setKids(l);
                sigBlock.setPage(signatureField.getWidget().getPage());

                sigBlock.setTitle("Signature Table");
                sigBlock.setParent(docElement);
                docElement.appendKid(sigBlock);

                // Create and add Attribute dictionary to mitigate PAC
                // warning
                COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject();
                COSDictionary sub = new COSDictionary();

                sub.setName("O", "Layout");
                sub.setName("Placement", "Block");
                sigBlockDic.setItem(COSName.A, sub);
                sigBlockDic.setNeedToBeUpdated(true);

                // Modify number tree
                PDNumberTreeNode ntn = structureTreeRoot.getParentTree();
                int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey();
                if (ntn == null) {
                    ntn = new PDNumberTreeNode(objectDic, null);
                    logger.info("No number-tree-node found!");
                }

                COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS);
                COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS);

                if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array

                    //create dictionary with limits and nums array
                    COSDictionary pTreeEntry = new COSDictionary();
                    COSArray limitsArray = new COSArray();
                    //limits for exact one entry
                    limitsArray.add(COSInteger.get(parentTreeNextKey));
                    limitsArray.add(COSInteger.get(parentTreeNextKey));

                    COSArray numsArray = new COSArray();
                    numsArray.add(COSInteger.get(parentTreeNextKey));
                    numsArray.add(sigBlock);

                    pTreeEntry.setItem(COSName.NUMS, numsArray);
                    pTreeEntry.setItem(COSName.LIMITS, limitsArray);

                    PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class);

                    ntnKids.add(newKidsElement);
                    ntnKids.setNeedToBeUpdated(true);

                } else if (ntnNumbers != null && ntnKids == null) {

                    int arrindex = ntnNumbers.size();

                    ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey));
                    ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject());

                    ntnNumbers.setNeedToBeUpdated(true);

                    structureTreeRoot.setParentTree(ntn);

                } else if (ntnNumbers == null && ntnKids == null) {
                    //document is not pdfua conform before signature creation
                    throw new PdfAsException("error.pdf.sig.pdfua.1");
                } else {
                    //this is not allowed
                    throw new PdfAsException("error.pdf.sig.pdfua.1");
                }

                // set StructureParent for signature field annotation
                signatureField.getWidget().setStructParent(parentTreeNextKey);

                //Increase the next Key value in the structure tree root
                structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1);

                // add the Tabs /S Element for Tabbing through annots
                PDPage p = signatureField.getWidget().getPage();
                p.getCOSObject().setName("Tabs", "S");
                p.getCOSObject().setNeedToBeUpdated(true);

                //check alternative signature field name
                if (signatureField != null) {
                    if (signatureField.getAlternateFieldName().equals(""))
                        signatureField.setAlternateFieldName(sigFieldName);
                }

                ntn.getCOSObject().setNeedToBeUpdated(true);
                sigBlock.getCOSObject().setNeedToBeUpdated(true);
                structureTreeRoot.getCOSObject().setNeedToBeUpdated(true);
                objectDic.setNeedToBeUpdated(true);
                docElement.getCOSObject().setNeedToBeUpdated(true);

            }
        } catch (Throwable e) {
            if (signatureProfileSettings.isPDFUA() == true) {
                logger.error("Could not create PDF-UA conform document!");
                throw new PdfAsException("error.pdf.sig.pdfua.1", e);
            } else {
                logger.info("Could not create PDF-UA conform signature");
            }
        }

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            synchronized (doc) {
                doc.saveIncremental(bos);
                byte[] outputDocument = bos.toByteArray();

                /*
                Check if resulting pdf is PDF-A conform
                 */
                //if (signatureProfileSettings.isPDFA()) {
                //   // TODO: run preflight parser
                //   runPDFAPreflight(outputDocument);
                //}

                pdfObject.setSignedDocument(outputDocument);
            }

        } finally {
            if (options != null) {
                if (options.getVisualSignature() != null) {
                    options.getVisualSignature().close();
                }
            }
        }

        System.gc();
    } catch (IOException e) {
        logger.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e);
        throw new PdfAsException("error.pdf.sig.01", e);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException e) {
                logger.debug("Failed to close COS Doc!", e);
                // Ignore
            }
        }

        logger.debug("Signature done!");

    }
}

From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java

License:EUPL

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {//from   w  w w.  j a  va 2  s.c o  m
        PDFBOXObject pdfObject = (PDFBOXObject) status.getPdfObject();

        PDDocument origDoc = new PDDocument();
        origDoc.addPage(new PDPage(PDRectangle.A4));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        origDoc.save(baos);
        baos.close();

        pdfObject.setOriginalDocument(new ByteArrayDataSource(baos.toByteArray()));

        SignatureProfileSettings signatureProfileSettings = TableFactory
                .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings());

        // create Table describtion
        Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(),
                requestedSignature);

        IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings());

        IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main);

        SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus()
                .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID());

        String signaturePosString = signatureProfileConfiguration.getDefaultPositioning();
        PositioningInstruction positioningInstruction = null;
        if (signaturePosString != null) {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(signaturePosString), "",
                    origDoc, visualObject, pdfObject.getStatus().getSettings());
        } else {
            positioningInstruction = Positioning.determineTablePositioning(new TablePos(), "", origDoc,
                    visualObject, pdfObject.getStatus().getSettings());
        }

        origDoc.close();

        SignaturePositionImpl position = new SignaturePositionImpl();
        position.setX(positioningInstruction.getX());
        position.setY(positioningInstruction.getY());
        position.setPage(positioningInstruction.getPage());
        position.setHeight(visualObject.getHeight());
        position.setWidth(visualObject.getWidth());

        requestedSignature.setSignaturePosition(position);

        PDFAsVisualSignatureProperties properties = new PDFAsVisualSignatureProperties(
                pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject,
                positioningInstruction, signatureProfileSettings);

        properties.buildSignature();
        PDDocument visualDoc;
        synchronized (PDDocument.class) {
            visualDoc = PDDocument.load(properties.getVisibleSignature());
        }
        // PDPageable pageable = new PDPageable(visualDoc);

        PDPage firstPage = visualDoc.getDocumentCatalog().getPages().get(0);

        float stdRes = 72;
        float targetRes = resolution;
        float factor = targetRes / stdRes;

        int targetPageNumber = 0;//TODO: is this always the case
        PDFRenderer pdfRenderer = new PDFRenderer(visualDoc);
        BufferedImage outputImage = pdfRenderer.renderImageWithDPI(targetPageNumber, targetRes, ImageType.ARGB);

        //BufferedImage outputImage = firstPage.convertToImage(BufferedImage.TYPE_4BYTE_ABGR, (int) targetRes);

        BufferedImage cutOut = new BufferedImage((int) (position.getWidth() * factor),
                (int) (position.getHeight() * factor), BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D graphics = (Graphics2D) cutOut.getGraphics();

        graphics.drawImage(outputImage, 0, 0, cutOut.getWidth(), cutOut.getHeight(), (int) (1 * factor),
                (int) (outputImage.getHeight() - ((position.getHeight() + 1) * factor)),
                (int) ((1 + position.getWidth()) * factor), (int) (outputImage.getHeight()
                        - ((position.getHeight() + 1) * factor) + (position.getHeight() * factor)),
                null);
        return cutOut;
    } catch (PdfAsException e) {
        logger.warn("PDF-AS  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    } catch (Throwable e) {
        logger.warn("Unexpected Throwable  Exception", e);
        throw ErrorExtractor.searchPdfAsError(e, status);
    }
}

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$print</h3>//from www.  j  a v a  2 s.  c o m
 * <p/>
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param title Is a string which will be printed as title in the PDF Document.
 * @param text Is a string which will be printed as message in the PDF Document.
 */
public void print(String title, String text) throws IOException, COSVisitorException {

    //creates a new PDDocument object
    PDDocument document = new PDDocument();
    //create a page to the document
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    //rectangle is for sizes (height and width) of page
    PDRectangle rectangle = page1.getMediaBox();
    //add page to document
    document.addPage(page1);

    //fonts for the document are implemented here
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate which line you are in the document right now
    int line = 0;

    try {
        //create the content stream which will write into the document
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //always use all these lines for entering new text into the document
        //move textToPosition will set the cursor to the current position
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString(title + ":");
        stream.endText();

        //calculates the correct place and then writes the whole text into the PDF-Document
        int start = 0;
        int end = text.length();
        while (start < end) {
            String tobePrinted;
            if ((end - start) > MAX_CHARACTERS_PER_LINE) {
                int tempEnd = start + MAX_CHARACTERS_PER_LINE;
                while (text.charAt(tempEnd) != ' ') {
                    ++tempEnd;
                }
                tobePrinted = text.substring(start, start = ++tempEnd);

            } else {
                tobePrinted = text.substring(start);
                start = start + MAX_CHARACTERS_PER_LINE;
            }
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(tobePrinted);
            stream.endText();

        }
        //print oculus image into pdf file
        BufferedImage awtImage = ImageIO
                .read(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/res/oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);

        //close stream afterwards
        stream.close();

        //save document and close document
        document.save(
                "/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/"
                        + title + ".pdf");
        document.close();
        //open document with standard application for the file
        Desktop.getDesktop().open(new File(
                "/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/"
                        + title + ".pdf"));
    } catch (IOException | COSVisitorException e) {
        throw e;
    }
}

From source file:at.oculus.teamf.technical.printing.Printer.java

License:Open Source License

/**
 * <h3>$printPrescription</h3>
 * <p/>// ww w  .  ja  va 2s  .  co  m
 * <b>Description:</b>
 * <p/>
 * This method prints the given parameters into a PDF-Document and opens the file with the standard program.
 * <p/>
 * <b>Parameter</b>
 *
 * @param iPrescription Is an Interface of a prescription from which all the information will be printed into
 *                      a PDF-File and then started with standard application from OS.
 */
public void printPrescription(IPrescription iPrescription, IDoctor iDoctor) throws COSVisitorException,
        IOException, CantGetPresciptionEntriesException, NoPrescriptionToPrintException {
    if (iPrescription == null) {
        throw new NoPrescriptionToPrintException();
    }

    //instantiate a new document, create a page and add the page to the document
    PDDocument document = new PDDocument();
    PDPage page1 = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rectangle = page1.getMediaBox();
    document.addPage(page1);

    //create fonts for the document
    PDFont fontPlain = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    //running variable to calculate current line
    int line = 0;

    try {
        //new Stream to print into the file
        PDPageContentStream stream = new PDPageContentStream(document, page1);

        //print header (headlining)
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT, rectangle.getHeight() - SPACING_TOP);
        stream.drawString("Prescription:");
        stream.endText();

        //get patient to print data from
        IPatient iPatient = iPrescription.getPatient();

        //write data from patient
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iPatient.getFirstName() + " " + iPatient.getLastName());
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        /* -- Team D: Add check on null -- */
        stream.drawString(iPatient.getBirthDay() == null ? "" : iPatient.getBirthDay().toString());
        /* -- -- -- */
        stream.endText();

        if (iPatient.getStreet() != null) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getStreet());
            stream.endText();
        }

        if ((iPatient.getPostalCode() != null) && (iPatient.getCity() != null)) {
            stream.beginText();
            stream.setFont(fontPlain, 12);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString(iPatient.getPostalCode() + ", " + iPatient.getCity());
            stream.endText();
        }

        //next row
        ++line;

        //write data from doctor
        stream.beginText();
        stream.setFont(fontBold, 14);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Prescription issued from doctor:");
        stream.endText();

        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString(iDoctor.getTitle() + " " + iDoctor.getFirstName() + " " + iDoctor.getLastName());
        stream.endText();

        //next row
        ++line;

        //print all the entries in the prescription
        if (iPrescription.getPrescriptionEntries().size() > 0) {
            stream.beginText();
            stream.setFont(fontBold, 14);
            stream.moveTextPositionByAmount(SPACING_LEFT,
                    rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
            stream.drawString("Prescription Entries:");
            stream.endText();
            for (IPrescriptionEntry entry : iPrescription.getPrescriptionEntries()) {
                stream.beginText();
                stream.setFont(fontPlain, 12);
                stream.moveTextPositionByAmount(SPACING_LEFT,
                        rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
                stream.drawString("ID: " + entry.getId() + ", " + entry.getMedicine());
                stream.endText();
            }
        }

        //print oculus image into pdf file
        //Not working
        /*BufferedImage awtImage = ImageIO.read(new File("oculus.JPG"));
        PDXObjectImage ximage = new PDPixelMap(document, awtImage);
        float scale = 0.3f; // alter this value to set the image size
        stream.drawXObject(ximage, 380, 780, ximage.getWidth() * scale, ximage.getHeight() * scale);*/

        //signature field

        ++line;
        stream.beginText();
        stream.setFont(fontPlain, 12);
        stream.moveTextPositionByAmount(SPACING_LEFT,
                rectangle.getHeight() - LINE_HEIGHT * (++line) - SPACING_HEADER);
        stream.drawString("Doctor's Signature:");
        stream.endText();

        //print a line for signature field
        stream.setLineWidth(0.5f);
        stream.addLine(SPACING_LEFT, rectangle.getHeight() - LINE_HEIGHT * (line += 2) - SPACING_HEADER,
                SPACING_LEFT + 100, rectangle.getHeight() - LINE_HEIGHT * (line) - SPACING_HEADER);
        stream.closeAndStroke();

        //close the stream
        stream.close();

        //save the document and close it
        document.save("prescription.pdf"); //Todo: position from property file
        document.close();
        //open file with standard OS application
        Desktop.getDesktop().open(new File("prescription.pdf"));

        //Print file directly from standard printer (NOT SUPPORTED ON OCULUS-LINUX -- should be tested first!!!)
        //Desktop.getDesktop().print(new File("/home/oculus/IdeaProjects/Oculus/Technical/src/at/oculus/teamf/technical/printing/output_files/prescription.pdf"));
    } catch (COSVisitorException | CantGetPresciptionEntriesException | IOException e) {
        throw e;
    }
}

From source file:au.org.alfred.icu.pdf.services.factories.ICUDischargeSummaryFactory.java

public static String createContent(PDDocument pdf, String icuVisitNumber, String visitNumber, String patientId,
        String userName, String userId) {
    InputStream is = null;//from   w  ww.  j  a  v a  2 s.  c  o  m
    int yCursor = 137;
    int temp = yCursor;

    DischargeSummaryData data = new DischargeSummaryData();
    PDPage pg_content;
    PDPageContentStream cs;
    String pdfName = DischargeSummaryDataBuilder.buildData(icuVisitNumber, visitNumber, patientId, userName,
            userId, data);
    try {

        pg_content = new PDPage(new PDRectangle(pageWidth, pageHeight));
        cs = new PDPageContentStream(pdf, pg_content);
        yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
        Paragraph para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getFinalDiagnosis());
        para.withColor(Color.BLACK);
        para.withFont(PDType1Font.TIMES_ROMAN, 12);
        para.withWidth(500);
        temp += para.getParaHeight();

        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("Final Diagnosis");
        cs.endText();

        yCursor += para.getFontHeight() * para.getLines().size();

        if (yCursor > (pageHeight - footerHeight)) {
            pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
            cs = new PDPageContentStream(pdf, pg_content);
            yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
        }

        write(cs, para);

        yCursor += 25;
        para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getPresentingHx());
        para.withColor(Color.BLACK);
        para.withFont(PDType1Font.TIMES_ROMAN, 12);
        para.withWidth(500);
        temp = yCursor;
        temp += para.getParaHeight();
        if (temp > (pageHeight - footerHeight)) {
            pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
            cs = new PDPageContentStream(pdf, pg_content);
            yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getPresentingHx());
            para.withColor(Color.BLACK);
            para.withFont(PDType1Font.TIMES_ROMAN, 12);
            para.withWidth(500);

        }

        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("Presenting History");
        cs.endText();
        yCursor += para.getFontHeight() * para.getLines().size();
        write(cs, para);

        yCursor += 25;
        para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getPastHx());
        para.withColor(Color.BLACK);
        para.withFont(PDType1Font.TIMES_ROMAN, 12);
        para.withWidth(500);
        temp = yCursor;
        temp += para.getParaHeight();
        if (temp > (pageHeight - footerHeight)) {
            pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
            cs = new PDPageContentStream(pdf, pg_content);
            yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getPastHx());
            para.withColor(Color.BLACK);
            para.withFont(PDType1Font.TIMES_ROMAN, 12);
            para.withWidth(500);

        }

        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("Past History");
        cs.endText();
        yCursor += para.getFontHeight() * para.getLines().size();
        write(cs, para);

        yCursor += 25;
        para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getDisSumm());
        para.withColor(Color.BLACK);
        para.withFont(PDType1Font.TIMES_ROMAN, 12);
        para.withWidth(500);
        temp = yCursor;
        temp += para.getParaHeight();
        if (temp > (pageHeight - footerHeight)) {
            List<String> pages = new ArrayList<String>();
            int hght = para.getParaHeight();
            System.out.println("height " + hght);
            if (hght > pageHeight - footerHeight) {
                while (hght > pageHeight - footerHeight) {
                    String div = data.getDisSumm().substring(0, data.getDisSumm().length() / 2);
                    Paragraph p = new Paragraph(leftMargin + 5, pageHeight - 147 - 15, div);
                    hght = p.getParaHeight();
                    pages.add(div);
                }
            }
            System.out.println("Pages: " + pages.size());
            if (pages.size() > 1) {
                Iterator itr = pages.iterator();
                while (itr.hasNext()) {
                    String inner = (String) itr.next();
                    pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                    cs = new PDPageContentStream(pdf, pg_content);
                    yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
                    para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, inner);
                    para.withColor(Color.BLACK);
                    para.withFont(PDType1Font.TIMES_ROMAN, 12);
                    para.withWidth(500);
                    cs.beginText();
                    cs.setFont(PDType1Font.TIMES_BOLD, 14);
                    cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
                    cs.setNonStrokingColor(darkGreen);
                    cs.drawString("ICU Stay Summary");
                    cs.endText();
                    yCursor += para.getFontHeight() * para.getLines().size();
                    write(cs, para);
                }
            } else {
                pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                cs = new PDPageContentStream(pdf, pg_content);
                yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
                para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getDisSumm());
                para.withColor(Color.BLACK);
                para.withFont(PDType1Font.TIMES_ROMAN, 12);
                para.withWidth(500);
            }

        }

        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("ICU Stay Summary");
        cs.endText();
        yCursor += para.getFontHeight() * para.getLines().size();
        write(cs, para);

        yCursor += 25;
        para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getPendingInvestigations());
        para.withColor(Color.BLACK);
        para.withFont(PDType1Font.TIMES_ROMAN, 12);
        para.withWidth(500);
        temp = yCursor;
        temp += para.getParaHeight();
        if (temp > (pageHeight - footerHeight)) {
            pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
            cs = new PDPageContentStream(pdf, pg_content);
            yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getPendingInvestigations());
            para.withColor(Color.BLACK);
            para.withFont(PDType1Font.TIMES_ROMAN, 12);
            para.withWidth(500);

        }

        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("Current Pending Investigations");
        cs.endText();
        yCursor += para.getFontHeight() * para.getLines().size();
        write(cs, para);

        yCursor += 25;

        if (yCursor > (pageHeight - footerHeight)) {
            pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
            cs = new PDPageContentStream(pdf, pg_content);
            yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
        }

        if (data.getMicro() != null) {
            int k = 0;
            String[][] table = new String[data.getMicro().size() + 1][6];
            table[k][0] = "Date";
            table[k][1] = "Site";
            table[k][2] = "Organism";
            table[k][3] = "Sensitivity";
            table[k][4] = "";
            table[k][5] = "";
            k++;
            for (Iterator<TblMicroResults> i = data.getMicro().iterator(); i.hasNext();) {
                TblMicroResults m = i.next();
                table[k][0] = m.getMTime() == null ? "N/A"
                        : new SimpleDateFormat("dd/MM/yy").format(m.getMTime());
                table[k][1] = m.getMSite() == null ? "N/A" : m.getMSite();
                table[k][2] = m.getMOrg() == null ? "N/A" : m.getMOrg();
                table[k][3] = m.getMSens() == null ? "N/A" : m.getMSens();
                table[k][4] = "";
                table[k][5] = "";
                k++;
            }

            //System.out.println(yCursor);
            temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);
            if ((yCursor + temp + 30) > (pageHeight - footerHeight)) {
                pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                cs = new PDPageContentStream(pdf, pg_content);
                yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            }
            yCursor += 25;
            cs.beginText();
            cs.setFont(PDType1Font.TIMES_BOLD, 14);
            cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
            cs.setNonStrokingColor(darkGreen);
            cs.drawString("Microbiology Results");
            cs.endText();

            yCursor += 10;

            yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);

        }

        if (data.getOther() != null) {
            int k = 0;
            String[][] table = new String[data.getOther().size() + 1][6];
            table[k][0] = "Date";
            table[k][1] = "Investigation";
            table[k][2] = "Results";
            table[k][3] = "";
            table[k][4] = "";
            table[k][5] = "";
            k++;
            for (Iterator<TblOtherResults> i = data.getOther().iterator(); i.hasNext();) {
                TblOtherResults m = i.next();
                table[k][0] = m.getOTime() == null ? "N/A"
                        : new SimpleDateFormat("dd/MM/yy").format(m.getOTime());
                table[k][1] = m.getOInv() == null ? "N/A" : m.getOInv();
                table[k][2] = m.getOResult() == null ? "N/A" : m.getOResult();
                table[k][3] = "";
                table[k][4] = "";
                table[k][5] = "";
                k++;
            }

            yCursor += 10;
            temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);
            if ((yCursor + temp + 30) > (pageHeight - footerHeight)) {
                pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                cs = new PDPageContentStream(pdf, pg_content);
                yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            }
            yCursor += 25;

            cs.beginText();
            cs.setFont(PDType1Font.TIMES_BOLD, 14);
            cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
            cs.setNonStrokingColor(darkGreen);
            cs.drawString("Other Significant Results");
            cs.endText();
            yCursor += 10;
            yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);

        }

        if (data.getAntibiotics() != null) {
            int k = 0;
            String[][] table = new String[data.getAntibiotics().size() + 1][6];
            table[k][0] = "Start Date";
            table[k][1] = "Suggested End Date";
            table[k][2] = "Antibiotic";
            table[k][3] = "Indication";
            table[k][4] = "";
            table[k][5] = "";

            k++;
            for (Iterator<TblAntibiotic> i = data.getAntibiotics().iterator(); i.hasNext();) {
                TblAntibiotic m = i.next();
                table[k][0] = m.getAStart() == null ? "N/A"
                        : new SimpleDateFormat("dd/MM/yy").format(m.getAStart());
                table[k][1] = m.getAEnd() == null ? "N/A" : m.getAEnd();
                table[k][2] = m.getAAntibiotic() == null ? "N/A" : m.getAAntibiotic();
                table[k][3] = m.getAIndication() == null ? "N/A" : m.getAIndication();
                table[k][4] = "";
                table[k][5] = "";
                k++;
            }

            temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);
            if ((yCursor + temp + 30) > (pageHeight - footerHeight)) {
                pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                cs = new PDPageContentStream(pdf, pg_content);
                yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            }
            yCursor += 25;

            cs.beginText();
            cs.setFont(PDType1Font.TIMES_BOLD, 14);
            cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
            cs.setNonStrokingColor(darkGreen);
            cs.drawString("Current Antibiotic Plans");
            cs.endText();
            yCursor += 10;
            yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);

        }

        if (data.getNeuro() != null) {
            int k = 0;
            String[][] table = new String[data.getNeuro().size() + 1][7];
            table[k][0] = "GCS-E";
            table[k][1] = "GCS-V";
            table[k][2] = "GCS-M";
            table[k][3] = "Upper Motor";
            table[k][4] = "Upper Sensation";
            table[k][5] = "Lower Motor";
            table[k][6] = "Lower Sensation";

            k++;
            for (TblNeurology m : data.getNeuro()) {
                table[k][0] = m.getNGcsE() != null ? m.getNGcsE() : "N/A";
                table[k][1] = m.getNGcsV() != null ? m.getNGcsV() : "N/A";
                table[k][2] = m.getNGcsM() != null ? m.getNGcsM() : "N/A";
                table[k][3] = m.getNUpperMotor() != null ? m.getNUpperMotor() : "N/A";
                table[k][4] = m.getNUpperSens() != null ? m.getNUpperSens() : "N/A";
                table[k][5] = m.getNLowerMotor() != null ? m.getNLowerMotor() : "N/A";
                table[k][6] = m.getNLowerSense() != null ? m.getNLowerSense() : "N/A";
                k++;
            }

            //System.out.println(table[1][1]);

            temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);
            if ((yCursor + temp + 30) > (pageHeight - footerHeight)) {
                pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                cs = new PDPageContentStream(pdf, pg_content);
                yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            }
            yCursor += 25;

            cs.beginText();
            cs.setFont(PDType1Font.TIMES_BOLD, 14);
            cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
            cs.setNonStrokingColor(darkGreen);
            cs.drawString("Current Neurological Exam");
            cs.endText();
            yCursor += 10;
            yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);

        }

        if (data.getProcs() != null) {
            int k = 0;
            String[][] table = new String[data.getProcs().size() + 1][6];
            table[k][0] = "Start Date";
            table[k][1] = "System";
            table[k][2] = "Intervention";
            table[k][3] = "Type";
            table[k][4] = "Site";
            table[k][5] = "Side";
            k++;
            for (Iterator<VwSiss> i = data.getProcs().iterator(); i.hasNext();) {
                VwSiss m = i.next();
                if (m.getSissEndDate() == null) {
                    table[k][0] = new SimpleDateFormat("dd/MM/yy").format(m.getSissStartDate());
                    table[k][1] = m.getSissSystemDesc() == null ? "-" : m.getSissSystemDesc();
                    table[k][2] = m.getSissInterventionDesc() == null ? "-" : m.getSissInterventionDesc();
                    table[k][3] = m.getSissTypeDesc() == null ? "-" : m.getSissTypeDesc();
                    table[k][4] = m.getSissSiteDesc() == null ? "-" : m.getSissSiteDesc();
                    table[k][5] = m.getSissSideDesc() == null ? "-" : m.getSissSideDesc();
                    //System.out.println(table[k][2]);
                    k++;
                }
            }

            temp = getTableHeight(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);
            if ((yCursor + temp + 30) > (pageHeight - footerHeight)) {
                pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                cs = new PDPageContentStream(pdf, pg_content);
                yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            }

            yCursor += 25;
            cs.beginText();
            cs.setFont(PDType1Font.TIMES_BOLD, 14);
            cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
            cs.setNonStrokingColor(darkGreen);
            cs.drawString("Current In-Situ Devices");
            cs.endText();

            yCursor += 10;

            yCursor += drawTable(pg_content, cs, pageHeight - yCursor, leftMargin, table,
                    PDType1Font.TIMES_BOLD, PDType1Font.TIMES_ROMAN, 10);

        }

        yCursor += 25;
        para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getActiveProblems());
        para.withColor(Color.BLACK);
        para.withFont(PDType1Font.TIMES_ROMAN, 12);
        para.withWidth(500);
        temp = yCursor;
        temp += para.getParaHeight();
        if (temp > (pageHeight - footerHeight)) {
            pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
            cs = new PDPageContentStream(pdf, pg_content);
            yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
            para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, data.getActiveProblems());
            para.withColor(Color.BLACK);
            para.withFont(PDType1Font.TIMES_ROMAN, 12);
            para.withWidth(500);

        }

        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("Ongoing Issues & Plan");
        cs.endText();
        yCursor += para.getFontHeight() * para.getLines().size();
        write(cs, para);

        // Add Nursing Plan
        pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
        cs = new PDPageContentStream(pdf, pg_content);
        yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
        cs.beginText();
        cs.setFont(PDType1Font.TIMES_BOLD, 14);
        cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
        cs.setNonStrokingColor(darkGreen);
        cs.drawString("Nursing Plan");
        cs.endText();

        Iterator itr = data.getNursingPlans().keySet().iterator();
        while (itr.hasNext()) {
            String heading = (String) itr.next();
            //System.out.println(heading);
            List<TblCarePlan> plans = (List<TblCarePlan>) data.getNursingPlans().get(heading);
            if (plans.size() > 0) {
                TblCarePlan plan = plans.get(0);
                yCursor += 25;
                para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, plan.getCarePlanNote());
                para.withColor(Color.BLACK);
                para.withFont(PDType1Font.TIMES_ROMAN, 12);
                para.withWidth(500);
                temp = yCursor;
                temp += para.getParaHeight();
                if (temp > (pageHeight - footerHeight)) {
                    pg_content = newPageBuilder(pdf, pg_content, cs, data, yCursor);
                    cs = new PDPageContentStream(pdf, pg_content);
                    yCursor = createNewPage(pdf, pg_content, cs, yCursor, data);
                    para = new Paragraph(leftMargin + 5, pageHeight - yCursor - 15, plan.getCarePlanNote());
                    para.withColor(Color.BLACK);
                    para.withFont(PDType1Font.TIMES_ROMAN, 12);
                    para.withWidth(500);

                }

                cs.beginText();
                cs.setFont(PDType1Font.TIMES_BOLD, 14);
                cs.moveTextPositionByAmount(leftMargin, pageHeight - yCursor);
                cs.setNonStrokingColor(darkGreen);
                cs.drawString(heading + " [" + DateFormat.getInstance().format(plan.getUpdateDate()) + "]");
                cs.endText();
                yCursor += para.getFontHeight() * para.getLines().size();
                write(cs, para);
            }

        }
        cs.close();
        pdf.addPage(pg_content);
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(ICUDischargeSummaryFactory.class.getName()).log(Level.SEVERE, null,
                ex);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(ICUDischargeSummaryFactory.class.getName()).log(Level.SEVERE,
                    null, ex);
        }
    }

    return pdfName;

}