How to convert a file to pdf using pdfbox in java?
<p>I want to extract all the content from a .docx or .txt file and then create a new pdf document which will contain the exact content. The problem is that I want to extract the content with the exact font style , if it's bolded or italic like so...This is what I've done so far:</p>

<pre><code>public class Main {
    public static void main(String[] args) {
        JFileChooser fileChooser = new JFileChooser();
        File file = null;
        do {

            int returnedValue = fileChooser.showOpenDialog(null);
            if (returnedValue == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
            } else break;
        } while (!file.getAbsolutePath().endsWith(".txt") &amp;&amp;
                !file.getAbsolutePath().endsWith(".docx"));
        Controller controller = new Controller();
        controller.createPDF(file);
    }
}

public class Controller {
    public void createPDF(File file) {
        String text = readFileContent(file);
        System.out.println(text);
        try {
            newPdf(text, file);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (COSVisitorException e) {
            e.printStackTrace();
        } catch (FontFormatException e) {
            e.printStackTrace();
        }
    }


    private void newPdf(String text, File file) throws IOException, COSVisitorException, FontFormatException {
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        PDFont font = PDType1Font.COURIER;
        contentStream.setFont(font, 14);
        contentStream.beginText();
        contentStream.setNonStrokingColor(Color.black);
        contentStream.moveTextPositionByAmount(20, 750);
        contentStream.drawString(text);
        contentStream.endText();
        contentStream.close();
        doc.save("doc.pdf");
        doc.close();
    }

    private String readFileContent(File file) {
        String finalText = new String();
        try {
            FileReader fileReader = new FileReader(file.getAbsolutePath());
            BufferedReader br = new BufferedReader(fileReader);
            String line;
            while ((line = br.readLine()) != null)
                finalText += line;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return finalText;
    }
}
</code></pre>