使用 Java 打印 Microsoft Office 和 PDF 文件

Har*_*der 5 java printing pdf api ms-office

我正在寻找可以打印 Microsoft Office 和 PDF 文件的 Java API。我还想提供打印规范,即使系统上没有用于打开这些文件的软件。商业图书馆很好。你能推荐一些吗?

Har*_*der 4

对于打印 PDF,这里是免费的最佳解决方案!使用 PDFBox ..

import java.awt.print.PrinterJob;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;


public class PrintPDF
{

    private static final String PASSWORD     = "-password";
    private static final String SILENT       = "-silentPrint";
    private static final String PRINTER_NAME = "-printerName";

    /**
     * private constructor.
     */
    private PrintPDF()
    {
        //static class
    }


    public static void main( String pdfFilepath,String printerindx ) throws Exception
    {
        String password = "";
        String pdfFile = pdfFilepath;
        boolean silentPrint = true;

        PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();            


        if( pdfFile == null )
        {
            usage();
        }

        PDDocument document = null;
        try
        {
            document = PDDocument.load( pdfFile );

            if( document.isEncrypted() )
            {
                document.decrypt( password );
            }
            PrinterJob printJob = PrinterJob.getPrinterJob();

            if(printerindx != null )
            {
                PrintService[] printService = PrinterJob.lookupPrintServices();

                printJob.setPrintService(printService[Integer.parseInt(printerindx)]);


            }
            txt=new PDDocument(document);
            if( silentPrint )
            {


                document.silentPrint( printJob );
            }
            else
            {
                document.print( printJob );
            }
        }
        finally
        {
            if( document != null )
            {
                document.close();
            }
        }
    }

    /**
     * This will print the usage requirements and exit.
     */
    private static void usage()
    {
        System.err.println( "Usage: java org.apache.pdfbox.PrintPDF [OPTIONS] <PDF file>\n" +
                "  -password  <password>        Password to decrypt document\n" +
                "  -silentPrint                 Print without prompting for printer info\n"
        );
        System.exit( 1 );
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 首先将 Office 文档转换为 PDF,然后打印。对于 docx,请尝试 docx4j;对于 xlsx 和旧的二进制格式,请尝试 POI,或者对于非 Java 方法,尝试 OpenOffice。 (2认同)