vikram
vikram

Reputation: 69

How to Convert from String into PDF in Java

Currently I am using this code but its throwing PrintJobFlavorException. This is my code help me out fixing this one:

public class PJUtil {
    public static void main(String[] args) throws Exception {
        DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
        Writer output = null;
        String text = "printing in pdfPrinting in Java ";
        File file = new File("C:\\CMPSup_AL_.PDF");
        output = new BufferedWriter(new FileWriter(file));
        output.write(text);
        output.close();
        InputStream is = new BufferedInputStream(new FileInputStream(file));
        PrintService service = PrintServiceLookup.lookupDefaultPrintService();
        DocPrintJob job = service.createPrintJob();
        Doc doc = new SimpleDoc(is, flavor, null);
        PrintJobWatcher pjDone = new PrintJobWatcher(job);
        job.print(doc, null);
        pjDone.waitForDone();
        is.close();
    }
}

and exception is

Exception in thread "main" sun.print.PrintJobFlavorException: invalid flavor
    at sun.print.Win32PrintJob.print(Win32PrintJob.java:327)
    at Collections.PrinterJobUtil.main(PrinterJobUtil.java:89)

Upvotes: 1

Views: 20953

Answers (5)

E Pavan Varma
E Pavan Varma

Reputation: 1

Change DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF to *DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE*.

E Pavan Varma

Upvotes: 0

Thakhani Tharage
Thakhani Tharage

Reputation: 1298

Also take a look on Jasper Reports http://community.jaspersoft.com/project/jasperreports-library

Upvotes: 0

jkysam
jkysam

Reputation: 5789

Just to give you another option for creating PDF files. Try using Apache's PDFBox and take a look at the cookbook. The HelloWorld example shows you how to create a simple PDF document like the one you were trying to create in your sample code.

Upvotes: 0

madth3
madth3

Reputation: 7344

As other have pointed out, you can't just create a file called PDF and print it. If you need to generate PDF then you might take a look at itext.

Upvotes: 2

Shahriar
Shahriar

Reputation: 824

your printer may not support text based representation. Have a look at this article java printing, specially page 5.

Upvotes: 2

Related Questions