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

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

Introduction

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

Prototype

public PDDocument() 

Source Link

Document

Creates an empty PDF document.

Usage

From source file:mail.java

private void ImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImprimirActionPerformed
    try {/*  w  w  w .  j  a v  a  2 s .co m*/
        // TODO add your handling code here:

        PDDocument documento = new PDDocument();
        PDPage paginablanco = new PDPage();
        documento.addPage(paginablanco);
        PDPageContentStream content;
        try {
            content = new PDPageContentStream(documento, paginablanco);

            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 9);
            content.newLineAtOffset(50, 780);
            content.showText("Consejo Profesional de Abogacia");
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 9);
            content.newLineAtOffset(450, 780);
            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, 770);
            content.showText("Direccin: San Martin 457 - Formosa");
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 10);
            content.newLineAtOffset(200, 750);
            content.showText("Estado de Cuenta de Matricula");
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 10);
            content.newLineAtOffset(50, 735);
            content.showText("Matricula N " + idmatricula + "       Nombre:     " + nombre + "," + apellido);//
            content.endText();
            content.beginText();
            content.setFont(PDType1Font.HELVETICA, 10);
            content.newLineAtOffset(100, 705);
            content.showText(
                    "Items       Periodo                        Vencimiento                            Importe");
            content.endText();
            content.addRect(50, 10, 400, 700);

            int j = 0;
            int renglon = 685;

            System.out.println(itemsList.size());

            for (int i = 1; i < itemsList.size(); i++) {

                content.beginText();
                content.setFont(PDType1Font.HELVETICA, 10);
                j++;
                content.newLineAtOffset(100, renglon);
                content.showText("  " + i + "              " + itemsList.get(i).getVencimiento()
                        + "                                " + itemsList.get(i).getPeriodo()
                        + "                                      "
                        + String.valueOf(itemsList.get(i).getImporte()));
                renglon = renglon - 13;
                content.endText();
            }
            content.beginText();
            content.newLineAtOffset(100, renglon - 20);
            DecimalFormatSymbols simbolos = new DecimalFormatSymbols();
            simbolos.setDecimalSeparator('.');
            DecimalFormat decim = new DecimalFormat("0.00", simbolos);

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

            documento.save("matricula_" + idmatricula + ".pdf");
            documento.close();
            System.out.println("guardo archivo matricula_" + idmatricula + ".pdf");
            EnviarMail.setEnabled(true);

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

    } catch (SQLException ex) {
        Logger.getLogger(mail.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:mail.java

private void bonos() throws SQLException {
    //**//www  . j a va  2s.  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:PDFUtil.java

License:Apache License

boolean create() {
    PDDocument doc = new PDDocument();
    doc.addPage(new PDPage());
    File testExist = new File(path);
    if (!testExist.exists()) {
        try {//w  ww .  ja va2s .com
            doc.save(path);
        } catch (IOException e) {
            System.out.println("Path doesn't existed");
            String dir = path.substring(0, path.lastIndexOf('\\'));
            File temp = new File(dir);
            //noinspection ResultOfMethodCallIgnored
            temp.mkdirs();
            try {
                doc.save(path);
            } catch (IOException ignored) {
            }
            return false;
        } finally {
            try {
                doc.close();
            } catch (IOException ignored) {
            }
        }
    } else {
        System.out.println("File existed, can't create file");
        return false;
    }
    return true;
}

From source file:app.Instance.java

/**
 * Ajoute un nouveau fichier//ww w. ja  v  a2 s  . c  om
 *
 * @param fileName
 * @return
 * @throws IOException
 */
public static DocFile addNewFile(String fileName) {
    DocFile docFile = null;

    File file = new File(fileName);

    PDDocument document = new PDDocument();
    document.addPage(new PDPage());

    docFile = new DocFile(docFiles.size(), document, file);

    opened = docFile.getId();
    docFiles.add(docFile);
    return docFile;
}

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 {/* www .jav  a  2s  .com*/
        //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

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {//from w  ww.  j  a  va2  s  .c  o  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

@Override
public Image generateVisibleSignaturePreview(SignParameter parameter, java.security.cert.X509Certificate cert,
        int resolution, OperationStatus status, RequestedSignature requestedSignature) throws PDFASError {
    try {/*  ww w. j a v  a  2 s. co 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.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java

License:EUPL

@Override
public void createTemplate(PDPage page) throws IOException {
    PDDocument template = new PDDocument();

    template.addPage(page);//from   w  w w. j a  v a 2s . c o m
    getStructure().setTemplate(template);
}

From source file:at.medevit.elexis.impfplan.ui.handlers.PrintVaccinationEntriesHandler.java

License:Open Source License

private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
    PDDocumentInformation pdi = new PDDocumentInformation();
    Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
    pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
    pdi.setCreationDate(new GregorianCalendar());
    pdi.setTitle("Impfausweis " + patient.getLabel());

    PDDocument document = new PDDocument();
    document.setDocumentInformation(pdi);

    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    document.addPage(page);//from  ww w .j a v a 2s  .  c  om

    PDRectangle pageSize = page.findMediaBox();
    PDFont font = PDType1Font.HELVETICA_BOLD;

    PDFont subFont = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.setFont(font, 14);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
    contentStream.drawString(patient.getLabel());
    contentStream.endText();

    String dateLabel = sdf.format(Calendar.getInstance().getTime());
    String title = Person.load(mandant.getId()).get(Person.TITLE);
    String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
    contentStream.beginText();
    contentStream.setFont(subFont, 10);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
    contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
    contentStream.endText();

    BufferedImage imageAwt = convertToAWT(image.getImageData());

    PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
    contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
    contentStream.close();

    String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR,
            CoreHub.getWritableUserDir().getAbsolutePath());
    if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
        SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath
                + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
    }
    File outputDir = new File(outputPath);
    File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
    document.save(pdf);
    document.close();
    Desktop.getDesktop().open(pdf);
}

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

License:Open Source License

/**
 * <h3>$print</h3>/*  www.ja 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;
    }
}