Java 打印PDF文檔的3種狀況

如下內容概括了經過Java程序打印PDF文檔時的3種情形。即:html

  •    靜默打印
  •    顯示打印對話框打印
  •    打印PDF時自定義紙張大小

使用工具:Spire.PDF for Javajava

Jar導入api

方法1經過官網下載jar包。maven

方法2經過maven庫導入。參考導入方法工具

 

Java代碼示例

【示例1】靜默打印

即經過使用默認打印機直接打印PDF文檔。打印時,咱們能夠設置打印份數,設置紙張打印頁邊距等。spa

import com.spire.pdf.*;
import java.awt.print.*;

public class Print {
    public static void main(String[] args) {
        //加載文檔
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("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();
        }
    }
}

【示例2】顯示打印對話框打印PDF文檔

import com.spire.pdf.*;
import java.awt.print.*;

public class Print {
    public static void main(String[] args) {
        //加載文檔
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("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();
            }
        }
    }
}

【示例3】打印時自定義紙張大小

import com.spire.pdf.*;
import java.awt.print.*;

public class Print {
    public static void main(String[] args) {
        //加載文檔
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("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();
        } 
    }
}
若是須要更詳細的打印設置,能夠在PrinterJob下設置相應的參數,可參考:https://www.programcreek.com/java-api-examples/java.awt.print.PrinterJob 

擴展:C# 打印PDF文檔的10種方法,請參閱這篇文章。(注:使用Spire.PDF for .NETcode

 

(本文完)orm

相關文章
相關標籤/搜索