Search code examples
javapdfsavefilechooser

saving a file fiormat pdf file with java


I am trying to create a pdf file then save it to device using fileChooser It works the saving but when i go to the file to open it it doesn't open here is my code

 FileChooser fc = new FileChooser();
        fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
        fc.setTitle("Save to PDF"
        );
        fc.setInitialFileName("untitled.pdf");
        Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();

        File file = fc.showSaveDialog(stg);
        if (file != null) {
            String str = file.getAbsolutePath();
            FileOutputStream fos = new FileOutputStream(str);
            Document document = new Document();

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
            document.open();
            document.add(new Paragraph("A Hello World PDF document."));
            document.close();
            writer.close();

            fos.flush();

        }

when i open it this is the error showing it says the file is either opened or used by another user


Solution

  • Your code does not close() the FileOutputStream which may cause a resource leak and the document is not properly accessible, maybe even corrupted.

    When you work with a FileOutputStream that implements AutoClosable, you have two options:

    close() the FileOutputStream manually:

    FileChooser fc = new FileChooser();
        fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
        fc.setTitle("Save to PDF");
        fc.setInitialFileName("untitled.pdf");
        Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();
    
        File file = fc.showSaveDialog(stg);
        if (file != null) {
            String str = file.getAbsolutePath();
            FileOutputStream fos = new FileOutputStream(str);
            Document document = new Document();
    
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
            document.open();
            document.add(new Paragraph("A Hello World PDF document."));
            document.close();
            writer.close();
    
            fos.flush();
            /*
             * ONLY DIFFERENCE TO YOUR CODE IS THE FOLLOWING LINE
             */
            fos.close();
        }
    }
    

    or use a try with resources read about that in this post, for example.