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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

This will close the underlying COSDocument object.

Usage

From source file:fys.StatistiekenController.java

@FXML
private void handleExportToPDFAction(ActionEvent event) throws IOException {
    if ((dateFrom.getText() == null || dateFrom.getText().trim().isEmpty())
            || (dateTo.getText() == null || dateTo.getText().trim().isEmpty())) {
        ErrorLabel.setText(taal[93]);//from w w  w.j  a  v  a2s  .  c o m
        ErrorLabel.setVisible(true);
    } else {
        String dateFromInput = dateFrom.getText();
        String dateToInput = dateTo.getText();
        //Doe dit alleen wanneer er waardes zijn ingevuld.
        lineChart.setAnimated(false);
        pieChart.setAnimated(false);
        //PIECHART
        //Maak alle data en aantallen weer leeg.
        int luggage = 0, foundAmount = 0, lostAmount = 0, destroyAmount = 0, settleAmount = 0,
                neverFoundAmount = 0, depotAmount = 0;
        int jan = 0, feb = 0, mar = 0, apr = 0, mei = 0, jun = 0, jul = 0, aug = 0, sep = 0, okt = 0, nov = 0,
                dec = 0;
        total = 0;
        series.getData().clear();
        pieChartData = FXCollections.observableArrayList();

        //Krijg alle data voor de pietchart die tussen de periode van DateFrom en DateTo ligt.
        try {
            conn = fys.connectToDatabase(conn);
            stmt = conn.createStatement();
            //connectToDatabase(conn, stmt, "test", "root", "root"); 
            String sql = "SELECT status, date, COUNT(status) AS Count FROM bagagedatabase.luggage_status "
                    + "WHERE date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" " + "AND date <= \""
                    + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY status";
            //Voeg alle aantallen per status toe aan variabelen.
            try (ResultSet rs = stmt.executeQuery(sql)) {
                while (rs.next()) {
                    luggage++;
                    //Retrieve by column name
                    foundAmount = (rs.getInt("status") == 0 ? rs.getInt("Count") : foundAmount);
                    lostAmount = (rs.getInt("status") == 1 ? rs.getInt("Count") : lostAmount);
                    destroyAmount = (rs.getInt("status") == 2 ? rs.getInt("Count") : destroyAmount);
                    settleAmount = (rs.getInt("status") == 3 ? rs.getInt("Count") : settleAmount);
                    neverFoundAmount = (rs.getInt("status") == 4 ? rs.getInt("Count") : neverFoundAmount);
                    depotAmount = (rs.getInt("status") == 5 ? rs.getInt("Count") : depotAmount);
                }
            }
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

        //Voeg de waardes toe aan de array.
        pieChartData = FXCollections.observableArrayList(new PieChart.Data(ExportToPdfTexts[15], foundAmount),
                new PieChart.Data(ExportToPdfTexts[16], lostAmount),
                new PieChart.Data(ExportToPdfTexts[17], destroyAmount),
                new PieChart.Data(ExportToPdfTexts[18], settleAmount),
                new PieChart.Data(ExportToPdfTexts[19], neverFoundAmount),
                new PieChart.Data(ExportToPdfTexts[20], depotAmount));

        //Update de titel
        pieChart.setTitle(ExportToPdfTexts[0]);

        //Update de piechart met de gevraagde gegevens.
        pieChart.setData(pieChartData);

        //Voor elke aantal tel ze met elkaar op en sla het op bij total.
        for (PieChart.Data d : pieChart.getData()) {
            total += d.getPieValue();
        }

        //Verander de tekst van elke piechartdata. naar: (aantal statusnaam: percentage).
        pieChartData.forEach(data -> data.nameProperty().bind(Bindings.concat((int) data.getPieValue(), " ",
                data.getName(), ": ",
                (total == 0 || (int) data.getPieValue() == 0) ? 0 : (int) (data.getPieValue() / total * 100),
                "%")));

        //LINECHART
        //Krijg alle data voor de linechart die tussen de periode van DateFrom en DateTo ligt.
        try {
            conn = fys.connectToDatabase(conn);
            stmt = conn.createStatement();
            String sql = "SELECT date, COUNT(date) as Count FROM bagagedatabase.luggage_status "
                    + "WHERE status = 6 AND date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" "
                    + "AND date <= \"" + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY date";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                //Retrieve by column name
                //Voeg alle aantallen per maand toe aan variabelen.
                if (rs.getString("date") != null) {
                    //Krijg van elke date record de maand eruit.
                    String str[] = rs.getString("date").split("-");
                    int month = Integer.parseInt(str[1]);
                    jan = (month == 1 ? jan += rs.getInt("Count") : jan);
                    feb = (month == 2 ? feb += rs.getInt("Count") : feb);
                    mar = (month == 3 ? mar += rs.getInt("Count") : mar);
                    apr = (month == 4 ? apr += rs.getInt("Count") : apr);
                    mei = (month == 5 ? jan += rs.getInt("Count") : mei);
                    jun = (month == 6 ? jun += rs.getInt("Count") : jun);
                    jul = (month == 7 ? jul += rs.getInt("Count") : jul);
                    aug = (month == 8 ? aug += rs.getInt("Count") : aug);
                    sep = (month == 9 ? sep += rs.getInt("Count") : sep);
                    okt = (month == 10 ? okt += rs.getInt("Count") : okt);
                    nov = (month == 11 ? nov += rs.getInt("Count") : nov);
                    dec = (month == 12 ? dec += rs.getInt("Count") : dec);
                }
            }
            rs.close();
            conn.close();
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

        //Update de titel
        lineChart.setTitle(ExportToPdfTexts[1]);

        //Update de linechart naar de waardes die gewenst is.
        series.setName(ExportToPdfTexts[2]);
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[3], jan));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[4], feb));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[5], mar));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[6], apr));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[7], mei));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[8], jun));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[9], jul));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[10], aug));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[11], sep));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[12], okt));
        series.getData().add(new XYChart.Data<>(ExportToPdfTexts[13], nov));
        series.getData().add(new XYChart.Data(ExportToPdfTexts[14], dec));

        //Update de piechart en linechart voordat er een screenshot van genomen wordt.
        lineChart.applyCss();
        lineChart.layout();
        pieChart.applyCss();
        pieChart.layout();

        //Maak een screenshot van de piechart en linechart.
        savePieChartAsPng();
        saveLineChartAsPng();

        try {

            //Krijg de datum van vandaag voor pdf.
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String dateString = dateFormat.format(date);

            //Krijg de content van de template pdf en maake nieuw pdf aan.
            File pdfdoc = new File("src/fys/templates/statisticstemplate.pdf");
            PDDocument document = null;
            document = PDDocument.load(pdfdoc);
            PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
            List<PDField> fields = acroForm.getFields();

            // set the text in the form-field <-- does work
            //Verander voor elk veld de waardes.
            for (PDField field : fields) {
                if (field.getFullyQualifiedName().equals("found")) {
                    field.setValue(String.valueOf(foundAmount));
                }
                if (field.getFullyQualifiedName().equals("lost")) {
                    field.setValue(String.valueOf(lostAmount));
                }
                if (field.getFullyQualifiedName().equals("destroyed")) {
                    field.setValue(String.valueOf(destroyAmount));
                }
                if (field.getFullyQualifiedName().equals("completed")) {
                    field.setValue(String.valueOf(settleAmount));
                }
                if (field.getFullyQualifiedName().equals("neverfound")) {
                    field.setValue(String.valueOf(neverFoundAmount));
                }
                if (field.getFullyQualifiedName().equals("depot")) {
                    field.setValue(String.valueOf(depotAmount));
                }

                if (field.getFullyQualifiedName().equals("jan")) {
                    field.setValue(String.valueOf(jan));
                }
                if (field.getFullyQualifiedName().equals("feb")) {
                    field.setValue(String.valueOf(feb));
                }
                if (field.getFullyQualifiedName().equals("mar")) {
                    field.setValue(String.valueOf(mar));
                }
                if (field.getFullyQualifiedName().equals("apr")) {
                    field.setValue(String.valueOf(apr));
                }
                if (field.getFullyQualifiedName().equals("may")) {
                    field.setValue(String.valueOf(mei));
                }
                if (field.getFullyQualifiedName().equals("jun")) {
                    field.setValue(String.valueOf(jun));
                }
                if (field.getFullyQualifiedName().equals("jul")) {
                    field.setValue(String.valueOf(jul));
                }
                if (field.getFullyQualifiedName().equals("aug")) {
                    field.setValue(String.valueOf(aug));
                }
                if (field.getFullyQualifiedName().equals("sep")) {
                    field.setValue(String.valueOf(sep));
                }
                if (field.getFullyQualifiedName().equals("oct")) {
                    field.setValue(String.valueOf(okt));
                }
                if (field.getFullyQualifiedName().equals("nov")) {
                    field.setValue(String.valueOf(nov));
                }
                if (field.getFullyQualifiedName().equals("dec")) {
                    field.setValue(String.valueOf(dec));
                }
                if (field.getFullyQualifiedName().equals("date")) {
                    field.setValue(String.valueOf(dateString));
                }
                if (field.getFullyQualifiedName().equals("period")) {
                    field.setValue(String.valueOf(dateFromInput + " | " + dateToInput));
                }
            }

            //Retrieving the page
            PDPage page = document.getPage(0);

            //Creating PDImageXObject object
            loginController login = new loginController();
            PDImageXObject pieChartImage = PDImageXObject
                    .createFromFile("src/fys/statistieken/PieChart_" + login.getUsersName() + ".png", document);
            PDImageXObject lineChartImage = PDImageXObject.createFromFile(
                    "src/fys/statistieken/LineChart_" + login.getUsersName() + ".png", document);

            //creating the PDPageContentStream object
            PDPageContentStream contents = new PDPageContentStream(document, page, true, true, true);

            //Drawing the image in the PDF document
            contents.drawImage(pieChartImage, 75, 0, 350, 300);
            contents.drawImage(lineChartImage, 425, 0, 350, 300);

            //Closing the PDPageContentStream object
            contents.close();

            //Sla het docment op.
            document.save("src/fys/statistieken/statistics" + dateFromInput + dateToInput + ".pdf");
            document.close();

            //Verwijder de plaatjes die waren opgeslagen.
            savePieChartAsPng().delete();
            saveLineChartAsPng().delete();

            //Sluit de popup
            home_pane.setDisable(false);
            pdfPane.setVisible(false);
        } catch (IOException ex) {
            Logger.getLogger(StatistiekenController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:generarPDF.GenerarFactura.java

public void imprimirFactura(int facturaID, JFrame dialogo) {
    try {//from   w ww. j  a  v a 2  s .co m
        PDDocument document = crearFactura(facturaID, dialogo);
        document.print();
        document.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(dialogo, "Error al crear la factura", "Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:generarPDF.ReporteFlujosCliente.java

public void imprimirFlujo(ArrayList<Integer> flujosID, int cliente_id, Calendar fechaInicial,
        Calendar fechaFinal) {/*from ww w .j a va  2  s .  com*/
    try {
        PDDocument document = crearInformeMovimientosCliente(flujosID, cliente_id, fechaInicial, fechaFinal);
        document.print();
        document.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error al crear la factura", "Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:geotheme.pdf.generatePDF.java

License:Open Source License

public ByteArrayOutputStream createPDFFromImage(wmsParamBean wpb, String host)
        throws IOException, COSVisitorException {
    PDDocument doc = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    OutputStreamWriter wr = null;
    OutputStreamWriter wl = null;
    URLConnection geoConn = null;
    URLConnection legConn = null;

    int width = 500;
    int height = 500;

    wpb.setBBOX(retainAspectRatio(wpb.getBBOX()));

    StringBuffer sb = new StringBuffer();
    sb.append(this.pdfURL);
    sb.append("&layers=").append(this.pdfLayers);
    sb.append("&bbox=").append(wpb.getBBOX());
    sb.append("&Format=image/jpeg");
    sb.append("&width=").append(width);
    sb.append("&height=").append(height);

    try {//from  w  w  w . j a  v  a2s.  c  o  m
        wpb.setREQUEST("GetMap");
        wpb.setWIDTH(Integer.toString(width));
        wpb.setHEIGHT(Integer.toString(height));

        URL url = new URL(host);
        URL urll = new URL(host);
        URL osm = new URL(sb.toString());

        geoConn = url.openConnection();
        geoConn.setDoOutput(true);

        legConn = urll.openConnection();
        legConn.setDoOutput(true);

        wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
        wr.write(wpb.getURL_PARAM());

        wr.flush();

        wpb.setREQUEST("GetLegendGraphic");
        wpb.setTRANSPARENT("FALSE");
        wpb.setWIDTH("");
        wpb.setHEIGHT("");

        wl = new OutputStreamWriter(legConn.getOutputStream(), "UTF-8");
        wl.write(wpb.getURL_PARAM() + "&legend_options=fontSize:9;");
        wl.flush();

        doc = new PDDocument();

        PDPage page = new PDPage(/*PDPage.PAGE_SIZE_A4*/);
        doc.addPage(page);

        BufferedImage img = ImageIO.read(geoConn.getInputStream());
        BufferedImage leg = ImageIO.read(legConn.getInputStream());

        PDXObjectImage ximage = new PDPixelMap(doc, img);
        PDXObjectImage xlegend = new PDPixelMap(doc, leg);
        PDXObjectImage xosm = new PDJpeg(doc, osm.openStream());

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        PDFont font = PDType1Font.HELVETICA_OBLIQUE;

        contentStream.beginText();
        contentStream.setFont(font, 8);
        contentStream.moveTextPositionByAmount(450, 10);
        Date date = new Date();
        contentStream.drawString(date.toString());
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 8);
        contentStream.moveTextPositionByAmount(10, 10);
        contentStream.drawString("GeoFuse Report: mario.basa@gmail.com");
        contentStream.endText();

        contentStream.drawImage(xosm, 20, 160);
        contentStream.drawImage(ximage, 20, 160);
        contentStream.drawImage(xlegend, width - xlegend.getWidth() - 3, 170);

        contentStream.beginText();
        contentStream.setFont(font, 50);
        contentStream.moveTextPositionByAmount(20, 720);
        contentStream.drawString(wpb.getPDF_TITLE());
        contentStream.endText();

        contentStream.beginText();
        contentStream.setFont(font, 18);
        contentStream.moveTextPositionByAmount(20, 695);
        contentStream.drawString(wpb.getPDF_NOTE());
        contentStream.endText();

        contentStream.setStrokingColor(180, 180, 180);

        float bx[] = { 10f, 10f, 30 + width, 30 + width, 10f };
        float by[] = { 150f, 170 + height, 170 + height, 150f, 150f };
        contentStream.drawPolygon(bx, by);

        contentStream.close();

        doc.save(baos);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (doc != null) {
            doc.close();
        }

        if (wr != null) {
            wr.close();
        }

        if (wl != null) {
            wl.close();
        }
    }

    return baos;
}

From source file:gov.nist.appvet.toolmgr.ToolServiceAdapter.java

License:Open Source License

public static String getPdfReportString(String reportPath, AppInfo appInfo) {
    File file = new File(reportPath);
    PDDocument pddDocument = null;
    PDFTextStripper textStripper = null;
    try {/*from  w w w  . j a v  a2  s .c  o m*/
        pddDocument = PDDocument.load(file);
        textStripper = new PDFTextStripper();
        textStripper.setStartPage(1);
        textStripper.setEndPage(1);
        final String report = textStripper.getText(pddDocument);
        return report;
    } catch (final IOException e) {
        appInfo.log.error(e.getMessage());
        return null;
    } finally {
        if (pddDocument != null) {
            try {
                pddDocument.close();
                pddDocument = null;
            } catch (IOException e) {
                appInfo.log.error(e.getMessage());
            }
        }
        textStripper = null;
        file = null;
    }
}

From source file:GUI.Helper.IOHelper.java

public static boolean getProjectImage(MainController mc) {
    FileChooser fc = new FileChooser();
    fc.setTitle("Select WZITS Project Image");
    fc.getExtensionFilters().addAll(//from  ww  w  .  jav  a2 s .  c o m
            //new FileChooser.ExtensionFilter("All Images", "*.*"),
            new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png"),
            new FileChooser.ExtensionFilter("PDF", "*.pdf"));
    File openFile = fc.showOpenDialog(MainController.getWindow()); //mc.getMainWindow()
    if (openFile != null) {
        if (fc.getSelectedExtensionFilter().getExtensions().get(0).equalsIgnoreCase("*.pdf")) {
            try {
                PDDocument doc = PDDocument.load(openFile);
                PDFRenderer pdfRenderer = new PDFRenderer(doc);
                BufferedImage image = pdfRenderer.renderImage(0);
                //ImageIOUtil.writeImage(image, "C:\\Users\\ltrask\\Documents\\test_image.png", 300);
                Image convertedImage = SwingFXUtils.toFXImage(image, null);
                mc.getProject().setProjPhoto(convertedImage);
                doc.close();
                return true;
            } catch (IOException e) {
                Alert al = new Alert(Alert.AlertType.ERROR);
                al.setTitle("WZITS Tool");
                al.setHeaderText("The selected PDF is password protected");
                al.showAndWait();
            }
        } else {
            try {
                mc.getProject().setProjPhoto(new Image(new FileInputStream(openFile)));
                return true;
            } catch (FileNotFoundException e) {

            }
        }
    }
    return false;
}

From source file:GUI.Helper.IOHelper.java

public static Image openImage(MainController mc) {
    FileChooser fc = new FileChooser();
    fc.setTitle("Select WZITS Project Image");
    fc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("JPG", "*.jpg"),
            new FileChooser.ExtensionFilter("PNG", "*.png"), new FileChooser.ExtensionFilter("PDF", "*.pdf"));
    File openFile = fc.showOpenDialog(mc.getWindow()); //mc.getMainWindow()
    if (openFile != null) {
        if (fc.getSelectedExtensionFilter().getExtensions().get(0).equalsIgnoreCase("*.pdf")) {
            try {
                PDDocument doc = PDDocument.load(openFile);
                PDFRenderer pdfRenderer = new PDFRenderer(doc);
                BufferedImage image = pdfRenderer.renderImage(0);
                Image convertedImage = SwingFXUtils.toFXImage(image, null);
                doc.close();
                return convertedImage;
            } catch (IOException e) {
                Alert al = new Alert(Alert.AlertType.ERROR);
                al.setTitle("WZITS Tool");
                al.setHeaderText("The selected PDF is password protected");
                al.showAndWait();/* w  w  w.j  a  va 2s  .c  o m*/
            }
        } else {
            try {
                return new Image(new FileInputStream(openFile));
            } catch (FileNotFoundException e) {

            }
        }
    }
    return null;
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeSummaryReport(MainController mc) {

    mc.selectStep(6);/*from   w  w w  .  ja v a 2s.  c  o m*/
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                boolean exportSuccess = true;
                try {
                    PDDocument doc = new PDDocument();
                    for (int factSheetIdx = 1; factSheetIdx <= 8; factSheetIdx++) {

                        Node n = mc.goToFactSheet(factSheetIdx, true);
                        MainController.getStage().show();
                        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();

                        PDPage page = new PDPage();
                        doc.addPage(page);

                        PDPageContentStream content = new PDPageContentStream(doc, page);

                        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

                        double prefHeight = wi.getHeight();
                        double prefWidth = wi.getWidth();
                        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);

                        PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
                        int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
                        int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
                        int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
                        drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
                        content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth,
                                drawHeight);
                        content.fillAndStroke();
                        content.close();
                    }
                    drawReportHeaderFooter(doc, mc.getProject(), true);
                    doc.save(saveFile);
                    doc.close();
                } catch (IOException ie) {
                    System.out.println("ERROR");
                    exportSuccess = false;
                }
                if (exportSuccess) {
                    Alert al = new Alert(Alert.AlertType.CONFIRMATION);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export successful");
                    al.showAndWait();
                } else {
                    Alert al = new Alert(Alert.AlertType.WARNING);
                    al.setTitle("WZITS Tool");
                    al.setHeaderText("Fact sheet export failed");
                    al.showAndWait();
                }
                mc.selectStep(6);
            }
        });
    }
}

