本文主要是介绍JRT打印预览实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
JRT客户端部分已经实现了打印、导出Excel部分,之前没实现打印预览部分,因为要自己写打印预览界面,所以留到最后做,经过两晚的努力,实现了打印预览。
效果:
打印预览界面代码
package Monitor.Print;import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import Monitor.Print.PrintProtocol;import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;import javafx.scene.image.Image;/*** 实现打印预览的弹窗和逻辑*/
public class PrintPreview {/*** 舞台*/private Stage curStage = null;/*** 操作打印协议的对象*/private PrintProtocol printProtocol = null;/*** 当前所在页*/TextField txtCurPage = new TextField();/*** 放预览图片*/FlowPane bottom = new FlowPane(500, 1);/*** 打印预览构造函数** @param oper*/public PrintPreview(PrintProtocol oper) {printProtocol = oper;// 创建新的Stage对象,设置标题和尺寸curStage = new Stage();curStage.setTitle("打印预览-由JRT计划提供");curStage.setWidth(1366);curStage.setHeight(768);SplitPane splitPane = new SplitPane();splitPane.setOrientation(Orientation.VERTICAL);// 打印当前页Button btnPrintCur = new Button("打印当前页");btnPrintCur.setStyle("-fx-background-color: #6abfef;");btnPrintCur.setOnMouseClicked(e -> {try {String curPage = txtCurPage.getText();List<Integer> pages = new ArrayList<>();pages.add(Integer.valueOf(curPage) - 1);oper.SetPrintPage(pages);oper.PrintOnece();} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrintCur.setPrefHeight(26);// 打印全部Button btnPrintAll = new Button("打印全部");btnPrintAll.setStyle("-fx-background-color: #6abfef;");btnPrintAll.setOnMouseClicked(e -> {try {List<Integer> pages = new ArrayList<>();for (int i = 0; i < oper.AllPageNum; i++) {pages.add(i);}oper.SetPrintPage(pages);oper.PrintOnece();Hide();} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrintAll.setPrefHeight(26);// 打印奇数页Button btnPrintOdd = new Button("打印奇数页");btnPrintOdd.setStyle("-fx-background-color: #6abfef;");btnPrintOdd.setOnMouseClicked(e -> {try {List<Integer> pages = new ArrayList<>();for (int i = 0; i < oper.AllPageNum; i++) {if (i % 2 == 0) {pages.add(i);}}oper.SetPrintPage(pages);oper.PrintOnece();Hide();} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrintOdd.setPrefHeight(26);// 打印偶数页Button btnPrintEven = new Button("打印偶数页");btnPrintEven.setStyle("-fx-background-color: #6abfef;");btnPrintEven.setOnMouseClicked(e -> {try {List<Integer> pages = new ArrayList<>();for (int i = 0; i < oper.AllPageNum; i++) {if (i % 2 == 1) {pages.add(i);}}oper.SetPrintPage(pages);oper.PrintOnece();Hide();} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrintEven.setPrefHeight(26);// 打印偶数页逆序Button btnPrintEvenRevert = new Button("打印偶逆序");btnPrintEvenRevert.setStyle("-fx-background-color: #6abfef;");btnPrintEvenRevert.setOnMouseClicked(e -> {try {List<Integer> pages = new ArrayList<>();for (int i = oper.AllPageNum - 1; i >= 0; i--) {if (i % 2 == 1) {pages.add(i);}}oper.SetPrintPage(pages);oper.PrintOnece();Hide();} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrintEvenRevert.setPrefHeight(26);//打印开始页TextField txtStart = new TextField();txtStart.setPrefWidth(60);txtStart.setPrefHeight(26);//分割字符Label lab = new Label("-");//打印结束页TextField txtEnd = new TextField();txtEnd.setPrefWidth(60);txtEnd.setPrefHeight(26);// 范围打印Button btnPrintRange = new Button("范围打印");btnPrintRange.setStyle("-fx-background-color: #6abfef;");btnPrintRange.setOnMouseClicked(e -> {try {String start = txtStart.getText();String end = txtEnd.getText();int startInt = Integer.valueOf(start) - 1;int endInt = Integer.valueOf(end) - 1;List<Integer> pages = new ArrayList<>();for (int i = 0; i < oper.AllPageNum; i++) {if (i >= startInt && i <= endInt) {pages.add(i);}}oper.SetPrintPage(pages);oper.PrintOnece();Hide();} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrintRange.setPrefHeight(26);// 打印设置Button btnPrintSetting = new Button("打印设置");btnPrintSetting.setStyle("-fx-background-color: #449be2;");btnPrintSetting.setOnMouseClicked(e -> {oper.job.printDialog();});btnPrintSetting.setPrefHeight(26);//当前页txtCurPage.setPrefWidth(30);txtCurPage.setText("1");txtCurPage.setPrefHeight(26);//所有页Label labAllPage = new Label("/" + oper.AllPageNum);labAllPage.setPrefHeight(26);// 上一页Button btnPrev = new Button("上一页");btnPrev.setStyle("-fx-background-color: #39c6c8;");btnPrev.setOnMouseClicked(e -> {try {String curPage = txtCurPage.getText();int curPageInt = Integer.valueOf(curPage);curPageInt--;if (curPageInt < 1 || curPageInt > oper.AllPageNum) {return;}txtCurPage.setText(curPageInt + "");BufferedImage img = new BufferedImage(867, 1169, BufferedImage.TYPE_INT_ARGB);Graphics g = img.getGraphics();g.setColor(Color.WHITE);g.fillRect(0, 0, img.getWidth(), img.getHeight());oper.PrintHandeler.DrawOnePage(g, curPageInt - 1);Image image = SwingFXUtils.toFXImage(img, null);ImageView onePage = new ImageView(image);bottom.getChildren().clear();bottom.getChildren().add(onePage);} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnPrev.setPrefHeight(26);// 下一页Button btnNext = new Button("下一页");btnNext.setStyle("-fx-background-color: #39c6c8;");btnNext.setOnMouseClicked(e -> {try {String curPage = txtCurPage.getText();int curPageInt = Integer.valueOf(curPage);curPageInt++;if (curPageInt < 1 || curPageInt > oper.AllPageNum) {return;}txtCurPage.setText(curPageInt + "");BufferedImage img = new BufferedImage(867, 1169, BufferedImage.TYPE_INT_ARGB);Graphics g = img.getGraphics();g.setColor(Color.WHITE);g.fillRect(0, 0, img.getWidth(), img.getHeight());oper.PrintHandeler.DrawOnePage(g, curPageInt - 1);Image image = SwingFXUtils.toFXImage(img, null);ImageView onePage = new ImageView(image);bottom.getChildren().clear();bottom.getChildren().add(onePage);} catch (Exception ex) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ex.getMessage());alert.showAndWait();}});btnNext.setPrefHeight(26);HBox top = new HBox(20, btnPrintCur, btnPrintAll, btnPrintOdd, btnPrintEven, btnPrintEvenRevert, txtStart, lab, txtEnd, btnPrintRange, btnPrintSetting, txtCurPage, labAllPage, btnPrev, btnNext);top.setPadding(new Insets(5, 5, 5, 15));top.setPrefHeight(40);top.setMaxHeight(40);bottom.setAlignment(Pos.CENTER);bottom.setPadding(new Insets(10, 10, 10, 15));// 创建一个ScrollPaneScrollPane scrollPane = new ScrollPane();// 设置滚动条的可见性为自动//scrollPane.setScrollbarsVisible(true);scrollPane.setContent(bottom);//画每页的图if (oper.AllPageNum > 0) {for (int i = 0; i < oper.AllPageNum; i++) {try {BufferedImage img = new BufferedImage(867, 1169, BufferedImage.TYPE_INT_ARGB);Graphics g = img.getGraphics();g.setColor(Color.WHITE);g.fillRect(0, 0, img.getWidth(), img.getHeight());oper.PrintHandeler.DrawOnePage(g, i);Image image = SwingFXUtils.toFXImage(img, null);ImageView onePage = new ImageView(image);Label labSP = new Label("---第" + (i + 1) + "页---");bottom.getChildren().add(labSP);bottom.getChildren().add(onePage);} catch (Exception ex) {// 弹出一个信息对话框Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setHeaderText(null);alert.setContentText(ex.getMessage());}}}//bottom.setBackground(new Background(new BackgroundFill(Color.WHITE, new CornerRadii(10), new Insets(10))));splitPane.getItems().addAll(top, scrollPane);Scene scene = new Scene(splitPane);splitPane.setStyle("-fx-background-color: #FAFAFA;");curStage.setOnCloseRequest(event -> {try {} catch (Exception ex) {}});curStage.setScene(scene);curStage.setMaximized(true);curStage.setAlwaysOnTop(true);}/*** 隐藏*/private void Hide() {Platform.runLater(() -> {curStage.hide();});}/*** 展示*/public void Show() {curStage.showAndWait();}
}
打印控制类调整
package Monitor.Print;import JRTPrintDraw.DrawConvert;
import JRTPrintDraw.DrawElement;
import JRTPrintDraw.JRTPrintDrawProtocol;
import JRTPrintDraw.JsonDealUtil;
import JRTPrintDraw.WebService.Parameters;
import Monitor.Print.PrintPreview;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.application.Platform;
import javafx.scene.control.Alert;import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.MediaTray;
import java.awt.*;
import java.awt.print.*;
import java.util.ArrayList;
import java.util.List;public class PrintProtocol implements Printable {/*** 纸张名称*/private String PageName;/*** 打印句柄*/public JRTPrintDrawProtocol PrintHandeler = null;/*** 所有页数*/public int AllPageNum = 0;/*** 通俗理解就是书、文档*/private Book book = new Book();/*** 获取打印服务对象*/PrinterJob job = PrinterJob.getPrinterJob();/*** 设置成竖打*/PageFormat pf = new PageFormat();/*** 得到打印机** @param printerName* @return*/public static PrintService GetPrinter(String printerName) {DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();PrintService printService[] = PrintServiceLookup.lookupPrintServices(psInFormat, pras);PrintService myPrinter = null;//遍历所有打印机如果没有选择打印机或找不到该打印机则调用默认打印机for (PrintService printService2 : printService) {String svcName = printService2.toString();if (svcName.contains(printerName)) {myPrinter = printService2;break;}}if (myPrinter == null) {myPrinter = PrintServiceLookup.lookupDefaultPrintService();return myPrinter;}return myPrinter;}/*** 按打印元素绘制协议实现打印** @param rowids 数据主键* @param userCode 用户* @param paramList 参数* @param connectString 连接串* @param printFlag 打印标识* @param className 调用类名* @param funcName 方法名称*/public PrintProtocol(String rowids, String userCode, String paramList, String connectString, String printFlag, String className, String funcName) throws Exception {try {Parameters para = new Parameters();para.P0 = rowids;para.P1 = userCode;para.P2 = paramList;para.P3 = rowids;String json = JRTPrintDraw.WebService.WebGetData.GetData(connectString, className, funcName, para, null);List<DrawElement> elementList = JsonDealUtil.Json2List(json, DrawElement.class);PrintHandeler = new JRTPrintDrawProtocol();AllPageNum = PrintHandeler.JRTPrintDrawInit(elementList);// 设置打印类job.setPageable(book);pf.setOrientation(PageFormat.PORTRAIT);boolean hasSetPaper = false;//控制打印机的数据if (elementList.get(0).PrintType.contains("PRINTER")) {DrawElement dr = elementList.get(0);//打印机名称String tPrinterName = elementList.get(0).PrintFlag;//选择打印机if (tPrinterName != null && !tPrinterName.isEmpty()) {PrintService printService = GetPrinter(tPrinterName);job.setPrintService(printService);}//设置打印机其他参数if (dr.PrintType.equals("PRINTER")) {//设置打印机宽度int PrinterWidth = DrawConvert.ToInt32(dr.PrintWidth);//设置打印机高度int PrinterHeight = DrawConvert.ToInt32(dr.PrintHeight);PrintHandeler.WriteLog("PRINTER得到纸张宽高:" + PrinterWidth + " " + PrinterHeight);//页面名称PageName = dr.DataField;//停靠String ReportLayout = dr.PrintAlignment;PrintHandeler.WriteLog("PRINTER得打印机名称:" + tPrinterName);//指定打印机送纸来源int iPaperSource = DrawConvert.ToInt32(dr.PrintFont);if (ReportLayout == "Landscape") {pf.setOrientation(PageFormat.LANDSCAPE);PrintHandeler.WriteLog("PRINTER旋转纸张:Landscape");}//宽高大于0就控制if (PrinterWidth > 0 && PrinterHeight > 0) {//通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。Paper paper = new Paper();// 设置纸张大小为 A4 大小(210 mm × 297 mm)int width = PrinterWidth;int height = PrinterHeight;//旋转if (ReportLayout == "Landscape") {int tmp = width;width = height;height = tmp;}double margin = 0;paper.setSize(width, height);paper.setImageableArea(margin, margin, width - 2 * margin, height - 2 * margin);pf.setPaper(paper);hasSetPaper = true;}}}if (hasSetPaper == false) {Paper paper = new Paper();// 设置纸张大小为 A4 大小(210 mm × 297 mm)int width = 794;int height = 1123;double margin = 0;paper.setSize(width, height);paper.setImageableArea(margin, margin, width - 2 * margin, height - 2 * margin);pf.setPaper(paper);}book.append(this, pf, AllPageNum);if (printFlag.contains("PrintPreview")) {Platform.runLater(() -> {try {PrintPreview frmPreview = new PrintPreview(this);frmPreview.Show();} catch (Exception ee) {Alert alert = new Alert(Alert.AlertType.INFORMATION);alert.setTitle("提示");alert.setContentText(ee.getMessage());alert.showAndWait();}});} else {job.print();}} catch (PrinterException e) {e.printStackTrace();}}/*** 设置打印页数** @param pages*/public void SetPrintPage(List<Integer> pages) {PrintHandeler.SetPrintPage(pages);book.append(this, pf, pages.size());}/*** 执行一次打印*/public void PrintOnece() throws Exception {job.print();//恢复页List<Integer> pages = new ArrayList<>();for (int i = 0; i < AllPageNum; i++) {pages.add(i);}SetPrintPage(pages);}/*** 打印画图** @param graphics* @param pageFormat* @param pageIndex* @return* @throws PrinterException*/@Overridepublic int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {// 转换成Graphics2D 拿到画笔Graphics2D g2 = (Graphics2D) graphics;if (PrintHandeler != null) {try {int drawOneRet = PrintHandeler.DrawOnePage(g2, pageIndex);return drawOneRet;} catch (Exception ex) {if (ex.getCause() != null) {PrintHandeler.WriteLog(ex.getCause().getMessage());} else {PrintHandeler.WriteLog(ex.getMessage());}ex.printStackTrace();return 1;}}return 1;}
}
之前做打印设计时候就考虑到后面做预览和在线打印预览要共用绘图,就把打印和绘图分离彻底了
从所有页里提取打印页,这是比老的设计合理的部分,因为合理设计,极大的简化了打印和打印预览的实现逻辑。
打印业务代码
import JRT.Core.Dto.OutParam;
import JRT.Core.Dto.PrintElement;
import JRT.Core.Util.PrintDrawProtocol;
import JRTBLLBase.BaseHttpHandlerNoSession;
import JRTBLLBase.Helper;import java.awt.*;
import java.util.ArrayList;
import java.util.List;/*** 输出符合打印元素绘制协议的打印元素数据,来供打印执行层打印*/
public class PrintBarCodeTest extends BaseHttpHandlerNoSession {/*** 按传入的RowID输出符合打印元素绘制协议的数据来实现打印控制* @param RowID 业务主键* @param P1* @param P2* @param P3* @param P4* @param P5* @param P6* @param P7* @param P8* @param P9* @param P10* @param P11* @param P12* @param P13* @param Session* @param Output* @return*/public String GetData(String RowID, String P1, String P2, String P3, String P4, String P5, String P6, String P7, String P8, String P9, String P10, String P11, String P12, String P13, OutParam Session, OutParam Output) throws Exception{List<PrintElement> retList=new ArrayList<>();//画一个文本retList.add(PrintDrawProtocol.DrawLabel(20,20,"zhanglianzhu","宋体",12,"", null,"","0"));//画一个条码retList.add(PrintDrawProtocol.DrawBarCode(20,50,"0947809",true,5,30,"","宋体",12,"",null,"","0"));//换一根横线retList.add(PrintDrawProtocol.DrawLine(20,70,70,70,1,"",""));//换一根竖线retList.add(PrintDrawProtocol.DrawLine(50,10,50,470,1,"",""));//绘制一个条码retList.add(PrintDrawProtocol.DrawQRCode(20,90,"jbase",90,90));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(20,210,"jbase打印支持","宋体",12,"",null,"","0"));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(20,230,"20231118 22:49","宋体",12,"",null,"","0"));//画一个点retList.add(PrintDrawProtocol.DrawPoint(20,270,10,10,"o",""));retList.add(PrintDrawProtocol.DrawPoint(100,270,10,10,"[]",""));retList.add(PrintDrawProtocol.DrawPoint(200,270,10,10,"<>",""));//画多边形List<Point> pointList=new ArrayList<>();Point p1=new Point();p1.x=10;p1.y=300;pointList.add(p1);Point p2=new Point();p2.x=100;p2.y=310;pointList.add(p2);Point p3=new Point();p3.x=50;p3.y=360;pointList.add(p3);retList.add(PrintDrawProtocol.DrawPoly(pointList,""));//画复选框retList.add(PrintDrawProtocol.DrawCheckBox(10,400,true,30,30));//画单选框retList.add(PrintDrawProtocol.DrawRadio(60,400,true,30,30));//画复选框retList.add(PrintDrawProtocol.DrawCheckBox(110,400,false,30,30));//画单选框retList.add(PrintDrawProtocol.DrawRadio(160,400,false,30,30));//换页retList.add(PrintDrawProtocol.ChangePage());//画一个文本retList.add(PrintDrawProtocol.DrawLabel(10,10,"这是打印的第二页","宋体",12,"", null,"","0"));//画一个条码retList.add(PrintDrawProtocol.DrawBarCode(10,50,"0947809",true,5,30,"","宋体",12,"",null,"","0"));//换一根横线retList.add(PrintDrawProtocol.DrawLine(10,70,70,70,1,"",""));//换一根竖线retList.add(PrintDrawProtocol.DrawLine(50,10,50,470,1,"",""));//绘制一个条码retList.add(PrintDrawProtocol.DrawQRCode(10,90,"jbase",90,90));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(10,210,"jbase打印支持","宋体",12,"",null,"","0"));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(10,230,"20231119","宋体",12,"",null,"","0"));//换页retList.add(PrintDrawProtocol.ChangePage());//画一个文本retList.add(PrintDrawProtocol.DrawLabel(10,10,"这是打印的第三页","宋体",12,"", null,"","0"));//画一个条码retList.add(PrintDrawProtocol.DrawBarCode(10,50,"0947809",true,5,30,"","宋体",12,"",null,"","0"));//换一根横线retList.add(PrintDrawProtocol.DrawLine(10,70,70,70,1,"",""));//换一根竖线retList.add(PrintDrawProtocol.DrawLine(50,10,50,470,1,"",""));//绘制一个条码retList.add(PrintDrawProtocol.DrawQRCode(10,90,"jbase",90,90));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(10,210,"jbase打印支持","宋体",12,"",null,"","0"));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(10,230,"20231119","宋体",12,"",null,"","0"));//换页retList.add(PrintDrawProtocol.ChangePage());//画一个文本retList.add(PrintDrawProtocol.DrawLabel(10,10,"这是打印的第四页","宋体",12,"", null,"","0"));//画一个条码retList.add(PrintDrawProtocol.DrawBarCode(10,50,"0947809",true,5,30,"","宋体",12,"",null,"","0"));//换一根横线retList.add(PrintDrawProtocol.DrawLine(10,70,70,70,1,"",""));//换一根竖线retList.add(PrintDrawProtocol.DrawLine(50,10,50,470,1,"",""));//绘制一个条码retList.add(PrintDrawProtocol.DrawQRCode(10,90,"jbase",90,90));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(10,210,"jbase打印支持","宋体",12,"",null,"","0"));//绘制一个条码retList.add(PrintDrawProtocol.DrawLabel(10,230,"20231206","宋体",12,"",null,"","0"));//先包一个打印元素绘制协议数据生成的工具类来解决元素约束问题,工具类实现了调用工具类得到标签,条码,文本等return Helper.Object2Json(retList);}
}
到此,JRT的设计目标全部实现,开始我还计划JRTWeb部分到过年左右完成的,JRTClient部分3-5年内实现,速度大大超出预期,也正好借着火候一鼓作气把全部实现了。
这篇关于JRT打印预览实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!