首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java打印Microsoft Office和PDF文件

用Java打印Microsoft Office和PDF文件
EN

Stack Overflow用户
提问于 2011-06-02 12:38:30
回答 5查看 5.1K关注 0票数 4

我正在寻找用于Java的API,可以打印Microsoft Office和PDF文件。我也想提供打印规格,即使系统上没有打开这些文件的软件。商业化的库是不错的。你能推荐一些吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-06-03 13:12:14

这里是最好的免费解决方案!!使用PDFBox ..

代码语言:javascript
复制
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 );
    }
}
票数 4
EN

Stack Overflow用户

发布于 2011-06-08 19:46:07

看看OpenOffice的API,里面有一些printing examples provided。OpenOffice可以打开MS Office文档,但是给定的API是非常非常有限的。

票数 1
EN

Stack Overflow用户

发布于 2011-06-10 14:17:19

Aspose有一套用于处理Word、Excel和PDF的产品。您可以导出为不同的格式,包括PDF和打印。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6210439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档