Java

Java 打印PDF文档

2020-08-26  本文已影响0人  Tina_Tang

本文将介绍如何在Java应用程序中打印PDF文档。一般有以下三种常见打印方式:

① 静默打印

② 显示打印对话框打印

③ 打印PDF时自定义纸张大小

使用工具:Free Spire.PDF for Java

创建运行环境:

方式1 通过官网下载组件,解压后将lib文件夹下的Spire.Pdf.jar手动导入IDEA中。具体步骤可参考下图。

方式2通过Maven仓库安装产品及导入相关依赖包。在pom.xml文件中配置Maven仓库路径,及指定Free Spire.PDF for Java的Maven依赖。

<repositories>

        <repository>

            <id>com.e-iceblue</id>

            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>

        </repository>

    </repositories>

<dependencies>

    <dependency>

        <groupId>e-iceblue</groupId>

        <artifactId>spire.pdf.free</artifactId>

        <version>2.6.3</version>

    </dependency>

</dependencies>

配置完成后,在IDEA中,您只需点击"Import Changes"即可导入JAR包;在Eclipse中,则需点击"Save"按钮。

代码示例

静默打印

import com.spire.pdf.*;

import java.awt.print.*;

public class Print {

public static void main(String[] args) {

//加载文档

PdfDocument pdf = new PdfDocument();

pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();

PageFormat loPageFormat  = loPrinterJob.defaultPage();

Paper loPaper = loPageFormat.getPaper();

//删除默认页边距

loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());

//设置打印份数

loPrinterJob.setCopies(2);

loPageFormat.setPaper(loPaper);

loPrinterJob.setPrintable(pdf,loPageFormat);

try { loPrinterJob.print();

        }

catch (PrinterException e) { e.printStackTrace();

        }

    }

}

显示打印对话框打印PDF文档

import com.spire.pdf.*;

import java.awt.print.*;

public class Print {

public static void main(String[] args) {

//加载文档

PdfDocument pdf = new PdfDocument();

pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();

PageFormat loPageFormat  = loPrinterJob.defaultPage();

Paper loPaper = loPageFormat.getPaper();

//删除默认页边距loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());

loPageFormat.setPaper(loPaper);

loPrinterJob.setPrintable(pdf,loPageFormat);

//显示打印对话框

if (loPrinterJob.printDialog()) {

try { loPrinterJob.print();

            }

catch (PrinterException e) { e.printStackTrace();

            }

        }

    }

}

打印时自定义纸张大小

import com.spire.pdf.*;

import java.awt.print.*;

public class Print {

public static void main(String[] args) {

//加载文档

PdfDocument pdf = new PdfDocument();

pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();

PageFormat loPageFormat  = loPrinterJob.defaultPage();

//设置打印纸张大小

Paper loPaper = loPageFormat.getPaper();

loPaper.setSize(500,600);

loPageFormat.setPaper(loPaper);

loPrinterJob.setPrintable(pdf,loPageFormat);

try { loPrinterJob.print();

        }

catch (PrinterException e) { e.printStackTrace();

        }

    }

}

上一篇下一篇

猜你喜欢

热点阅读