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

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

Introduction

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

Prototype

public void save(OutputStream output) throws IOException 

Source Link

Document

This will save the document to an output stream.

Usage

From source file:mail.java

private void ImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImprimirActionPerformed
    try {/*from 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 {
    //**// w  ww.jav a  2  s .co  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:FormFiller.java

private static void fillPdf(HashMap dealerTrackData, String inputFileName, String outputDir,
        String outputFormType) {/*from  w  w w.j ava  2s  .  co m*/
    try {
        PDDocument pdfTemplate = PDDocument.load(new File(inputFileName));

        PDDocumentCatalog docCatalog = pdfTemplate.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();

        List<PDField> fieldList = acroForm.getFields();

        String[] fieldArray = new String[fieldList.size()];
        int i = 0;
        for (PDField sField : fieldList) {
            fieldArray[i] = sField.getFullyQualifiedName();
            i++;
        }

        for (String f : fieldArray) {
            PDField field = acroForm.getField(f);
            String value = (String) dealerTrackData.get(f);
            if (value != null) {
                try {
                    field.setValue(value);
                } catch (IllegalArgumentException e) {
                    System.err.println("Could not insert: " + f + ".");
                }
            }
        }

        pdfTemplate.save(outputDir + "/" + dealerTrackData.get("fullName") + " " + outputFormType + ".pdf");

        // printing - need to look into the long form stuff!
        if (print && !inputFileName.contains("Title Guarantee"))
            printPdf(pdfTemplate, dealerTrackData, inputFileName,
                    inputFileName.contains("Purchase Contract") ? 2 : 1);

        pdfTemplate.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:FormFiller.java

private static void getChaseCreditInfo(JavascriptExecutor jse, HashMap dealerTrackData, WebDriver driver)
        throws InterruptedException, IOException {

    // Home Phone
    String homePhone0 = (String) jse.executeScript("return document.getElementById('iFrm')."
            + "contentWindow.document.body.childNodes[2].contentDocument.getElementById('app_home_phone1').value");
    String homePhone1 = (String) jse.executeScript("return document.getElementById('iFrm')."
            + "contentWindow.document.body.childNodes[2].contentDocument.getElementById('app_home_phone2').value");
    String homePhone2 = (String) jse.executeScript("return document.getElementById('iFrm')."
            + "contentWindow.document.body.childNodes[2].contentDocument.getElementById('app_home_phone3').value");

    dealerTrackData.put("Home (or business) Phone Number",
            "(" + homePhone0 + ")" + " " + homePhone1 + "-" + homePhone2);

    // Business Phone
    String workPhone0 = (String) jse.executeScript("return document.getElementById('iFrm')."
            + "contentWindow.document.body.childNodes[2].contentDocument.getElementById('app_bus_phone1').value");
    String workPhone1 = (String) jse.executeScript("return document.getElementById('iFrm')."
            + "contentWindow.document.body.childNodes[2].contentDocument.getElementById('app_bus_phone2').value");
    String workPhone2 = (String) jse.executeScript("return document.getElementById('iFrm')."
            + "contentWindow.document.body.childNodes[2].contentDocument.getElementById('app_bus_phone3').value");

    dealerTrackData.put("workPhone", "(" + workPhone0 + ")" + " " + workPhone1 + "-" + workPhone2);

    jse.executeScript(/*from www  .j av a2  s. c  o  m*/
            "document.getElementById('iFrm').contentWindow.document.body.childNodes[2].contentDocument."
                    + "getElementsByName('cmdPrint')[0].click()");

    Thread.sleep(4000);
    File chaseCreditApplication;
    String downloadDir = System.getProperty("os.name").toLowerCase().contains("win")
            ? "C:/Users/" + System.getProperty("user.name") + "/Downloads/"
            : "/Users/" + System.getProperty("user.name") + "/Downloads/";
    do {
        chaseCreditApplication = getLatestFileFromDir(downloadDir);
        Thread.sleep(1000);
    } while (chaseCreditApplication == null
            || System.currentTimeMillis() > chaseCreditApplication.lastModified() + 4000);

    PDDocument creditAppTemplate = PDDocument.load(chaseCreditApplication);
    outputDir = makeOutputDir(dealerTrackData);
    creditAppTemplate.save(outputDir + "/" + dealerTrackData.get("fullName") + " " + "Chase Credit App.pdf");

    if (print)
        printPdf(creditAppTemplate, dealerTrackData, "Chase Credit Application", 1);
    creditAppTemplate.close();

}

From source file:ReducePDFSize.java

License:Apache License

public static void main(String[] args) throws IOException {
    if (2 != args.length) {
        throw new RuntimeException("arg0 must be input file, org1 must be output file");
    }//from  www  .  j a  v  a2s . co m
    String in = args[0];
    String out = args[1];
    PDDocument doc = null;

    try {
        doc = PDDocument.load(new File(in));
        doc.setAllSecurityToBeRemoved(true);
        for (COSObject cosObject : doc.getDocument().getObjects()) {
            COSBase base = cosObject.getObject();
            // if it's a stream: decode it, then re-write it using FLATE_DECODE
            if (base instanceof COSStream) {
                COSStream stream = (COSStream) base;
                byte[] bytes;
                try {
                    bytes = new PDStream(stream).toByteArray();
                } catch (IOException ex) {
                    // NOTE: original example code from PDFBox just logged & "continue;"d here, 'skipping' this stream.
                    // If this type of failure ever happens, we can (perhaps) consider (re)ignoring this type of failure?
                    //
                    // IIUC then that will leave the original (non-decoded / non-flated) stream in place?
                    throw new RuntimeException("can't serialize byte[] from: " + cosObject.getObjectNumber()
                            + " " + cosObject.getGenerationNumber() + " obj: " + ex.getMessage(), ex);
                }
                stream.removeItem(COSName.FILTER);
                OutputStream streamOut = stream.createOutputStream(COSName.FLATE_DECODE);
                streamOut.write(bytes);
                streamOut.close();
            }
        }
        doc.getDocumentCatalog();
        doc.save(out);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:SetField.java

License:Apache License

private void setField(String[] args) throws IOException, COSVisitorException {
    PDDocument pdf = null;
    try {/*from   w  w w . j av a  2 s. co m*/
        if (args.length < 3) {
            usage();
        } else {
            SetField example = new SetField();

            pdf = PDDocument.load(args[0]);
            example.setField(pdf, Arrays.copyOfRange(args, 1, args.length));
            pdf.save(args[0] + ".computed.pdf");
        }
    } finally {
        if (pdf != null) {
            pdf.close();
        }
    }
}

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  w w  .j a v a2s.  c  o  m*/
            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:adams.core.io.PDFBox.java

License:Open Source License

/**
 * Saves the PDF document under the specified filename.
 *
 * @param doc      the document to save/* w w w  .  j  av  a 2s  .c  om*/
 * @param file   the file to save the document to
 * @return      true if successfully saved
 */
public static boolean save(PDDocument doc, File file) {
    boolean result;

    try {
        doc.save(file.getAbsoluteFile());
        result = true;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failed to save PDF document to file '" + file + "':", e);
        result = false;
    }

    return result;
}

From source file:algorithm.PDFFileAttacher.java

License:Apache License

private void attachAll(File outputFile, List<File> payloadList) throws IOException {
    PDDocument document = PDDocument.load(outputFile);
    List<PDComplexFileSpecification> fileSpecifications = getFileSpecifications(document, payloadList);
    PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(document.getDocumentCatalog());
    PDEmbeddedFilesNameTreeNode filesTree = namesDictionary.getEmbeddedFiles();
    filesTree = new PDEmbeddedFilesNameTreeNode();
    Map<String, COSObjectable> fileMap = new HashMap<String, COSObjectable>();
    for (int i = 0; i < fileSpecifications.size(); i++) {
        fileMap.put("PericlesMetadata-" + i, fileSpecifications.get(i));
    }//from   w ww . ja  v a2 s . c  o m
    filesTree.setNames(fileMap);
    namesDictionary.setEmbeddedFiles(filesTree);
    document.getDocumentCatalog().setNames(namesDictionary);
    try {
        document.save(outputFile);
    } catch (COSVisitorException e) {
    }
    document.close();
}

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  w w .  j  a  va  2s. co 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;
}