99maas
99maas

Reputation: 1267

How to open PDF file after being generated from a method

I need your help in opening the generated PDF file automatically after it is being written from a bean. I used iText libraries to write a PDF file and in the below method, I am able to generate the PDF, but I do not know how to open it on the fly for the users.

public static void main(String[] args) throws DocumentException, FileNotFoundException, IOException {

     Document document = new Document(PageSize.A4, 50, 50, 50, 50);

     document.open();

    BaseFont bf = BaseFont.createFont(
        "c://windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font font = new Font(bf, 25);
    PdfPTable table = new PdfPTable(1);
    PdfPCell  cell = new PdfPCell(new Phrase("Good Morning", font));
    cell.setBorder(Rectangle.NO_BORDER);
    cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
    table.addCell(cell);
    document.add(table);

    document.close();      

 }

I want the PDF file to be shown to the user after it is being written to allow him to print the file, so how can I do this?

Upvotes: 3

Views: 6937

Answers (1)

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4463

You can just open the pdf file in the default pdf viewer installed in on the user's machine.

Use this.

Desktop.getDesktop().open(new File("path/to/pdf"));

The file will be opened in the application whichever is installed on the target machine. (Adobe Reader, Nitro PDF, etc.)

Once the file is opened in the default viewer, the user will be able to print it by pressing ctrl + P

Upvotes: 4

Related Questions