This commit is contained in:
lifangliang
2025-06-23 10:33:26 +08:00
commit d04c487851
13 changed files with 829 additions and 0 deletions
@@ -0,0 +1,13 @@
package com.goeing.printserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GoeingPrintServerApplication {
public static void main(String[] args) {
SpringApplication.run(GoeingPrintServerApplication.class, args);
}
}
@@ -0,0 +1,51 @@
package com.goeing.printserver.main;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.goeing.printserver.main.domain.request.PrintRequest;
import com.goeing.printserver.main.utils.PdfPrinter;
import org.springframework.web.bind.annotation.*;
import javax.print.PrintService;
import java.awt.print.PrinterJob;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api")
public class PrintController {
private final String rootPath = "/Users/fl0919/work_space/goeingPrintServer/pdf";
@GetMapping("printerList")
public List<String> printerList(){
PrintService[] printServices = PrinterJob.lookupPrintServices();
Set<String> collect = Arrays.stream(printServices).map(PrintService::getName).collect(Collectors.toSet());
return collect.stream().sorted().collect(Collectors.toList());
}
@PostMapping("print")
public String print(@RequestBody PrintRequest request) {
System.out.println(JSONUtil.toJsonPrettyStr(request));
String fileUrl = request.getFileUrl();
String filePath = rootPath+"/"+IdUtil.getSnowflakeNextId() + ".pdf";
try {
HttpUtil.downloadFile(fileUrl, filePath);
} catch (Exception e) {
System.err.println("There was an error downloading the print file");
throw new RuntimeException("There was an error downloading the print file");
}
try {
PdfPrinter.print(filePath, request.getPrinterName(), request.getPrintOption());
} catch (Exception e) {
throw new RuntimeException(e);
}
return "success";
}
}
@@ -0,0 +1,22 @@
package com.goeing.printserver.main.domain.bo;
import lombok.Data;
@Data
public class PrintOption {
private String size;
private String paper;
private String color;
private String sides;
private String bind;
private double margin; // in inches
private String position;
private String front;
private String back;
private String section;
private String orientation;
private int qty;
}
@@ -0,0 +1,12 @@
package com.goeing.printserver.main.domain.request;
import com.goeing.printserver.main.domain.bo.PrintOption;
import lombok.Data;
@Data
public class PrintRequest {
private String fileUrl;
private String printerName;
private PrintOption printOption;
}
@@ -0,0 +1,152 @@
package com.goeing.printserver.main.utils;// src/main/java/com/example/printer/PdfPrinter.java
import cn.hutool.core.util.StrUtil;
import com.goeing.printserver.main.domain.bo.PrintOption;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.*;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class PdfPrinter {
private static final Map<String, MediaSizeName> PAPER_SIZES = new HashMap<>();
static {
PAPER_SIZES.put("Letter", MediaSizeName.NA_LETTER);//8.5" × 11"
PAPER_SIZES.put("Legal", MediaSizeName.NA_LEGAL);//8.5" × 14"
PAPER_SIZES.put("Tabloid", MediaSizeName.TABLOID);//11" × 17"
}
public static PDDocument print(String pdfPath, String printerName, PrintOption option) throws Exception {
File file = new File(pdfPath);
PDDocument document = PDDocument.load(file);
PrinterJob job = getPrintServiceByName(printerName);
setPageStyle(document, job, option);
return document;
}
public static PrinterJob getPrintServiceByName(String printerName) throws Exception {
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
if (services == null || services.length == 0) {
throw new RuntimeException("No working printers found");
}
for (PrintService service : services) {
if (StrUtil.isNotBlank(printerName)&&service.getName().equalsIgnoreCase(printerName)) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(service);
return job;
}
}
throw new RuntimeException("No name found [" + printerName + "] Printers");
}
private static void setPageStyle(PDDocument document, PrinterJob job, PrintOption option) {
// 创建PageFormat对象
PageFormat pageFormat = new PageFormat();
// 根据打印选项获取纸张大小
Paper paper = getPdfPaper(option.getSize());
// 计算边距大小
double marginPoints = option.getMargin() * 72;
// 计算可打印区域的宽度
double imageableWidth = paper.getWidth() - 2 * marginPoints;
// 计算可打印区域的高度
double imageableHeight = paper.getHeight() - 2 * marginPoints;
// 设置纸张的可打印区域
paper.setImageableArea(marginPoints, marginPoints, imageableWidth, imageableHeight);
// 设置PageFormat对象的纸张
pageFormat.setPaper(paper);
// 根据打印选项设置页面方向
if ("ORI_LANDSCAPE".equalsIgnoreCase(option.getOrientation())) {
pageFormat.setOrientation(PageFormat.LANDSCAPE);
} else {
pageFormat.setOrientation(PageFormat.PORTRAIT);
}
// 创建PrintRequestAttributeSet对象
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
// 设置纸张大小
aset.add(PAPER_SIZES.getOrDefault(option.getSize(), MediaSizeName.NA_LETTER));
// 根据打印选项设置颜色模式
if ("Full Color".equalsIgnoreCase(option.getColor()) || "Cover Letter Color Only".equalsIgnoreCase(option.getColor())) {
aset.add(Chromaticity.COLOR);
} else {
aset.add(Chromaticity.MONOCHROME);
}
// 根据打印选项设置打印面
if ("Double-Sided".equalsIgnoreCase(option.getSides()) || "Two-Sided".equalsIgnoreCase(option.getSides())) {
aset.add(Sides.TWO_SIDED_LONG_EDGE);
} else {
aset.add(Sides.ONE_SIDED);
}
// 设置打印份数
aset.add(new Copies(option.getQty()));
// 设置装订选项
setBindingOption(aset, option.getBind());
// 设置Pageable对象
job.setPageable(new PDFPageable(document));
try {
// 执行打印任务
job.print(aset);
} catch (PrinterException e) {
// 打印异常处理
e.printStackTrace();
}
}
private static Paper getPdfPaper(String size) {
switch (size) {
case "Letter":
return createPaper(8.5 * 72, 11 * 72);
case "Legal":
return createPaper(8.5 * 72, 14 * 72);
case "Tabloid":
return createPaper(8.5 * 72, 16 * 72);
default:
return createPaper(8.5 * 72, 11 * 72);
}
}
private static Paper createPaper(double width, double height) {
Paper paper = new Paper();
paper.setSize(width, height);
return paper;
}
private static void setBindingOption(PrintRequestAttributeSet aset, String bind) {
switch (bind) {
// case "Left":
// aset.add(Binding.LEFT);
// break;
// case "Top":
// aset.add(Binding.TOP);
// break;
case "Staple":
aset.add(Finishings.STAPLE);
break;
default:
break;
}
}
}
@@ -0,0 +1,3 @@
spring.application.name=goeingPrintServer
server.port=9090