From source file:GUI.Helper.PDFIOHelper.java

public static void writeStepSummary(MainController mc, int factSheetIdx) {
    Node n = mc.goToFactSheet(factSheetIdx, false);
    FileChooser fc = new FileChooser();
    fc.setTitle("Save WZITS Tool Project");
    fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File (.pdf)", "*.pdf"));
    if (mc.getProject().getSaveFile() != null) {
        File initDir = mc.getProject().getSaveFile().getParentFile();
        if (initDir.isDirectory()) {
            fc.setInitialDirectory(initDir);
        }/* w w  w .  j a v  a  2 s.  com*/
    }
    File saveFile = fc.showSaveDialog(MainController.getWindow()); //mc.getMainWindow()
    if (saveFile != null) {

        BorderPane bp = (BorderPane) ((ScrollPane) n).getContent();
        //Scene scene = new Scene(bp);
        //n.applyCss();
        //bp.applyCss();
        //WritableImage wi = scene.snapshot(null);

        WritableImage wi = bp.snapshot(new SnapshotParameters(), null);

        double prefHeight = wi.getHeight();
        double prefWidth = wi.getWidth();

        BufferedImage bi = SwingFXUtils.fromFXImage(wi, null);
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        boolean exportSuccess = false;
        try {
            //ImageIO.write(bi, "png", new File("test.png"));
            PDPageContentStream content = new PDPageContentStream(doc, page);
            PDImageXObject ximage = LosslessFactory.createFromImage(doc, bi);
            int drawWidth = (int) Math.min(MAX_DRAW_WIDTH, Math.round(WIDTH_FACTOR * prefWidth));
            int drawHeight = (int) Math.round(HEIGHT_FACTOR * prefHeight);
            int numPages = (int) Math.ceil(drawHeight / MAX_DRAW_HEIGHT);
            drawHeight = (int) Math.min(MAX_DRAW_HEIGHT, drawHeight);
            content.drawImage(ximage, MARGIN_LEFT_X, MARGIN_TOP_Y - drawHeight, drawWidth, drawHeight);
            content.fillAndStroke();
            content.close();
            drawReportHeaderFooter(doc, mc.getProject(), true);
            doc.save(saveFile);
            doc.close();
            exportSuccess = true;
        } catch (IOException ie) {
            System.out.println("ERROR");
        }
        if (exportSuccess) {
            Alert al = new Alert(Alert.AlertType.CONFIRMATION);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export successful");
            al.showAndWait();
        } else {
            Alert al = new Alert(Alert.AlertType.WARNING);
            al.setTitle("WZITS Tool");
            al.setHeaderText("Fact sheet export failed");
            al.showAndWait();
        }
    }
}

From source file:helper.PdfText.java

License:Apache License

/**
 * @param pdfFile this file will be extracted.
 * @return the plain text of the pdf//from w w  w.  ja v a  2s  .c o m
 */
public String toString(InputStream pdfFile) {
    PDDocument doc = null;
    try {

        doc = PDDocument.load(pdfFile);
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(doc);
        return text;
    } catch (IOException e) {
        throw new HttpArchiveException(500, e);
    } catch (Exception e) {
        throw new HttpArchiveException(500, e);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException e) {
                logger.warn("", e);
            }
        }
    }
}