简体   繁体   中英

Java printing html as pdf

i have installed doPDF printer driver, and i want to use it from Java to convert HTML to PDF.

PrintService service = getPrinterByName("doPDF");                
DocPrintJob printJob = service.createPrintJob();
Doc document = new SimpleDoc(conn.getInputStream(), DocFlavor.INPUT_STREAM.AUTOSENSE, null);
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
File f = new File(new File(System.getProperty("user.home")),"out.pdf");

attr.add(new Destination(f.toURI()));
printJob.print(document, attr);

The problem is that when i open out.pdf with any pdf reader it says format error and with notepad++ it shows just html.

    private PrintService getPrinterByName(String name) {
    PrintService[] list = getPrintersList();
    if (list.length > 0) {
        for (PrintService service : list) {
            if (service.getName().contains(name)) {
                return service;
            }
        }
    }
    return null;
}

private PrintService[] getPrintersList() {
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);

    return services;
}

I needed this operation silent, and the only way was using OpenOffice API. Any other method requires user input/confirmation.

I used JOD Converter to achieve this. And a little bit more, I convert any file to PDF (ie: any Microsoft Office document, any image, any Open Office document, text, html) and then merge everything to one PDF, with header and footer, including page count, date, user and such. This works both in windows or linux.

Just in case you don't need silent:

    public void print() {
        Desktop desktop = Desktop.getDesktop();
        try {
            desktop.print(new File("web.html"));
        } catch (IOException e) {           
            e.printStackTrace();
        }
    }

User is prompted to select printer, go for PDFCreator or doPDF.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM