PDFBox打印PDF A4格式文档和定制规格条码实例

新接手一个打印终端的项目,要求可以打印A4格式的单据和 70mm * 40mm 规格的条码。整体流程可分两种情况,一种是将打印模板转换为pdf文档二进制数组,进而生成为pdf文档,保存到本地,然后再读取到程序中,打印,最后删除生成的pdf文档(不然随着打印次数的增多,本地磁盘岂不爆满);另一种是省略保存中间步骤,直接将打印模板转换得到的pdf文档二进制数组用于程序打印。显然,第二种...
摘要由CSDN通过智能技术生成

新接手一个打印终端的项目,要求可以打印A4格式的单据和 70mm * 40mm 规格的条码。

整体流程可分两种情况,

一种是将打印模板转换为pdf文档二进制数组,进而生成为pdf文档,保存到本地,然后再读取到程序中,打印,最后删除生成的pdf文档(不然随着打印次数的增多,本地磁盘岂不爆满);

另一种是省略保存中间步骤,直接将打印模板转换得到的pdf文档二进制数组用于程序打印。

显然,第二种情况较为简单,项目最后也是采用的这种。

先说打印A4的情况。

打印A4的情况比较简单,本地有一台惠普的A4打印,直接上代码。

package com.jiuqi.dna.gams.GXH.yndx.printing.util;

import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.print.PrintService;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import net.sf.json.JSONObject;

/**
 * 自助打印终端打印工具类
 * @author wangjiao01
 *
 */
public class PDFPrintUtil {
	
	/**
	 * 获取临时生成的pdf文件路径
	 * @param pdfData
	 * @return
	 */
	public static String getNewPDFPath(byte[] pdfData) {
		
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String newPdfName = df.format(new Date());
		String newPdfPath = "E:\\pdf\\" + newPdfName + ".pdf";// 随具体环境变化
		
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(newPdfPath);
			outputStream.write(pdfData);
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			if(outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return newPdfPath;
	}
	
	/**
	 * 执行打印
	 * @param pdfData pdf文档对应的二进制数组
	 * @param printerName 打印机标识
	 * @param copyCount 打印份数
	 * @return
	 * @throws IOException
	 */
	public static String doPrintByPDFBox(byte[] pdfData, String printerName, Integer copyCount) throws IOException {
		String result = null;
		PDDocument document = null;
		try {
			document = PDDocument.load(pdfData);
			PrinterJob printerJob = PrinterJob.getPrinterJob();
			
			// 查找并设置打印机
			PrintService[] printServices = PrinterJob.lookupPrintServices();
			if(printServices == null || printServices.length == 0) {
				result = getPrintMessage(false, "打印失败,计算机未安装打印机,请检查。");
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值